/* =====================================================================
   AI-COS — Printable document previews (certificate, invoice, contract,
   quotation). Rendered as paper sheets inside full-page detail views.
   ===================================================================== */
function Sheet({ children, doc = 'DOCUMENT', accent = 'var(--primary-700)' }) {
  return (
    <div style={{ background: '#fff', border: '1px solid var(--border)', borderRadius: 6, boxShadow: 'var(--sh-md)', maxWidth: 760, margin: '0 auto', overflow: 'hidden' }}>
      {/* letterhead */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '20px 30px', borderBottom: `3px solid ${accent}` }}>
        <BrandMark size={46} style={{ flex: 'none' }} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 800, letterSpacing: '-.3px', color: 'var(--ink)' }}>Al Duqum <span style={{ color: 'var(--adam-orange, #e2794b)' }}>Al Masiya</span> ENT</div>
          <div style={{ fontSize: 11, color: 'var(--text-3)' }}>Gas Monitor Calibration Laboratory · Duqm SEZ, Sultanate of Oman · CR 1538472</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="eyebrow" style={{ fontSize: 9, color: accent }}>{doc}</div>
          <div style={{ fontSize: 10, color: 'var(--text-3)', marginTop: 2 }}>ISO/IEC 17025 · ISO 9001</div>
        </div>
      </div>
      <div style={{ padding: '24px 30px 30px' }}>{children}</div>
      <div style={{ borderTop: '1px solid var(--border)', padding: '9px 30px', display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: 9.5, color: 'var(--text-3)', flexWrap: 'wrap' }}>
        <span>P.O. Box 124, Duqm 811, Al Wusta · +968 2521 8400 · lab@aldam.om · www.aldam.om</span>
        <span>CR 1538472 · VATIN OM1100258934</span>
      </div>
    </div>
  );
}
function DocRow({ k, v, mono }) {
  return <div style={{ display: 'flex', justifyContent: 'space-between', padding: '5px 0', fontSize: 12.5, borderBottom: '1px dotted var(--border)' }}><span className="faint">{k}</span><span className={mono ? 'mono' : ''} style={{ fontWeight: 650, color: 'var(--ink)' }}>{v}</span></div>;
}
function DocGrid({ pairs }) {
  return <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 30px' }}>{pairs.map(([k, v, m], i) => <DocRow key={i} k={k} v={v} mono={m} />)}</div>;
}
function DocTitle({ children, sub }) {
  return <div style={{ marginBottom: 16 }}><div style={{ fontSize: 19, fontWeight: 800, letterSpacing: '-.4px', color: 'var(--ink)' }}>{children}</div>{sub && <div className="faint" style={{ fontSize: 12, marginTop: 2 }}>{sub}</div>}</div>;
}
function SignBlock({ roles }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${roles.length},1fr)`, gap: 16, marginTop: 22 }}>
      {roles.map(([role, name], i) => (
        <div key={i}>
          <div style={{ fontFamily: 'cursive', fontSize: 18, color: 'var(--primary-700)', opacity: .85, borderBottom: '1px solid var(--border-2)', paddingBottom: 4 }}>{name ? '✒ ' + name.split(' ')[0] : ''}</div>
          <div className="eyebrow" style={{ fontSize: 8.5, marginTop: 6 }}>{role}</div>
          <div style={{ fontSize: 11.5, fontWeight: 600, marginTop: 2 }}>{name || '—'}</div>
        </div>
      ))}
    </div>
  );
}

/* ---- Certificate preview ---- */
function CertPreview({ ct }) {
  const DB = window.DB;
  const c = DB.custById(ct.customer);
  const kind = (typeof certKind === 'function') ? certKind(ct) : 'h2s';
  const res = (typeof certResults === 'function') ? certResults(kind) : { cols: [], rows: [] };
  return (
    <Sheet doc={ct.bump ? 'BUMP TEST REPORT' : 'CALIBRATION CERTIFICATE'}>
      <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <DocTitle sub={`Issued under ${ct.bump ? 'ADAM-TECH-L3-P-006' : kind === 'multi' ? 'ADAM-TECH-L3-P-003' : 'ADAM-TECH-L3-P-004'} · template ADAM-QMS-L4-F-005`}>{ct.bump ? 'Bump Test Report' : 'Certificate of Calibration'}</DocTitle>
        <QRBox size={66} />
      </div>
      <DocGrid pairs={[
        ['Certificate No.', ct.id, 1], ['Calibration date', DB.fmt(ct.issued)],
        ['Client', c.name], ['Location', c.site],
        ['Instrument', ct.model], ['Serial / Asset ID', ct.monitor, 1],
        ['Sensor type', kind === 'multi' ? 'LEL / O₂ / CO / H₂S' : 'H₂S'], ['Measurement range', kind === 'multi' ? 'Per sensor' : '0–100 ppm'],
        ['Calibration gas', kind === 'multi' ? '4-gas mix' : '25 ppm H₂S'], ['Cylinder / lot', kind === 'multi' ? 'CYL-2453' : 'CYL-2451', 1],
        ['Expanded uncertainty', `${ct.mu} (k=2)`], ['Decision rule', 'Simple acceptance'],
        ['Next due', DB.fmt(DB.addM(ct.issued, 6))], ['Certificate expiry', DB.fmt(DB.addM(ct.issued, 6))],
      ]} />
      <div className="eyebrow" style={{ fontSize: 9.5, margin: '18px 0 8px' }}>Calibration results</div>
      <table className="tbl" style={{ fontSize: 11.5, border: '1px solid var(--border)', borderRadius: 6, overflow: 'hidden' }}>
        <thead><tr>{res.cols.map((c2) => <th key={c2} style={{ padding: '7px 10px' }}>{c2}</th>)}</tr></thead>
        <tbody>{res.rows.map((r, i) => <tr key={i}>{r.map((cell, j) => j === r.length - 1 ? <td key={j} style={{ padding: '6px 10px' }}><Badge kind="ok" icon="check">Pass</Badge></td> : <td key={j} className={j === 0 ? 'cell-strong' : 'mono'} style={{ padding: '6px 10px' }}>{cell}</td>)}</tr>)}</tbody>
      </table>
      <p style={{ fontSize: 11.5, color: 'var(--text-2)', lineHeight: 1.6, marginTop: 16, fontStyle: 'italic' }}>
        This is to certify that the above instrument has been calibrated using certified reference gas traceable to national standards, and was found operating within acceptable tolerance limits at the time of calibration. Valid until the certificate expiry date, provided the instrument is maintained and used per manufacturer recommendations.
      </p>
      <SignBlock roles={[['Calibrated by', DB.staffById(ct.bump ? 'U-002' : 'U-003').name], ['Reviewed by', 'Priya Nair'], ['Approved by', DB.staffById(ct.signatory).name]]} />
    </Sheet>
  );
}

/* ---- Invoice preview ---- */
function InvoicePreview({ iv }) {
  const DB = window.DB;
  const c = DB.custById(iv.customer);
  const net = iv.amount / (1 + iv.vat / 100);
  const lines = [
    ['Calibration — portable gas monitors', 18, (net * 0.62 / 18)],
    ['Bump test service', 6, (net * 0.18 / 6)],
    ['Sensor replacement (H₂S)', 2, (net * 0.20 / 2)],
  ];
  return (
    <Sheet doc="TAX INVOICE" accent="var(--ok)">
      <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <DocTitle sub={`VAT compliant · gap-free numbering`}>Tax Invoice</DocTitle>
        <div style={{ textAlign: 'right' }}><div className="mono" style={{ fontWeight: 750, fontSize: 15 }}>{iv.id}</div><StatusBadge status={iv.status} /></div>
      </div>
      <DocGrid pairs={[['Bill to', c.name], ['Invoice date', DB.fmt(iv.date)], ['Site', c.site], ['Due date', DB.fmt(iv.due)], ['VAT reg. no.', 'OM1100258934', 1], ['Payment terms', '30 days net']]} />
      <table className="tbl" style={{ fontSize: 12, marginTop: 18, border: '1px solid var(--border)', borderRadius: 6, overflow: 'hidden' }}>
        <thead><tr><th>Description</th><th className="num">Qty</th><th className="num">Unit (OMR)</th><th className="num">Amount (OMR)</th></tr></thead>
        <tbody>{lines.map((l, i) => <tr key={i}><td style={{ fontSize: 12 }}>{l[0]}</td><td className="num mono">{l[1]}</td><td className="num mono">{l[2].toFixed(3)}</td><td className="num mono cell-strong">{(l[1] * l[2]).toFixed(3)}</td></tr>)}</tbody>
      </table>
      <div style={{ marginLeft: 'auto', width: 260, marginTop: 14 }}>
        {[['Net', net], [`VAT (${iv.vat}%)`, iv.amount - net], ['Total due', iv.amount]].map(([k, v], i) => (
          <div key={i} className="row" style={{ justifyContent: 'space-between', padding: '6px 0', borderTop: i === 2 ? '2px solid var(--ink)' : '1px dotted var(--border)' }}><span className={i === 2 ? 'cell-strong' : 'faint'} style={{ fontSize: 12.5 }}>{k}</span><b className="mono" style={{ fontSize: i === 2 ? 15 : 12.5 }}>{v.toFixed(3)}</b></div>
        ))}
      </div>
      <p style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 18 }}>Issued invoices are immutable — corrections via credit note only. Bank: Bank Muscat · IBAN OM81 0018 0000 1234 5678 901 · Swift BMUSOMRX.</p>
    </Sheet>
  );
}

/* ---- Contract / AMC preview ---- */
function ContractPreview({ ct }) {
  const DB = window.DB;
  const c = DB.custById(ct.customer);
  return (
    <Sheet doc="SERVICE AGREEMENT" accent="var(--ai)">
      <DocTitle sub={`Annual Maintenance & Calibration Contract`}>Service Agreement — {ct.id}</DocTitle>
      <DocGrid pairs={[['Client', c.name], ['Contract period', ct.period], ['Covered assets', `${ct.assets} monitors`], ['Calibration frequency', ct.freq], ['Annual value', `${ct.value.toLocaleString()} OMR`], ['Renewal date', DB.fmt(ct.renew)]]} />
      <div className="eyebrow" style={{ fontSize: 9.5, margin: '18px 0 8px' }}>Scope of services</div>
      <ul style={{ fontSize: 12.5, color: 'var(--text-2)', lineHeight: 1.7, paddingLeft: 18, margin: 0 }}>
        <li>Scheduled {ct.freq.toLowerCase()} calibration of all covered gas monitors under ISO/IEC 17025.</li>
        <li>Auto-planning of covered equipment across the contract period; reminders and overdue escalation.</li>
        <li>Issuance of accredited calibration certificates with measurement uncertainty and QR verification.</li>
        <li>Customer portal access — equipment, due status, certificates and service requests.</li>
        <li>Agreed rates per the price schedule; AMC billing {ct.freq.toLowerCase()}.</li>
      </ul>
      <SignBlock roles={[['For Al Duqum Al Masiya ENT', 'Savad Ahammed'], [`For ${c.short}`, c.contact]]} />
    </Sheet>
  );
}

/* ---- Quotation / proposal preview ---- */
function QuotationPreview({ qt }) {
  const DB = window.DB;
  const c = DB.custById(qt.customer);
  const net = qt.value;
  const vat = net * 0.05;
  return (
    <Sheet doc="QUOTATION" accent="var(--warn)">
      <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <DocTitle sub={qt.title}>Quotation {qt.id}</DocTitle>
        <StatusBadge status={qt.status} />
      </div>
      <DocGrid pairs={[['Prepared for', c.name], ['Date', DB.fmt(qt.date)], ['Attention', c.contact], ['Valid until', DB.fmt(qt.validity)], ['Items', `${qt.items}`], ['Currency', 'OMR']]} />
      <table className="tbl" style={{ fontSize: 12, marginTop: 18, border: '1px solid var(--border)', borderRadius: 6, overflow: 'hidden' }}>
        <thead><tr><th>Line item</th><th className="num">Qty</th><th className="num">Rate</th><th className="num">Amount</th></tr></thead>
        <tbody>
          <tr><td>{qt.title}</td><td className="num mono">{qt.items}</td><td className="num mono">{(net / qt.items).toFixed(3)}</td><td className="num mono cell-strong">{net.toFixed(3)}</td></tr>
        </tbody>
      </table>
      <div style={{ marginLeft: 'auto', width: 260, marginTop: 14 }}>
        {[['Net', net], ['VAT (5%)', vat], ['Total', net + vat]].map(([k, v], i) => (
          <div key={i} className="row" style={{ justifyContent: 'space-between', padding: '6px 0', borderTop: i === 2 ? '2px solid var(--ink)' : '1px dotted var(--border)' }}><span className={i === 2 ? 'cell-strong' : 'faint'} style={{ fontSize: 12.5 }}>{k}</span><b className="mono" style={{ fontSize: i === 2 ? 15 : 12.5 }}>{v.toFixed(3)}</b></div>
        ))}
      </div>
      <p style={{ fontSize: 11.5, color: 'var(--text-2)', marginTop: 16 }}>On acceptance, this quotation converts to a job or AMC contract; covered equipment is auto-scheduled. Prices valid until the date shown.</p>
    </Sheet>
  );
}

Object.assign(window, { Sheet, CertPreview, InvoicePreview, ContractPreview, QuotationPreview });
