/* ─── Customers page — v2 redesign ───────────────────────────────────────────
   Stat-tile filters → search → list rows with contact + review count →
   profile drawer with review history. Overrides window.Customers. */

const CUSTS_V2 = [
  { cid:'#2108', name:'Hgv',              email:'abdulhusain14s@gmail.com', phone:'+61 449 978 693', country:'AU', joined:'13 Dec 2025', reviews:[{p:'Spain Testing',s:5,d:'13/12/2025'}] },
  { cid:'#4569', name:'767',              email:'husain@gmail.com',         phone:'+91 88888 88880', country:'IN', joined:'10 Nov 2025', reviews:[{p:'Spain Testing',s:5,d:'10/11/2025'}] },
  { cid:'#5824', name:'Screenshot test',  email:'hh@gmail.com',             phone:null,              country:'ES', joined:'30 Jun 2025', reviews:[{p:'Spain Testing',s:5,d:'30/05/2026'},{p:'Spain Testing',s:5,d:'26/08/2025'},{p:'USA testing',s:5,d:'30/06/2025'}] },
  { cid:'#0649', name:'Test',             email:'test@gmail.com',           phone:'+91 99999 99999', country:'IN', joined:'02 Jun 2026', reviews:[{p:'Spain Testing',s:4,d:'02/06/2026'}] },
  { cid:'#2007', name:'zahabiya',         email:'zasdfgh@gmail.com',        phone:null,              country:'IN', joined:'25 May 2026', reviews:[{p:'Spain Testing',s:5,d:'25/05/2026'}] },
  { cid:'#5117', name:'ZAhabiya',         email:'zasdfds@gmail.com',        phone:'+1 789 009 8789', country:'US', joined:'31 May 2026', reviews:[{p:'Spain Testing',s:3,d:'31/05/2026'}] },
  { cid:'#0082', name:'Huu',              email:'gg@gmail.com',             phone:null,              country:'ES', joined:'02 Jun 2026', reviews:[{p:'Spain Testing',s:5,d:'02/06/2026'}] },
  { cid:'#6949', name:'Zahabiya test 1',  email:'zahabiay78657@gmail.com',  phone:'+1 678 900 9876', country:'US', joined:'18 Apr 2026', reviews:[{p:'USA testing',s:5,d:'18/04/2026'}] },
  { cid:'#0652', name:'zasddsadas',       email:'sdfghgfd@gmail.com',       phone:'+91 78458 93495', country:'IN', joined:'12 Mar 2026', reviews:[{p:'Brontix Wifi Router',s:4,d:'12/03/2026'}] },
  { cid:'#1065', name:'zahashbiuytfgh',   email:'gfgbnnb@gmail.com',        phone:'+91 85252 85205', country:'IN', joined:'02 Feb 2026', reviews:[{p:'Brontix Wifi Router',s:5,d:'02/02/2026'},{p:'Bedsure Queen Comforter',s:5,d:'14/02/2026'}] },
];

const custHue = c => (parseInt(c.cid.slice(1),10)*7)%360;

