// flow-detail.jsx — Shipment detail (Overview tab as primary, all tabs stubbed)

const { TIMELINE_EVENTS, ACTIVE_CLOCKS: DETAIL_CLOCKS } = window.FLOW_DATA;

const TABS = [
  { id: 'overview', label: 'Overview' },
  { id: 'documents', label: 'Documents', count: 8 },
  { id: 'timeline', label: 'Timeline', count: 47 },
  { id: 'customs', label: 'Customs', count: 2 },
  { id: 'freetime', label: 'Free-time' },
  { id: 'claims', label: 'Claims' },
  { id: 'invoices', label: 'Invoices', badge: 'warn' },
];

const GATE_DEFS = [
  { id: 'sanctions', n: 'G1', label: 'Sanctions screen', desc: 'Consignee + driver passed OFAC/EU lists', icon: 'shield' },
  { id: 'lc',        n: 'G2', label: 'Letter of credit', desc: 'Not required for this lane', icon: 'fileCheck' },
  { id: 'insurance', n: 'G3', label: 'Cargo insurance',  desc: 'Lloyd\'s policy LP-44218 · valid through 2027-02-14', icon: 'shield' },
  { id: 'export',    n: 'G4', label: 'Export license',   desc: 'Beyanname 26TR0510120000128 issued', icon: 'fileCheck' },
  { id: 'customs',   n: 'G5', label: 'Customs broker',   desc: 'Sofia Customs Group · 24/7 contact assigned', icon: 'stamp' },
  { id: 'adr',       n: 'G6', label: 'ADR readiness',    desc: 'Class 3 cert valid · vehicle 34 ABC 7821 ADR-OK', icon: 'flag' },
];

const Gate = ({ def, state, reason }) => {
  const cls = state === 'pass' ? 'pass' : state === 'fail' ? 'fail' : state === 'warn' ? 'warn' : 'na';
  const Ic = state === 'pass' ? I.check : state === 'fail' ? I.x : state === 'warn' ? I.alert : I.info;
  return (
    <div className={`gate ${cls}`}>
      <div className="gate-icon"><Ic size={15} /></div>
      <div className="col flex-1 gap-1" style={{ minWidth: 0 }}>
        <div className="row gap-2" style={{ alignItems: 'baseline' }}>
          <span className="text-xs mono fw-700 text-muted">{def.n}</span>
          <span className="text-sm fw-600">{def.label}</span>
        </div>
        <div className="text-xs text-muted ellipsis" style={{ lineHeight: 1.4 }}>{reason || def.desc}</div>
      </div>
    </div>
  );
};

const PreDispatchGates = ({ s }) => {
  const states = s.gates;
  const pass = Object.values(states).filter((v) => v === 'pass').length;
  const total = Object.values(states).length;
  const blocked = Object.values(states).includes('fail');
  return (
    <Card style={{ padding: 16 }}>
      <div className="row gap-3" style={{ alignItems: 'center', marginBottom: 14 }}>
        <I.shield size={16} className="text-muted" />
        <div className="col gap-1 flex-1">
          <div className="text-sm fw-600">Pre-dispatch gates</div>
          <div className="text-xs text-muted">All gates must pass before dispatch · last run {s.gates.adr ? '06:42' : '09:00'} UTC</div>
        </div>
        {blocked
          ? <span className="badge badge-danger"><I.x size={11}/>Blocked</span>
          : <span className="badge badge-success"><I.check size={11}/>{pass}/{total}</span>}
        <button className="btn btn-sm"><I.refresh size={13}/>Re-run</button>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 8 }}>
        {GATE_DEFS.map((d) => (
          <Gate key={d.id} def={d} state={states[d.id] || 'na'}
                reason={d.id === 'export' && states.export === 'fail' ? s.gateFailReason : null} />
        ))}
      </div>
      {blocked && (
        <div className="row gap-3" style={{ marginTop: 12, padding: '10px 12px', background: 'var(--danger-50)', border: '1px solid hsl(0 70% 86%)', borderRadius: 10, alignItems: 'center' }}>
          <I.alert size={16} style={{ color: 'var(--danger-700)' }} />
          <div className="text-sm flex-1" style={{ color: 'var(--danger-700)' }}>
            <b>Dispatch blocked.</b> Resolve <b>G4 · {s.gateFailReason}</b> to continue. Carrier and driver have been notified.
          </div>
          <button className="btn btn-sm btn-danger">Re-issue Beyanname</button>
        </div>
      )}
    </Card>
  );
};

