/* =====================================================================
   AI-COS — Customer Portal (scoped to one customer org)
   ===================================================================== */
function Portal({ onLogout }) {
  const DB = window.DB;
  const cust = DB.custById('C-PDO');
  const [tab, setTab] = useState('overview');
  const [reqOpen, setReqOpen] = useState(false);
  const [detail, setDetail] = useState(null);
  useEffect(() => { const prev = window._openDetail; window._openDetail = (t, d) => { setDetail({ type: t, data: d }); document.querySelector('.content')?.scrollTo(0, 0); }; return () => { window._openDetail = prev; }; }, []);
  const myMonitors = DB.monitors.filter((m) => m.customer === cust.id);
  const myCerts = DB.certificates.filter((c) => c.customer === cust.id);
  const tabs = [['overview', 'Overview', 'grid'], ['equipment', 'My Equipment', 'cpu'], ['certs', 'Certificates', 'certificate'], ['requests', 'Service Requests', 'phone']];

  return (
    <div style={{ height: '100vh', display: 'flex', flexDirection: 'column', overflow: 'hidden', background: 'var(--bg)' }}>
      {/* portal top bar */}
      <header style={{ height: 60, flex: 'none', background: 'var(--surface)', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', padding: '0 26px', gap: 16 }}>
        <div className="row" style={{ gap: 11 }}>
          <BrandMark size={34} />
          <div><div style={{ fontWeight: 800, fontSize: 15, letterSpacing: '-.2px' }}>AI-COS <span style={{ color: 'var(--text-3)', fontWeight: 600 }}>Portal</span></div></div>
        </div>
        <DemoChip />
        <div className="vr" />
        <div className="row" style={{ gap: 9 }}>
          <span className="avatar avatar-sm" style={{ background: cust.color, borderRadius: 7 }}>{cust.short}</span>
          <div className="col" style={{ gap: 0, lineHeight: 1.2 }}><span style={{ fontSize: 13, fontWeight: 700, whiteSpace: 'nowrap' }}>{cust.name}</span><span className="faint" style={{ fontSize: 11 }}>{cust.tier}</span></div>
        </div>
        <span className="spacer" />
        <div className="searchbox" style={{ width: 240 }}><Icon name="search" size={15} /><input placeholder="Search my equipment…" /></div>
        <Btn variant="primary" icon="plus" size="sm" onClick={() => { setTab('requests'); setReqOpen(true); }}>New request</Btn>
        <button className="icon-btn" onClick={onLogout} title="Sign out"><Icon name="logout" size={17} /></button>
      </header>

      {/* portal nav */}
      <div style={{ background: 'var(--surface)', borderBottom: '1px solid var(--border)', padding: '0 26px', flex: 'none' }}>
        <div className="tabs" style={{ border: 'none' }}>
          {tabs.map(([id, label, ic]) => (
            <div key={id} className={`tab${tab === id ? ' on' : ''}`} onClick={() => setTab(id)} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
              <Icon name={ic} size={15} />{label}
            </div>
          ))}
        </div>
      </div>

      <div className="content">
        <div className="page" style={{ maxWidth: 1180 }}>
          {detail ? <RecordPage type={detail.type} data={detail.data} onBack={() => setDetail(null)} onNav={() => setDetail(null)} /> : <React.Fragment>
          {tab === 'overview' && <PortalOverview cust={cust} monitors={myMonitors} certs={myCerts} onTab={setTab} onReq={() => { setTab('requests'); setReqOpen(true); }} />}
          {tab === 'equipment' && <PortalEquipment monitors={myMonitors} />}
          {tab === 'certs' && <PortalCerts certs={myCerts} />}
          {tab === 'requests' && <PortalRequests reqOpen={reqOpen} setReqOpen={setReqOpen} cust={cust} monitors={myMonitors} />}
          </React.Fragment>}
        </div>
      </div>
    </div>
  );
}

function PortalOverview({ cust, monitors, certs, onTab, onReq }) {
  const DB = window.DB;
  const dueSoon = monitors.filter((m) => m.status !== 'Active');
  return (
    <div className="rise">
      <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 20 }}>
        <div>
          <div className="h-page">Welcome, {cust.contact.split(' ')[0]}</div>
          <div className="h-sub">{cust.name} · {cust.site} · your calibration status at a glance</div>
        </div>
        <Btn variant="primary" icon="phone" onClick={onReq}>Request service</Btn>
      </div>
      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 18 }}>
        <Kpi label="My equipment" value={cust.assets} icon="cpu" tone="info" />
        <Kpi label="Due within 30 days" value={dueSoon.length} icon="clock" tone="warn" />
        <Kpi label="Valid certificates" value="241" icon="certificate" tone="ok" />
        <Kpi label="Open requests" value={1} icon="phone" tone="info" />
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 16, alignItems: 'start' }}>
        <div className="card">
          <div className="card-head"><Icon name="clock" size={16} style={{ color: 'var(--warn)' }} /><div className="h-sec" style={{ fontSize: 14 }}>Calibration due soon</div><span className="spacer" /><Btn size="sm" onClick={() => onTab('equipment')} iconR="arrowR">All equipment</Btn></div>
          <table className="tbl">
            <thead><tr><th>Asset</th><th>Model</th><th>Last cal</th><th>Next due</th><th></th></tr></thead>
            <tbody>
              {dueSoon.slice(0, 6).map((m) => (
                <tr key={m.id} className="clickable" onClick={() => window.openDetail('asset', m)}>
                  <td className="mono cell-strong" style={{ fontSize: 12 }}>{m.id}</td>
                  <td style={{ fontSize: 12.5 }}>{m.model}</td>
                  <td className="faint">{DB.fmt(m.last)}</td>
                  <td><Badge kind={m.status === 'Overdue' ? 'bad' : 'warn'} dot>{m.dueRel}</Badge></td>
                  <td><Btn size="sm" variant="soft" onClick={(e) => { e.stopPropagation(); window.toast(`Calibration booking requested for ${m.id}`); }}>Book</Btn></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="card">
            <div className="card-head"><Icon name="certificate" size={15} style={{ color: 'var(--ok)' }} /><div className="h-sec" style={{ fontSize: 13.5 }}>Recent certificates</div></div>
            <div className="card-body" style={{ paddingTop: 4, paddingBottom: 4 }}>
              {certs.slice(0, 4).map((c) => (
                <div key={c.id} className="lrow" style={{ cursor: 'pointer' }} onClick={() => window.openDetail('cert', c)}>
                  <span style={{ width: 30, height: 30, borderRadius: 8, background: 'var(--primary-50)', color: 'var(--primary-600)', display: 'grid', placeItems: 'center', flex: 'none' }}><Icon name="certificate" size={15} /></span>
                  <div style={{ flex: 1 }}><div className="mono" style={{ fontSize: 11.5, fontWeight: 650 }}>{c.id}</div><div className="faint" style={{ fontSize: 11 }}>{c.model}</div></div>
                  <button className="icon-btn" style={{ width: 30, height: 30 }}><Icon name="download" size={14} /></button>
                </div>
              ))}
            </div>
          </div>
          <div className="card card-pad" style={{ background: 'linear-gradient(140deg,#0c2138,#163a5e)', color: '#fff', textAlign: 'center' }}>
            <QRBox size={70} />
            <div style={{ fontWeight: 700, fontSize: 13.5, marginTop: 12 }}>Verify any certificate</div>
            <div style={{ fontSize: 12, color: '#9fb4d0', marginTop: 3 }}>Scan the QR on any ClearLoft certificate to confirm Valid / Superseded / Withdrawn — instantly.</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function PortalEquipment({ monitors }) {
  const DB = window.DB;
  return (
    <div className="rise">
      <div className="h-page" style={{ marginBottom: 4 }}>My Equipment</div>
      <div className="h-sub" style={{ marginBottom: 18 }}>{monitors.length} of your assets shown · full register scoped to your organization</div>
      <div className="card">
        <table className="tbl">
          <thead><tr><th>Asset ID</th><th>Model</th><th>Serial</th><th>Sensors</th><th>Last cal</th><th>Next due</th><th>Status</th><th></th></tr></thead>
          <tbody>
            {monitors.map((m) => (
              <tr key={m.id} className="clickable" onClick={() => window.openDetail('asset', m)}>
                <td className="mono cell-strong" style={{ fontSize: 12 }}>{m.id}</td>
                <td style={{ fontSize: 12.5 }}>{m.model}</td>
                <td className="mono faint" style={{ fontSize: 11.5 }}>{m.serial}</td>
                <td><div className="row wrap" style={{ gap: 4 }}>{m.sensors.map((s) => <span key={s} className="tag" style={{ padding: '1px 6px', fontSize: 10.5 }}>{s}</span>)}</div></td>
                <td className="faint">{DB.fmt(m.last)}</td>
                <td><span style={{ fontWeight: 600, color: m.status === 'Overdue' ? 'var(--bad)' : m.status === 'Due soon' ? 'var(--warn)' : 'var(--text)' }}>{m.dueRel}</span></td>
                <td><StatusBadge status={m.status} /></td>
                <td><Icon name="chevR" size={16} style={{ color: 'var(--text-3)' }} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function PortalCerts({ certs }) {
  const DB = window.DB;
  return (
    <div className="rise">
      <div className="h-page" style={{ marginBottom: 4 }}>Certificates</div>
      <div className="h-sub" style={{ marginBottom: 18 }}>Download PDFs · verify authenticity · superseded versions clearly marked</div>
      <div className="card">
        <table className="tbl">
          <thead><tr><th>Certificate №</th><th>Equipment</th><th>Method</th><th>Uncertainty</th><th>Issued</th><th>Status</th><th></th></tr></thead>
          <tbody>
            {certs.map((c) => (
              <tr key={c.id} className="clickable" onClick={() => window.openDetail('cert', c)}>
                <td className="mono cell-strong" style={{ fontSize: 12 }}>{c.id}</td>
                <td><div style={{ fontSize: 12.5, fontWeight: 600 }}>{c.model}</div><div className="cell-sub mono">{c.monitor}</div></td>
                <td className="mono" style={{ fontSize: 11.5 }}>{c.method}</td>
                <td className="mono">{c.mu}</td>
                <td className="faint">{DB.fmt(c.issued)}</td>
                <td><StatusBadge status={c.status} /></td>
                <td><div className="row" style={{ gap: 6 }}><button className="icon-btn" style={{ width: 30, height: 30 }} title="Verify" onClick={(e) => { e.stopPropagation(); window.toast('Certificate verified · Valid', 'ok'); }}><Icon name="qr" size={14} /></button><button className="icon-btn" style={{ width: 30, height: 30 }} title="Download" onClick={(e) => { e.stopPropagation(); window.toast(`${c.id}.pdf downloaded`); }}><Icon name="download" size={14} /></button></div></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function PortalRequests({ reqOpen, setReqOpen, cust, monitors }) {
  const [sent, setSent] = useState(false);
  const [type, setType] = useState('Calibration booking');
  const existing = [
    { id: 'SR-26-0188', type: 'Calibration booking', items: 6, status: 'In progress', date: 'in progress · job JOB-26-0412' },
    { id: 'SR-26-0171', type: 'Fault report', items: 1, status: 'Closed', date: 'resolved 4d ago' },
  ];
  return (
    <div className="rise">
      <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18 }}>
        <div><div className="h-page">Service Requests</div><div className="h-sub">Book calibration, report a fault, or ask a question — tracked to closure with a reference number</div></div>
        <Btn variant="primary" icon="plus" onClick={() => { setReqOpen(true); setSent(false); }}>New request</Btn>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: reqOpen ? '1fr 400px' : '1fr', gap: 16, alignItems: 'start' }}>
        <div className="card">
          <div className="card-head"><Icon name="phone" size={15} style={{ color: 'var(--primary-600)' }} /><div className="h-sec" style={{ fontSize: 13.5 }}>My requests</div></div>
          <table className="tbl">
            <thead><tr><th>Reference</th><th>Type</th><th>Items</th><th>Status</th><th>Update</th></tr></thead>
            <tbody>
              {(sent ? [{ id: 'SR-26-0192', type, items: 1, status: 'Open', date: 'just now · awaiting lab' }, ...existing] : existing).map((r) => (
                <tr key={r.id}>
                  <td className="mono cell-strong" style={{ fontSize: 12 }}>{r.id}</td>
                  <td style={{ fontSize: 12.5 }}>{r.type}</td>
                  <td className="num mono">{r.items}</td>
                  <td><StatusBadge status={r.status} /></td>
                  <td className="faint" style={{ fontSize: 11.5 }}>{r.date}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {reqOpen && (
          <div className="card">
            <div className="card-head"><div className="h-sec" style={{ fontSize: 13.5 }}>New service request</div><span className="spacer" /><button className="icon-btn" style={{ width: 30, height: 30 }} onClick={() => setReqOpen(false)}><Icon name="x" size={15} /></button></div>
            <div className="card-body">
              {sent ? (
                <div style={{ textAlign: 'center', padding: '14px 8px' }}>
                  <div style={{ width: 46, height: 46, borderRadius: 13, background: 'var(--ok)', color: '#fff', display: 'grid', placeItems: 'center', margin: '0 auto 12px' }}><Icon name="check" size={24} /></div>
                  <div style={{ fontWeight: 750, fontSize: 15 }}>Request submitted</div>
                  <div className="muted" style={{ fontSize: 12.5, margin: '4px 0 14px' }}>Reference <b className="mono">SR-26-0192</b> · the lab has been notified and you can track it here.</div>
                  <Btn variant="ghost" onClick={() => setReqOpen(false)}>Done</Btn>
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
                  <div>
                    <label className="eyebrow" style={{ fontSize: 10 }}>Request type</label>
                    <div className="seg" style={{ width: '100%', marginTop: 6 }}>
                      {['Calibration booking', 'Fault report', 'Other'].map((t) => <button key={t} className={type === t ? 'on' : ''} style={{ flex: 1 }} onClick={() => setType(t)}>{t.split(' ')[0]}</button>)}
                    </div>
                  </div>
                  <div>
                    <label className="eyebrow" style={{ fontSize: 10 }}>Equipment (optional)</label>
                    <select style={{ width: '100%', fontFamily: 'inherit', fontSize: 12.5, padding: '9px 11px', borderRadius: 9, border: '1px solid var(--border-2)', marginTop: 6, background: 'var(--surface)' }}>
                      <option>Select an asset…</option>{monitors.slice(0, 6).map((m) => <option key={m.id}>{m.id} · {m.model}</option>)}
                    </select>
                  </div>
                  <div>
                    <label className="eyebrow" style={{ fontSize: 10 }}>Describe your need</label>
                    <textarea rows="4" placeholder="e.g. 6 monitors due for 6-monthly calibration; on-site preferred." style={{ width: '100%', fontFamily: 'inherit', fontSize: 12.5, padding: '10px 11px', borderRadius: 9, border: '1px solid var(--border-2)', marginTop: 6, resize: 'vertical' }} />
                  </div>
                  <Btn variant="primary" icon="arrowR" onClick={() => setSent(true)}>Submit request</Btn>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.Portal = Portal;