function CustomerDrawer({ cust, onClose }) {
  const avg = (cust.reviews.reduce((a,r)=>a+r.s,0)/cust.reviews.length).toFixed(1);
  return (
    <div className="fixed inset-0 z-50 flex justify-end bg-ink/40" onClick={onClose}>
      <div className="w-full max-w-md h-full bg-white shadow-pop overflow-y-auto" onClick={e=>e.stopPropagation()}>
        <div className="px-6 py-5 border-b border-line flex items-center justify-between sticky top-0 bg-white z-10">
          <div className="flex items-center gap-3 min-w-0">
            <span className="w-11 h-11 rounded-full text-white font-bold text-[15px] flex items-center justify-center shrink-0"
                  style={{background:`linear-gradient(135deg, hsl(${custHue(cust)},55%,58%), hsl(${(custHue(cust)+50)%360},50%,44%))`}}>{cust.name[0].toUpperCase()}</span>
            <div className="min-w-0">
              <p className="text-[15px] font-extrabold text-ink truncate">{cust.name}</p>
              <p className="text-[12px] text-ink-muted">{cust.cid} · joined {cust.joined}</p>
            </div>
          </div>
          <button onClick={onClose} className="w-9 h-9 rounded-full text-ink-soft hover:bg-surface-input hover:text-ink flex items-center justify-center transition-colors shrink-0">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M6 6l12 12M18 6L6 18" strokeLinecap="round"/></svg>
          </button>
        </div>
        <div className="p-6 space-y-5">
          <div className="grid grid-cols-2 gap-3">
            <div className="bg-surface-subtle rounded-xl px-4 py-3">
              <p className="text-[11px] font-semibold text-ink-muted uppercase tracking-wide">Reviews</p>
              <p className="font-extrabold text-[20px] text-ink mt-1">{cust.reviews.length}</p>
            </div>
            <div className="bg-surface-subtle rounded-xl px-4 py-3">
              <p className="text-[11px] font-semibold text-ink-muted uppercase tracking-wide">Avg rating</p>
              <p className="font-extrabold text-[20px] text-ink mt-1">{avg} <span className="text-[14px]" style={{color:'#F59E0B'}}>★</span></p>
            </div>
          </div>
          <div>
            <p className="text-[11px] font-bold uppercase tracking-wider text-ink-muted mb-2">Contact</p>
            <div className="rounded-2xl border border-line divide-y divide-line/70">
              <div className="px-4 py-3 flex items-center gap-3 text-[13px]">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-ink-soft shrink-0"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M2 7l10 6 10-6"/></svg>
                <span className="text-ink truncate">{cust.email}</span>
              </div>
              <div className="px-4 py-3 flex items-center gap-3 text-[13px]">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-ink-soft shrink-0"><path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1 1 .4 2 .7 2.9a2 2 0 0 1-.4 2.1L8.1 10a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.4c.9.3 1.9.6 2.9.7a2 2 0 0 1 1.6 2z"/></svg>
                {cust.phone
                  ? <span className="text-ink">{cust.phone}</span>
                  : <span className="text-ink-soft">No phone provided</span>}
              </div>
            </div>
          </div>
          <div>
            <p className="text-[11px] font-bold uppercase tracking-wider text-ink-muted mb-2">Review history</p>
            <div className="space-y-2.5">
              {cust.reviews.map((r,i)=>(
                <div key={i} className="rounded-2xl border border-line px-4 py-3 flex items-center justify-between gap-3">
                  <div className="min-w-0">
                    <p className="text-[13px] font-bold text-ink truncate">{r.p}</p>
                    <p className="text-[11.5px] text-ink-soft mt-0.5">{r.d}</p>
                  </div>
                  <StarsRow n={r.s}/>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function CustomersV2() {
  const [query, setQuery]   = React.useState('');
  const [filter, setFilter] = React.useState('all');   // all | repeat | nophone
  const [open, setOpen]     = React.useState(null);
  const rows = CUSTS_V2
    .filter(c => (c.name+' '+c.email+' '+c.cid).toLowerCase().includes(query.toLowerCase()))
    .filter(c => filter==='all' ? true : filter==='repeat' ? c.reviews.length > 1 : !c.phone);
  const totalReviews = CUSTS_V2.reduce((a,c)=>a+c.reviews.length,0);
  const repeat = CUSTS_V2.filter(c=>c.reviews.length>1).length;
  const avgAll = (CUSTS_V2.reduce((a,c)=>a+c.reviews.reduce((x,r)=>x+r.s,0),0)/totalReviews).toFixed(1);
  const exportBtn = (
    <BtnPrimary icon={
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4">
        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    }>Export CSV</BtnPrimary>
  );
  return (
    <>
      <PageHeader title="Customers" action={exportBtn}/>
      <div className="px-7 py-6 space-y-5">
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <StatTileV2 label="All customers" value={CUSTS_V2.length} sub={`${totalReviews} reviews written`} active={filter==='all'} onClick={()=>setFilter('all')}/>
          <StatTileV2 label="Repeat reviewers" value={repeat} sub="reviewed more than once" active={filter==='repeat'} onClick={()=>setFilter('repeat')}/>
          <StatTileV2 label="Missing phone" value={CUSTS_V2.filter(c=>!c.phone).length} sub="email contact only" active={filter==='nophone'} onClick={()=>setFilter('nophone')}/>
          <StatTileV2 label="Avg rating" value={avgAll + ' ★'} sub="across all reviews" onClick={()=>{}}/>
        </div>
        <SearchInput placeholder="Search by name, email or CID" value={query} onChange={e=>setQuery(e.target.value)}/>
        {rows.length === 0 ? (
          <div className="bg-white rounded-2xl border border-line shadow-soft py-16 text-center">
            <p className="text-[15px] font-bold text-ink">No customers match</p>
            <p className="text-[13px] text-ink-muted mt-1">Try a different search or clear the filter.</p>
            <button onClick={()=>{setQuery('');setFilter('all');}} className="mt-4 text-[13px] font-bold text-brand hover:text-brand-dark">Clear filters</button>
          </div>
        ) : (
          <Card className="overflow-hidden">
            <div className="overflow-x-auto">
            <div className="min-w-[880px]">
            <div className="grid items-center gap-3 px-5 py-3 bg-surface-subtle text-[11px] font-semibold uppercase tracking-wider text-ink-muted" style={{gridTemplateColumns:'minmax(160px,1.2fr) minmax(200px,1.5fr) 56px 100px 104px 96px 76px'}}>
              <span>Customer</span><span>Contact</span><span>Country</span><span>Last review</span><span>Rating</span><span>Reviews</span><span></span>
            </div>
            <div className="divide-y divide-gray-100">
            {rows.map(c => {
              const avg = (c.reviews.reduce((a,r)=>a+r.s,0)/c.reviews.length);
              return (
                <div key={c.cid} className="grid items-center gap-3 px-5 py-3.5 hover:bg-surface-subtle transition-colors" style={{gridTemplateColumns:'minmax(160px,1.2fr) minmax(200px,1.5fr) 56px 100px 104px 96px 76px'}}>
                  <div className="flex items-center gap-3 min-w-0">
                    <span className="w-9 h-9 rounded-full text-white text-[12.5px] font-bold flex items-center justify-center shrink-0"
                          style={{background:`linear-gradient(135deg, hsl(${custHue(c)},55%,58%), hsl(${(custHue(c)+50)%360},50%,44%))`}}>{c.name[0].toUpperCase()}</span>
                    <div className="min-w-0">
                      <p className="text-[13px] font-bold text-ink truncate">{c.name}</p>
                      <p className="text-[11px] text-ink-soft mt-0.5">{c.cid} · joined {c.joined}</p>
                    </div>
                  </div>
                  <div className="min-w-0">
                    <p className="text-[12.5px] text-ink truncate">{c.email}</p>
                    <p className="text-[11.5px] mt-0.5 truncate">{c.phone ? <span className="text-ink-muted">{c.phone}</span> : <span className="text-amber-600 font-semibold">No phone</span>}</p>
                  </div>
                  <span className="inline-flex w-fit text-[10px] font-bold px-1.5 py-0.5 rounded bg-surface-input text-ink-muted">{c.country}</span>
                  <span className="text-[12px] text-ink-muted">{c.reviews[0].d}</span>
                  <StarsRow n={Math.round(avg)}/>
                  <span className={"inline-flex w-fit items-center text-[11px] font-bold px-2.5 py-1 rounded-full whitespace-nowrap "+(c.reviews.length>1?"acc-bg-soft acc-text":"bg-surface-input text-ink-muted")}>
                    {c.reviews.length} review{c.reviews.length>1?'s':''}
                  </span>
                  <div className="flex items-center gap-1 justify-end">
                    <button onClick={()=>setOpen(c.cid)} title="View profile"
                      className="w-8 h-8 rounded-lg text-ink-soft hover:bg-surface-input hover:text-ink flex items-center justify-center transition-colors shrink-0">
                      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></svg>
                    </button>
                    <button title="Delete"
                      className="w-8 h-8 rounded-lg text-ink-soft hover:bg-rose-50 hover:text-rose-600 flex items-center justify-center transition-colors shrink-0">
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg>
                    </button>
                  </div>
                </div>
              );
            })}
            </div>
            </div>
            </div>
          </Card>
        )}
        {rows.length > 0 && <p className="text-[12px] text-ink-soft">Showing {rows.length} of {CUSTS_V2.length} customers</p>}
        {open !== null && <CustomerDrawer cust={CUSTS_V2.find(c=>c.cid===open)} onClose={()=>setOpen(null)}/>}
      </div>
    </>
  );
}

window.Customers = CustomersV2;