const TradeShieldLink = ({ s }) => (
  <Card style={{ padding: 16, background: 'linear-gradient(135deg, hsl(210 60% 98%), hsl(220 60% 96%))' }}>
    <div className="row gap-2" style={{ alignItems: 'center', marginBottom: 12 }}>
      <div style={{
        width: 24, height: 24, borderRadius: 6,
        background: 'linear-gradient(135deg, hsl(160 70% 35%), hsl(190 80% 45%))',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: 'white', fontWeight: 700, fontSize: 12,
      }}>T</div>
      <div className="text-sm fw-600">TradeShield lane · TR-BG / Road / 40T tilt</div>
      <div className="flex-1" />
      <span className="badge badge-success"><I.check size={11}/>Synced</span>
      <button className="btn btn-ghost btn-xs">Open in TradeShield<I.ext size={11}/></button>
    </div>
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
      <KV label="Expected landed">€{(2840).toLocaleString()}<span className="text-xs text-muted"> /shipment</span></KV>
      <KV label="CBAM exposure">€312 <span className="text-xs text-muted">embedded</span></KV>
      <KV label="FTA framework">EU-Türkiye Customs Union</KV>
      <KV label="Lane benchmark P50">€2,720 <span className="text-xs" style={{ color: 'var(--success)' }}>−4.2% vs market</span></KV>
    </div>
  </Card>
);

