// Pelanggan — list with 4-tab drawer
const { useState: useStateCust } = React;

function PelangganPage({ role }) {
  const [selected, setSelected] = useStateCust(null);
  const [q, setQ] = useStateCust('');

  const filtered = OWNER.filter(o => {
    if (!q) return true;
    return (o.name + ' ' + o.phone).toLowerCase().includes(q.toLowerCase());
  });

  return (
    <div>
      <PageHeader
        eyebrow="Hubungan"
        title="Pelanggan"
        subtitle={`${OWNER.length} owner aktif · ${OWNER.filter(o => o.corporate).length} corporate · ${KENDARAAN.length} kendaraan tercatat`}
        actions={<><Btn icon="upload" tone="outline">Import</Btn><Btn icon="plus">Tambah Owner</Btn></>}
      />

      <div className="grid mb-6" style={{gridTemplateColumns:'repeat(4, 1fr)', gap:12}}>
        <Kpi label="Total Owner" value={OWNER.length} hint="aktif terdaftar" icon="users" tone="info" />
        <Kpi label="Corporate" value={OWNER.filter(o => o.corporate).length} hint="fleet account" icon="building" tone="accent" />
        <Kpi label="Rata kendaraan" value={(KENDARAAN.length / OWNER.length).toFixed(1)} hint="per owner" icon="car" tone="info" />
        <Kpi label="LTV avg" value={rupiah(8500000, {compact:true})} hint="lifetime value" icon="heart" tone="good" />
      </div>

      <Card style={{padding:12, marginBottom:12}}>
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="Cari nama atau nomor HP…" style={{width:'100%', padding:'8px 12px', border:'1px solid hsl(var(--border))', borderRadius:8, fontSize:13, background:'hsl(var(--card))'}} />
      </Card>

      <Card style={{padding:0, overflow:'hidden'}}>
        <table className="table">
          <thead>
            <tr>
              <th>Owner</th>
              <th style={{width:120}}>HP / WA</th>
              <th style={{width:90}}>Type</th>
              <th style={{width:100}}>Kendaraan</th>
              <th style={{width:120}}>Servis Terakhir</th>
              <th style={{width:80}}>Total Spent</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(o => {
              const vhs = KENDARAAN.filter(k => k.ownerId === o.id);
              const lastSv = SERVIS_HISTORY.filter(h => vhs.some(v => v.id === h.vhId)).sort((a, b) => b.tgl.localeCompare(a.tgl))[0];
              const totalSpent = SERVIS_HISTORY.filter(h => vhs.some(v => v.id === h.vhId)).reduce((s, h) => s + h.total, 0);
              return (
                <tr key={o.id} style={{cursor:'pointer'}} onClick={() => setSelected(o)}>
                  <td>
                    <div className="row gap-2" style={{alignItems:'center'}}>
                      <Avatar initials={o.name.split(' ').map(s => s[0]).slice(0,2).join('')} />
                      <div>
                        <div style={{fontWeight:600}}>{o.name}</div>
                        <div style={{fontSize:11, color:'hsl(var(--muted-foreground))'}}>{cabangName(o.cabang)}</div>
                      </div>
                    </div>
                  </td>
                  <td className="mono" style={{fontSize:12}}>{o.phone}</td>
                  <td>{o.corporate ? <Pill tone="accent">Corp</Pill> : <Pill tone="muted">Pribadi</Pill>}</td>
                  <td style={{fontSize:13, fontWeight:600}}>{vhs.length}</td>
                  <td style={{fontSize:12}}>{lastSv ? formatDateID(lastSv.tgl) : '—'}</td>
                  <td className="mono" style={{fontVariantNumeric:'tabular-nums', fontSize:12}}>{rupiah(totalSpent, {compact:true})}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>

      {selected && <OwnerDrawer owner={selected} onClose={() => setSelected(null)} />}
    </div>
  );
}

function OwnerDrawer({ owner, onClose }) {
  const [tab, setTab] = useStateCust('info');
  const vhs = KENDARAAN.filter(k => k.ownerId === owner.id);
  const hist = SERVIS_HISTORY.filter(h => vhs.some(v => v.id === h.vhId)).sort((a, b) => b.tgl.localeCompare(a.tgl));
  const totalSpent = hist.reduce((s, h) => s + h.total, 0);

  return (
    <div className="drawer-overlay" onClick={onClose}>
      <div className="drawer" onClick={e => e.stopPropagation()}>
        <div className="drawer-head">
          <div className="row gap-2" style={{alignItems:'center'}}>
            <Avatar initials={owner.name.split(' ').map(s => s[0]).slice(0,2).join('')} className="lg" />
            <div>
              <h2 style={{margin:0, fontFamily:'Fraunces, Georgia, serif', fontSize:20, fontWeight:650}}>{owner.name}</h2>
              <div style={{fontSize:13, color:'hsl(var(--muted-foreground))'}}>{owner.corporate ? 'Corporate Account' : 'Customer Pribadi'} · {cabangName(owner.cabang)}</div>
            </div>
          </div>
          <Btn icon="x" tone="ghost" onClick={onClose}>Tutup</Btn>
        </div>

        <div style={{padding:'0 18px', borderBottom:'1px solid hsl(var(--border))'}}>
          <div className="row gap-1">
            {[{id:'info',l:'Info'},{id:'vh',l:`Kendaraan (${vhs.length})`},{id:'hist',l:`Riwayat (${hist.length})`},{id:'family',l:'Family'}].map(t => (
              <button key={t.id} onClick={() => setTab(t.id)} style={{padding:'10px 14px', background:'transparent', border:'none', cursor:'pointer', fontSize:13, fontWeight:600, color: tab === t.id ? 'hsl(var(--accent))' : 'hsl(var(--muted-foreground))', borderBottom: tab === t.id ? '2px solid hsl(var(--accent))' : '2px solid transparent', marginBottom:-1}}>{t.l}</button>
            ))}
          </div>
        </div>

        <div className="drawer-body">
          {tab === 'info' && (
            <Card style={{padding:14}}>
              <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:14, fontSize:13}}>
                <div><div style={{fontSize:11, color:'hsl(var(--muted-foreground))', textTransform:'uppercase', letterSpacing:0.4, fontWeight:600, marginBottom:3}}>Nama</div><div>{owner.name}</div></div>
                <div><div style={{fontSize:11, color:'hsl(var(--muted-foreground))', textTransform:'uppercase', letterSpacing:0.4, fontWeight:600, marginBottom:3}}>HP / WA</div><div className="mono">{owner.phone}</div></div>
                <div><div style={{fontSize:11, color:'hsl(var(--muted-foreground))', textTransform:'uppercase', letterSpacing:0.4, fontWeight:600, marginBottom:3}}>Alamat</div><div>{owner.addr || '-'}</div></div>
                <div><div style={{fontSize:11, color:'hsl(var(--muted-foreground))', textTransform:'uppercase', letterSpacing:0.4, fontWeight:600, marginBottom:3}}>Cabang Utama</div><div>{cabangName(owner.cabang)}</div></div>
                <div><div style={{fontSize:11, color:'hsl(var(--muted-foreground))', textTransform:'uppercase', letterSpacing:0.4, fontWeight:600, marginBottom:3}}>Type</div><div>{owner.corporate ? 'Corporate' : 'Pribadi'}</div></div>
                <div><div style={{fontSize:11, color:'hsl(var(--muted-foreground))', textTransform:'uppercase', letterSpacing:0.4, fontWeight:600, marginBottom:3}}>Total Spent</div><div className="mono" style={{fontWeight:700}}>{rupiah(totalSpent)}</div></div>
              </div>
            </Card>
          )}
          {tab === 'vh' && (
            <div className="grid" style={{gridTemplateColumns:'repeat(2, 1fr)', gap:12}}>
              {vhs.map(v => <VehicleCard key={v.id} v={v} />)}
            </div>
          )}
          {tab === 'hist' && (
            <Card style={{padding:0}}>
              <table className="table">
                <thead><tr><th>Tanggal</th><th>Kendaraan</th><th>Item</th><th style={{width:120}}>Total</th></tr></thead>
                <tbody>
                  {hist.map(h => {
                    const vh = KENDARAAN_BY_ID[h.vhId];
                    return (
                      <tr key={h.id}>
                        <td style={{fontSize:12}}>{formatDateID(h.tgl)}</td>
                        <td className="mono" style={{fontSize:11}}>{vh?.plat}</td>
                        <td style={{fontSize:12}}>{h.items.slice(0,2).map(id => ITEM_SERVIS_BY_ID[id]?.label).join(', ')}{h.items.length > 2 ? `, +${h.items.length - 2}` : ''}</td>
                        <td className="mono" style={{fontWeight:600}}>{rupiah(h.total, {compact:true})}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </Card>
          )}
          {tab === 'family' && (
            <Card style={{padding:14}}>
              <div className="family-avatars" style={{marginBottom:10}}>
                {vhs.slice(0, 5).map((v, i) => (
                  <Avatar key={v.id} initials={v.plat.split(' ')[1]?.slice(0,2)} tone={i % 2 === 0 ? 'accent' : 'info'} />
                ))}
              </div>
              <div style={{fontSize:13, color:'hsl(var(--muted-foreground))'}}>Owner {owner.name} memiliki {vhs.length} kendaraan terdaftar di BMS. Total {hist.length} servis dalam history.</div>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}

window.PelangganPage = PelangganPage;