const TimelineRail = () => (
  <Card style={{ padding: 16 }}>
    <div className="row gap-2" style={{ alignItems: 'center', marginBottom: 12 }}>
      <div className="text-sm fw-600">Recent activity</div>
      <div className="flex-1" />
      <button className="btn btn-ghost btn-xs">View all<I.arrowRight size={11}/></button>
    </div>
    <div className="col">
      {TIMELINE_EVENTS.map((e, i) => {
        const Ic = I[e.icon] || I.info;
        const tone = e.tone === 'success' ? 'var(--success)' : e.tone === 'danger' ? 'var(--danger)' : e.tone === 'warning' ? 'var(--warning-700)' : 'var(--primary)';
        return (
          <div key={i} className="row gap-3" style={{ position: 'relative', paddingBottom: 14 }}>
            <div className="col" style={{ alignItems: 'center', width: 24, flex: '0 0 auto' }}>
              <div style={{ width: 22, height: 22, borderRadius: 999, background: 'white', border: `1.5px solid ${tone}`, color: tone, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Ic size={11} />
              </div>
              {i < TIMELINE_EVENTS.length - 1 && <div style={{ width: 1.5, flex: 1, background: 'var(--border)', marginTop: 4 }} />}
            </div>
            <div className="col gap-1 flex-1" style={{ minWidth: 0, paddingTop: 1 }}>
              <div className="text-sm" style={{ lineHeight: 1.4 }}>{e.text}</div>
              <div className="text-xs text-muted">
                <span className="mono">{e.ts}</span> · {e.actor}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  </Card>
);

const CargoSummary = ({ s }) => (
  <Card style={{ padding: 16 }}>
    <div className="row gap-2" style={{ alignItems: 'center', marginBottom: 12 }}>
      <I.package size={16} className="text-muted" />
      <div className="text-sm fw-600">Cargo</div>
      <div className="flex-1" />
      {s.adr.is && <span className="badge badge-warning"><I.flag size={11}/>ADR Class {s.adr.classes.join(', ')}</span>}
    </div>
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
      <KV label="Gross weight">{s.cargo.weight.toLocaleString()} <span className="text-muted text-xs">kg</span></KV>
      <KV label="Volume">{s.cargo.volume} <span className="text-muted text-xs">m³</span></KV>
      <KV label="Packages">{s.cargo.packages} <span className="text-muted text-xs">colli</span></KV>
      <KV label="Declared value">€{s.cargo.value.toLocaleString()}</KV>
    </div>
    {s.cargo.hsn && (
      <div className="row gap-3" style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--border)' }}>
        <div className="text-xs"><span className="text-muted">HS code</span> <span className="mono fw-600">{s.cargo.hsn}</span></div>
        <div className="text-xs"><span className="text-muted">UN number</span> <span className="mono fw-600">UN1268</span></div>
        <div className="text-xs"><span className="text-muted">Packing group</span> <span className="mono fw-600">II</span></div>
      </div>
    )}
  </Card>
);

const PartyBlock = ({ icon, role, name, addr, dt, dtLabel, status }) => {
  const Ic = icon;
  return (
    <div className="col gap-3" style={{ flex: 1, minWidth: 0 }}>
      <div className="row gap-2" style={{ alignItems: 'center' }}>
        <Ic size={14} className="text-muted" />
        <div className="text-xs fw-600 text-muted" style={{ textTransform: 'uppercase', letterSpacing: '0.04em' }}>{role}</div>
        {status}
      </div>
      <div className="col gap-1">
        <div className="text-sm fw-600">{name}</div>
        <div className="text-xs text-muted" style={{ lineHeight: 1.4 }}>{addr}</div>
      </div>
      <div className="col gap-1" style={{ paddingTop: 6, borderTop: '1px dashed var(--border)' }}>
        <div className="text-xs text-muted" style={{ textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, fontSize: 10.5 }}>{dtLabel}</div>
        <div className="text-sm mono">{dt}</div>
      </div>
    </div>
  );
};

const ShipmentDetail = ({ shipment, onBack, onOpenEcmr }) => {
  const s = shipment || window.FLOW_DATA.SHIPMENTS[0];
  const [tab, setTab] = useState('overview');

  const blocked = Object.values(s.gates).includes('fail');

  return (
    <div className="col" style={{ height: '100%', minHeight: 0 }}>
      {/* Sticky header band */}
      <div style={{ padding: '20px 24px 0' }}>
        <div className="row gap-2" style={{ alignItems: 'center', marginBottom: 12 }}>
          <button className="btn btn-ghost btn-xs" onClick={onBack}><I.chevLeft size={13}/>Shipments</button>
          <I.chevRight size={12} className="text-muted" />
          <span className="text-sm mono">{s.id}</span>
        </div>
        <div className="row gap-3" style={{ alignItems: 'flex-start', marginBottom: 14 }}>
          <div className="col gap-2 flex-1">
            <div className="row gap-3" style={{ alignItems: 'center', flexWrap: 'wrap' }}>
              <h1 className="fw-600" style={{ fontSize: 26, margin: 0, letterSpacing: '-0.02em' }}>
                {s.lane.from} <span className="text-muted">→</span> {s.lane.to}
              </h1>
              <StatusBadge status={s.status} />
              {s.adr.is && <span className="badge badge-warning"><I.flag size={11}/>ADR {s.adr.classes.join(',')}</span>}
              {blocked && <span className="badge badge-danger"><I.x size={11}/>Dispatch blocked</span>}
            </div>
            <div className="row gap-3" style={{ alignItems: 'center' }}>
              <span className="text-sm text-muted mono">{s.id}</span>
              {s.mrn && <><span className="text-sm text-muted">·</span><span className="text-sm text-muted">MRN <span className="mono">{s.mrn}</span></span></>}
              <span className="text-sm text-muted">·</span>
              <span className="text-sm text-muted">last update <b className="text-ink">3 min ago</b> from carrier API</span>
            </div>
          </div>
          <div className="row gap-2">
            <button className="btn btn-sm"><I.signature size={14}/>Send POD link</button>
            <button className="btn btn-sm"><I.download size={14}/>Export</button>
            <button className="btn btn-sm"><I.more size={14}/></button>
            {!blocked
              ? <button className="btn btn-sm btn-primary"><I.send size={14}/>Dispatch</button>
              : <button className="btn btn-sm btn-danger"><I.alert size={14}/>Resolve & dispatch</button>}
          </div>
        </div>
        <div className="tabs">
          {TABS.map((t) => (
            <div key={t.id} className={`tab ${tab === t.id ? 'active' : ''}`} onClick={() => setTab(t.id)}>
              {t.label}
              {t.count != null && <span className="badge badge-ghost text-xs num" style={{ marginLeft: 6 }}>{t.count}</span>}
              {t.badge === 'warn' && <span style={{ display: 'inline-block', marginLeft: 6, width: 6, height: 6, borderRadius: 999, background: 'var(--warning)' }} />}
            </div>
          ))}
        </div>
      </div>

      <div className="ab-body" style={{ padding: '20px 24px 24px' }}>
        {tab === 'overview' && <OverviewTab s={s} />}
        {tab === 'documents' && <DocumentsTab s={s} onOpenEcmr={onOpenEcmr} />}
        {tab === 'timeline' && <TimelineTab s={s} />}
        {tab === 'customs' && <CustomsTab s={s} />}
        {tab === 'freetime' && <FreetimeTab s={s} />}
        {tab === 'claims' && <ClaimsTab s={s} />}
        {tab === 'invoices' && <InvoicesTab s={s} />}
      </div>
    </div>
  );
};

const OverviewTab = ({ s }) => (
  <div className="col gap-3">
    <PreDispatchGates s={s} />

    {/* Three-col summary */}
    <Card style={{ padding: 18 }}>
      <div className="row gap-5" style={{ alignItems: 'stretch' }}>
        <PartyBlock
          icon={I.warehouse} role="Origin"
          name="Cambro Lubricants Sanayi A.Ş."
          addr={`Kocaeli OSB, Mah. 5, No. 12\n41400 ${s.lane.from}`}
          dtLabel="Pickup actual"
          dt={s.pickup.actual || s.pickup.planned}
          status={<span className="badge badge-success"><I.check size={11}/>Picked up</span>}
        />
        <div className="col" style={{ flex: '0 0 auto', alignItems: 'center', justifyContent: 'center', padding: '0 12px' }}>
          <div style={{ width: 100, position: 'relative' }}>
            <div style={{ height: 2, background: 'linear-gradient(to right, var(--success), var(--primary))' }} />
            <div style={{ position: 'absolute', top: -6, left: '60%', width: 14, height: 14, borderRadius: 999, background: 'var(--primary)', border: '2px solid white', boxShadow: '0 0 0 3px hsl(220 70% 35% / 0.18)' }} />
          </div>
          <div className="text-xs text-muted mono" style={{ marginTop: 6 }}>{s.lane.km} km · 60% complete</div>
        </div>
        <div className="vdivider" />
        <PartyBlock
          icon={I.truck} role="Carriage"
          name={s.carrier}
          addr={<>Vehicle <b className="mono">{s.vehicle}</b><br/>Driver <b>{s.driver}</b> · TR mobile +90 532 ••• 4421</>}
          dtLabel="Currently"
          dt="Plovdiv–Sofia E80, 142 km/h avg"
          status={<span className="badge badge-primary"><span className="dot"/>Moving</span>}
        />
        <div className="vdivider" />
        <PartyBlock
          icon={I.flag} role="Destination"
          name="Cambro Özay BG EOOD"
          addr={`Industrial Zone West, ul. Hadji Dimitar 14\n9700 ${s.lane.to}`}
          dtLabel="Delivery planned"
          dt={`${s.delivery.planned} ${s.delivery.etaShift && s.delivery.etaShift !== 'on time' ? '(' + s.delivery.etaShift + ')' : ''}`}
          status={<span className="badge badge-neutral">Awaiting</span>}
        />
      </div>
    </Card>

    {/* TradeShield link + cargo */}
    <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 12 }}>
      <TradeShieldLink s={s} />
      <CargoSummary s={s} />
    </div>

    {/* Lower row: customs snapshot + timeline + freetime mini */}
    <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 12 }}>
      <Card style={{ padding: 16 }}>
        <div className="row gap-2" style={{ alignItems: 'center', marginBottom: 14 }}>
          <I.stamp size={16} className="text-muted" />
          <div className="text-sm fw-600">Customs · Transit declaration</div>
          <span className="badge badge-primary mono text-xs">{s.mrn}</span>
          <div className="flex-1" />
          <button className="btn btn-ghost btn-xs">Open declaration<I.ext size={11}/></button>
        </div>
        <MRNStepper currentIdx={2} steps={[
          { label: 'Submitted',  ts: '2026-05-08 21:48' },
          { label: 'Accepted',   ts: '2026-05-08 22:05' },
          { label: 'In transit', ts: '2026-05-09 06:30' },
          { label: 'Arrived',    ts: '—' },
          { label: 'Cleared',    ts: '—' },
        ]} />
        <div className="row gap-4" style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--border)' }}>
          <KV label="Office">Kapıkule → Kapitan Andreevo</KV>
          <KV label="Type">T1 Transit</KV>
          <KV label="Declarant">Sofia Customs Group</KV>
          <KV label="Duty">€0 (transit)</KV>
          <KV label="A.TR">EU-TR ref provided</KV>
        </div>
      </Card>
      <TimelineRail />
    </div>
  </div>
);

// ---- Other tabs (lightweight, but real content) ----

const DocumentsTab = ({ s, onOpenEcmr }) => {
  const docs = [
    { id: 'mbl', kind: 'MBL', name: 'Master Bill of Lading', status: 'issued', issuer: 'Anatolia Lojistik', signedBy: '—', method: '—', uploaded: '2026-05-06 09:30', children: ['hbl1', 'hbl2'] },
    { id: 'hbl1', parent: 'mbl', kind: 'HBL', name: 'House Bill — load A (drums)', status: 'issued', issuer: 'Cambro TR', signedBy: '—', method: '—', uploaded: '2026-05-06 09:32' },
    { id: 'hbl2', parent: 'mbl', kind: 'HBL', name: 'House Bill — load B (totes)', status: 'issued', issuer: 'Cambro TR', signedBy: '—', method: '—', uploaded: '2026-05-06 09:32' },
    { id: 'ecmr', kind: 'eCMR', name: 'eCMR — TR→BG transit', status: 'signed', issuer: 'Flow', signedBy: 'H. Yıldız (driver)', method: 'Touch signature', uploaded: '2026-05-08 14:12' },
    { id: 'msds', kind: 'MSDS', name: 'Safety data sheet — Section 14 ADR', status: 'parsed', issuer: 'Cambro Lubricants TR', signedBy: '—', method: '—', uploaded: '2026-05-06 11:04' },
    { id: 'inv',  kind: 'INV',  name: 'Commercial invoice — INV-2026-887', status: 'issued', issuer: 'Cambro TR', signedBy: '—', method: '—', uploaded: '2026-05-06 09:00' },
    { id: 'pol',  kind: 'PKL',  name: 'Packing list', status: 'issued', issuer: 'Cambro TR', signedBy: '—', method: '—', uploaded: '2026-05-06 09:00' },
    { id: 'pod',  kind: 'POD',  name: 'Proof of delivery — pending', status: 'missing', issuer: '—', signedBy: '—', method: '—', uploaded: '—' },
  ];
  const [openMbl, setOpenMbl] = useState(true);

  const StatusPill = ({ st }) => {
    const m = {
      signed:   { v: 'success', l: 'Signed' },
      issued:   { v: 'primary', l: 'Issued' },
      parsed:   { v: 'success', l: 'Parsed' },
      draft:    { v: 'neutral', l: 'Draft' },
      missing:  { v: 'danger',  l: 'Missing' },
    }[st] || { v: 'neutral', l: st };
    return <span className={`badge badge-${m.v}`}>{m.l}</span>;
  };

  return (
    <div className="col gap-3">
      <Card style={{ padding: 16 }}>
        <div className="row gap-3" style={{ alignItems: 'center', marginBottom: 12 }}>
          <I.layers size={16} className="text-muted" />
          <div className="text-sm fw-600">Documents · 7 of 8 in place</div>
          <div className="flex-1" />
          <button className="btn btn-sm"><I.upload size={14}/>Upload</button>
          <button className="btn btn-sm btn-primary" onClick={onOpenEcmr}><I.spark size={14}/>Generate eCMR</button>
        </div>
        <div className="col" style={{ borderTop: '1px solid var(--border)' }}>
          <div className="row" style={{ padding: '8px 12px', background: 'hsl(220 30% 98%)', borderBottom: '1px solid var(--border)', fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>
            <div style={{ flex: '0 0 280px' }}>Document</div>
            <div style={{ flex: '0 0 110px' }}>Status</div>
            <div style={{ flex: '0 0 180px' }}>Issuer</div>
            <div style={{ flex: '0 0 180px' }}>Signed by · method</div>
            <div className="flex-1">Uploaded</div>
          </div>
          {docs.map((d) => {
            const isChild = !!d.parent;
            if (isChild && !openMbl) return null;
            return (
              <div key={d.id} className="doc-row" style={{ paddingLeft: isChild ? 36 : 12 }}>
                <div className="row gap-2" style={{ alignItems: 'center' }}>
                  {isChild ? <span className="doc-tree-line">└─</span> : (
                    d.id === 'mbl'
                      ? <button className="btn btn-ghost btn-icon btn-xs" onClick={() => setOpenMbl((o) => !o)}><I.chevDown size={12} style={{ transform: openMbl ? 'none' : 'rotate(-90deg)' }}/></button>
                      : <I.file size={14} className="text-muted" />
                  )}
                </div>
                <div className="col gap-1" style={{ flex: '0 0 280px', minWidth: 0 }}>
                  <div className="row gap-2" style={{ alignItems: 'center', minWidth: 0 }}>
                    <span className="badge badge-outline mono" style={{ fontSize: 10.5, height: 18 }}>{d.kind}</span>
                    <span className="text-sm fw-500 ellipsis">{d.name}</span>
                  </div>
                </div>
                <div style={{ flex: '0 0 110px' }}><StatusPill st={d.status} /></div>
                <div className="text-sm ellipsis" style={{ flex: '0 0 180px' }}>{d.issuer}</div>
                <div className="text-sm ellipsis" style={{ flex: '0 0 180px' }}>
                  {d.signedBy !== '—' ? <><b>{d.signedBy}</b><br/><span className="text-xs text-muted">{d.method}</span></> : <span className="text-muted">—</span>}
                </div>
                <div className="row flex-1 gap-2" style={{ alignItems: 'center' }}>
                  <span className="text-sm mono text-muted">{d.uploaded}</span>
                  <div className="flex-1" />
                  {d.status === 'missing'
                    ? <button className="btn btn-xs btn-primary"><I.upload size={11}/>Upload</button>
                    : <button className="btn btn-ghost btn-icon btn-xs"><I.eye size={13}/></button>}
                </div>
              </div>
            );
          })}
        </div>
        <div className="row gap-2" style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--border)', alignItems: 'center', color: 'var(--muted)' }}>
          <I.lock size={12} />
          <div className="text-xs">Document set archived under EU CMR retention rules until <b className="text-ink">2036-05-15</b>.</div>
        </div>
      </Card>
    </div>
  );
};

const TimelineTab = ({ s }) => {
  const events = [
    ...TIMELINE_EVENTS,
    { ts: '2026-05-07 16:20', type: 'doc', actor: 'system', text: 'MSDS uploaded — auto-parsed UN1268, hazard class 3, packing group II.', icon: 'fileCheck', tone: 'success' },
    { ts: '2026-05-07 11:00', type: 'status', actor: 'Elif Özay', text: 'Status changed: planned → ready_to_dispatch.', icon: 'truck', tone: 'primary' },
    { ts: '2026-05-06 11:04', type: 'doc', actor: 'Cambro TR', text: 'Commercial invoice + packing list received via SFTP.', icon: 'file', tone: 'primary' },
    { ts: '2026-05-06 09:30', type: 'doc', actor: 'system', text: 'MBL + 2 HBLs issued. Master/house hierarchy auto-linked.', icon: 'fileCheck', tone: 'success' },
    { ts: '2026-05-05 14:00', type: 'status', actor: 'Elif Özay', text: 'Shipment created from TradeShield lane TR-BG / Road / 40T tilt.', icon: 'spark', tone: 'primary' },
  ];
  return (
    <Card style={{ padding: 16 }}>
      <div className="row gap-2" style={{ alignItems: 'center', marginBottom: 14, flexWrap: 'wrap' }}>
        <div className="text-sm fw-600">Event timeline · {events.length} events</div>
        <div className="flex-1" />
        <div className="row gap-1">
          <button className="chip active">All</button>
          <button className="chip">Status</button>
          <button className="chip">Documents</button>
          <button className="chip">Customs</button>
          <button className="chip">Last 24h</button>
        </div>
        <button className="btn btn-sm"><I.download size={13}/>Export</button>
      </div>
      <div className="col">
        {events.map((e, i) => {
          const Ic = I[e.icon] || I.info;
          const tone = e.tone === 'success' ? 'var(--success)' : e.tone === 'danger' ? 'var(--danger)' : 'var(--primary)';
          return (
            <div key={i} className="row gap-3" style={{ position: 'relative', padding: '8px 0' }}>
              <div style={{ flex: '0 0 130px' }} className="col gap-1">
                <div className="text-sm mono">{e.ts.slice(11)}</div>
                <div className="text-xs text-muted">{e.ts.slice(0, 10)}</div>
              </div>
              <div className="col" style={{ alignItems: 'center', width: 24, flex: '0 0 auto' }}>
                <div style={{ width: 22, height: 22, borderRadius: 999, background: 'white', border: `1.5px solid ${tone}`, color: tone, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Ic size={11} /></div>
                {i < events.length - 1 && <div style={{ width: 1.5, flex: 1, background: 'var(--border)', marginTop: 4, marginBottom: -8 }} />}
              </div>
              <div className="col gap-1 flex-1" style={{ minWidth: 0, paddingTop: 1 }}>
                <div className="text-sm">{e.text}</div>
                <div className="text-xs text-muted">{e.actor} · {e.type}</div>
              </div>
            </div>
          );
        })}
      </div>
    </Card>
  );
};

const CustomsTab = ({ s }) => (
  <Card style={{ padding: 16 }}>
    <div className="text-sm fw-600" style={{ marginBottom: 12 }}>Customs declarations · 2</div>
    <MRNStepper currentIdx={2} steps={[
      { label: 'Submitted',  ts: '2026-05-08 21:48' },
      { label: 'Accepted',   ts: '2026-05-08 22:05' },
      { label: 'In transit', ts: '2026-05-09 06:30' },
      { label: 'Arrived',    ts: '—' },
      { label: 'Cleared',    ts: '—' },
    ]} />
  </Card>
);

const FreetimeTab = ({ s }) => (
  <Card style={{ padding: 16 }}>
    <div className="text-sm fw-600" style={{ marginBottom: 12 }}>Active free-time clocks · 1</div>
    <div className="col gap-3">
      <FreeTimeBar usedHours={3.6} freeHours={4} />
      <div className="text-sm">Driver waiting at Kapıkule border · started 04:10 · accruing €15/hr after 4h.</div>
    </div>
  </Card>
);

const ClaimsTab = () => (
  <Card style={{ padding: 40, textAlign: 'center' }}>
    <div className="col gap-2" style={{ alignItems: 'center', color: 'var(--muted)' }}>
      <div style={{ width: 48, height: 48, borderRadius: 999, background: 'var(--success-50)', color: 'var(--success)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <I.check size={22} />
      </div>
      <div className="fw-600 text-lg" style={{ color: 'var(--ink)' }}>No claims on this shipment</div>
      <div className="text-sm" style={{ maxWidth: 360 }}>If damage or shortage is discovered on delivery, open a claim within the 7-day road notification window.</div>
      <button className="btn btn-sm" style={{ marginTop: 8 }}>Open new claim</button>
    </div>
  </Card>
);

const InvoicesTab = ({ s }) => {
  const lines = [
    { type: 'Linehaul', expected: 2480, invoiced: 2480, var: 0 },
    { type: 'Fuel surcharge (BAF)', expected: 240, invoiced: 240, var: 0 },
    { type: 'Customs handling', expected: 80, invoiced: 80, var: 0 },
    { type: 'Driver waiting', expected: 0, invoiced: 60, var: 60 },
    { type: 'Documentation', expected: 40, invoiced: 40, var: 0 },
  ];
  const totalE = lines.reduce((a, l) => a + l.expected, 0);
  const totalI = lines.reduce((a, l) => a + l.invoiced, 0);
  return (
    <Card style={{ padding: 16 }}>
      <div className="row gap-2" style={{ alignItems: 'center', marginBottom: 12 }}>
        <div className="text-sm fw-600">Anatolia Lojistik · INV-2026-2014</div>
        <span className="badge badge-warning">Variance 4.1%</span>
        <div className="flex-1" />
        <button className="btn btn-sm">Dispute</button>
        <button className="btn btn-sm btn-primary">Approve €{totalI}</button>
      </div>
      <table className="table">
        <thead>
          <tr><th>Line</th><th style={{ textAlign: 'right' }}>Expected (TS)</th><th style={{ textAlign: 'right' }}>Invoiced</th><th style={{ textAlign: 'right' }}>Variance</th></tr>
        </thead>
        <tbody>
          {lines.map((l, i) => (
            <tr key={i}>
              <td>{l.type}</td>
              <td className="mono num" style={{ textAlign: 'right' }}>€{l.expected}</td>
              <td className="mono num" style={{ textAlign: 'right' }}>€{l.invoiced}</td>
              <td className="mono num" style={{ textAlign: 'right', color: l.var > 0 ? 'var(--warning-700)' : 'var(--muted)' }}>{l.var > 0 ? '+€' + l.var : '—'}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
};

window.ShipmentDetail = ShipmentDetail;
