// flow-ecmr.jsx — eCMR generation flow (modal)

const ECMR_STEPS = [
  { id: 'parties', label: 'Parties' },
  { id: 'cargo',   label: 'Cargo' },
  { id: 'carriage',label: 'Carriage' },
  { id: 'review',  label: 'Review & issue' },
];

const FieldRow = ({ label, value, mono, autofilled, hint, edit }) => (
  <div className="col gap-1" style={{ paddingBottom: 10 }}>
    <div className="row gap-2" style={{ alignItems: 'baseline' }}>
      <div className="text-xs fw-600 text-muted" style={{ textTransform: 'uppercase', letterSpacing: '0.04em', fontSize: 10.5 }}>{label}</div>
      {autofilled && <span className="badge badge-primary" style={{ height: 16, fontSize: 9.5, padding: '0 5px' }}><I.spark size={9}/>auto</span>}
      <div className="flex-1" />
      {edit && <button className="btn btn-ghost btn-icon btn-xs"><I.edit size={11}/></button>}
    </div>
    <div className={`text-sm ${mono ? 'mono' : ''}`}>{value}</div>
    {hint && <div className="text-xs text-muted">{hint}</div>}
  </div>
);

const PreviewBlock = ({ title, n, children }) => (
  <div style={{ border: '1px solid var(--border)', borderRadius: 8, padding: 12, background: 'white' }}>
    <div className="row gap-2" style={{ alignItems: 'baseline', marginBottom: 8 }}>
      <span className="mono text-xs fw-700 text-muted">{n}</span>
      <span className="text-xs fw-600" style={{ textTransform: 'uppercase', letterSpacing: '0.04em' }}>{title}</span>
    </div>
    <div className="col gap-1">{children}</div>
  </div>
);

const ECMRDialog = ({ s, onClose }) => {
  const [step, setStep] = useState(0);
  const cur = ECMR_STEPS[step];

  return (
    <div className="col" style={{ height: '100%', minHeight: 0, background: 'var(--bg)' }}>
      {/* Header */}
      <div style={{ padding: '14px 24px', borderBottom: '1px solid var(--border)', background: 'var(--surface)', backdropFilter: 'blur(8px)' }}>
        <div className="row gap-3" style={{ alignItems: 'center' }}>
          <div style={{ width: 36, height: 36, borderRadius: 9, background: 'var(--primary-50)', color: 'var(--primary-700)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <I.fileCheck size={18} />
          </div>
          <div className="col gap-1 flex-1">
            <div className="row gap-2" style={{ alignItems: 'center' }}>
              <div className="fw-600 text-lg">Generate eCMR</div>
              <span className="badge badge-primary"><I.spark size={11}/>22 of 24 fields auto-filled</span>
              <span className="text-xs text-muted">· compliant with eCMR Protocol Annex (UN/CEFACT)</span>
            </div>
            <div className="text-xs text-muted">For shipment <span className="mono fw-600 text-ink">{s.id}</span> — {s.lane.from} → {s.lane.to}</div>
          </div>
          <button className="btn btn-ghost btn-icon" onClick={onClose}><I.x size={16}/></button>
        </div>
      </div>

      {/* Stepper */}
      <div style={{ padding: '12px 24px', borderBottom: '1px solid var(--border)' }}>
        <div className="row gap-3" style={{ alignItems: 'center', maxWidth: 700 }}>
          {ECMR_STEPS.map((s, i) => (
            <Fragment key={s.id}>
              <button className="row gap-2" style={{
                background: 'transparent', border: 0, cursor: 'pointer', font: 'inherit',
                color: i === step ? 'var(--primary-700)' : i < step ? 'var(--ink)' : 'var(--muted)',
                fontWeight: i <= step ? 600 : 500, alignItems: 'center',
              }} onClick={() => setStep(i)}>
                <span style={{
                  width: 22, height: 22, borderRadius: 999, fontSize: 11, fontWeight: 700,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  background: i < step ? 'var(--success)' : i === step ? 'var(--primary)' : 'var(--slate-100)',
                  color: i <= step ? 'white' : 'var(--muted)',
                }}>{i < step ? <I.check size={11}/> : i + 1}</span>
                <span className="text-sm">{s.label}</span>
              </button>
              {i < ECMR_STEPS.length - 1 && <div style={{ flex: 1, height: 2, background: i < step ? 'var(--success)' : 'var(--border)' }} />}
            </Fragment>
          ))}
        </div>
      </div>

      {/* Body — split */}
      <div className="row" style={{ flex: 1, minHeight: 0 }}>
        {/* Left: form for current step */}
        <div className="col" style={{ flex: 1, minWidth: 0, padding: 24, overflow: 'auto', borderRight: '1px solid var(--border)' }}>
          {cur.id === 'parties' && <PartiesStep s={s} />}
          {cur.id === 'cargo' && <CargoStep s={s} />}
          {cur.id === 'carriage' && <CarriageStep s={s} />}
          {cur.id === 'review' && <ReviewStep s={s} />}
        </div>
        {/* Right: live preview */}
        <div className="col" style={{ flex: '0 0 460px', padding: 24, overflow: 'auto', background: 'var(--surface-2)' }}>
          <div className="row gap-2" style={{ alignItems: 'center', marginBottom: 12 }}>
            <I.eye size={14} className="text-muted" />
            <div className="text-sm fw-600">Live eCMR preview</div>
            <div className="flex-1" />
            <span className="text-xs text-muted">v0.1 draft</span>
          </div>
          <ECMRPreview s={s} />
        </div>
      </div>

      {/* Footer */}
      <div style={{ padding: '12px 24px', borderTop: '1px solid var(--border)', background: 'var(--surface)' }}>
        <div className="row gap-3" style={{ alignItems: 'center' }}>
          <div className="text-xs text-muted row gap-2" style={{ alignItems: 'center' }}>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--success)' }} />
            Saved as draft 12 s ago
          </div>
          <div className="flex-1" />
          {step > 0 && <button className="btn" onClick={() => setStep(step - 1)}><I.chevLeft size={14}/>Back</button>}
          <button className="btn">Save & close</button>
          {step < ECMR_STEPS.length - 1
            ? <button className="btn btn-primary" onClick={() => setStep(step + 1)}>Continue<I.chevRight size={14}/></button>
            : <button className="btn btn-primary"><I.send size={14}/>Issue eCMR</button>}
        </div>
      </div>
    </div>
  );
};

const PartiesStep = ({ s }) => (
  <div className="col gap-3" style={{ maxWidth: 720 }}>
    <div>
      <div className="text-lg fw-600" style={{ marginBottom: 4 }}>Parties</div>
      <div className="text-sm text-muted">Pulled from the booking record. Edit if the consignee or carrier differs from what was registered.</div>
    </div>

    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
      <Card style={{ padding: 16 }}>
        <div className="row gap-2" style={{ marginBottom: 10, alignItems: 'center' }}>
          <I.warehouse size={14} className="text-muted" />
          <div className="text-xs fw-700 text-muted" style={{ textTransform: 'uppercase', letterSpacing: '0.04em' }}>Box 1 · Sender (Consignor)</div>
          <div className="flex-1" />
          <span className="badge badge-primary" style={{ height: 18, fontSize: 10 }}><I.spark size={10}/>auto</span>
        </div>
        <FieldRow label="Name"   value="Cambro Lubricants Sanayi A.Ş." edit autofilled />
        <FieldRow label="Address" value="Kocaeli OSB, Mah. 5, No. 12, 41400 Gebze, TR" edit autofilled />
        <FieldRow label="VAT"    mono value="TR 215 4488 902" autofilled />
      </Card>

      <Card style={{ padding: 16 }}>
        <div className="row gap-2" style={{ marginBottom: 10, alignItems: 'center' }}>
          <I.flag size={14} className="text-muted" />
          <div className="text-xs fw-700 text-muted" style={{ textTransform: 'uppercase', letterSpacing: '0.04em' }}>Box 2 · Consignee</div>
          <div className="flex-1" />
          <span className="badge badge-primary" style={{ height: 18, fontSize: 10 }}><I.spark size={10}/>auto</span>
        </div>
        <FieldRow label="Name"   value="Cambro Özay BG EOOD" edit autofilled />
        <FieldRow label="Address" value="Industrial Zone West, ul. Hadji Dimitar 14, 9700 Shumen, BG" edit autofilled />
        <FieldRow label="EORI"   mono value="BG 175 444 122" autofilled />
      </Card>

      <Card style={{ padding: 16 }}>
        <div className="row gap-2" style={{ marginBottom: 10, alignItems: 'center' }}>
          <I.truck size={14} className="text-muted" />
          <div className="text-xs fw-700 text-muted" style={{ textTransform: 'uppercase', letterSpacing: '0.04em' }}>Box 5 · Carrier</div>
          <div className="flex-1" />
          <span className="badge badge-primary" style={{ height: 18, fontSize: 10 }}><I.spark size={10}/>auto</span>
        </div>
        <FieldRow label="Name"      value={s.carrier} edit autofilled />
        <FieldRow label="License #" mono value="TR-FCL-2204-118" autofilled />
        <FieldRow label="Liability cover" value="Lloyd's policy LP-44218 · €350k SDR" autofilled />
      </Card>

      <Card style={{ padding: 16 }}>
        <div className="row gap-2" style={{ marginBottom: 10, alignItems: 'center' }}>
          <I.user size={14} className="text-muted" />
          <div className="text-xs fw-700 text-muted" style={{ textTransform: 'uppercase', letterSpacing: '0.04em' }}>Box 16 · Successive carriers</div>
          <div className="flex-1" />
          <span className="badge badge-neutral" style={{ height: 18, fontSize: 10 }}>none</span>
        </div>
        <div className="row gap-3" style={{ alignItems: 'center', padding: '20px 8px', justifyContent: 'center', color: 'var(--muted)' }}>
          <I.plus size={14}/>
          <span className="text-sm">Add a successive carrier</span>
        </div>
      </Card>
    </div>
  </div>
);

const CargoStep = ({ s }) => (
  <div className="col gap-3" style={{ maxWidth: 720 }}>
    <div>
      <div className="text-lg fw-600" style={{ marginBottom: 4 }}>Cargo (Boxes 6–13)</div>
      <div className="text-sm text-muted">Cargo data merged from MSDS parse + commercial invoice. Verify ADR section before issuing.</div>
    </div>

    <Card style={{ padding: 16 }}>
      <div className="row gap-2" style={{ alignItems: 'center', marginBottom: 8 }}>
        <I.fileCheck size={14} className="text-success" style={{ color: 'var(--success)' }} />
        <div className="text-sm fw-600">MSDS parsed automatically</div>
        <div className="flex-1" />
        <span className="text-xs text-muted">cambro-msds-en.pdf · 1.2 MB</span>
        <button className="btn btn-ghost btn-xs">Re-parse</button>
      </div>
      <table className="table" style={{ fontSize: 13 }}>
        <thead>
          <tr><th>#</th><th>Description (Box 6)</th><th>Pkg type (7)</th><th>Marks (8)</th><th>UN # (9)</th><th>Class</th><th style={{textAlign:'right'}}>Gross kg (11)</th><th style={{textAlign:'right'}}>Vol m³ (12)</th></tr>
        </thead>
        <tbody>
          <tr>
            <td>1</td>
            <td>Industrial lubricant base oil — Group II</td>
            <td>Steel drums</td>
            <td className="mono">CAM-LP-44 / 1-12</td>
            <td className="mono">UN1268</td>
            <td><span className="badge badge-warning">3</span></td>
            <td className="mono num" style={{textAlign:'right'}}>9,840</td>
            <td className="mono num" style={{textAlign:'right'}}>32.4</td>
          </tr>
          <tr>
            <td>2</td>
            <td>Hydraulic fluid concentrate</td>
            <td>IBC totes</td>
            <td className="mono">CAM-HF-1100 / 1-12</td>
            <td className="mono">UN1993</td>
            <td><span className="badge badge-warning">3</span></td>
            <td className="mono num" style={{textAlign:'right'}}>8,610</td>
            <td className="mono num" style={{textAlign:'right'}}>29.6</td>
          </tr>
        </tbody>
      </table>
    </Card>

    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
      <Card style={{ padding: 16 }}>
        <FieldRow label="Box 13 · Sender's instructions"
                  value="Keep upright. Stow away from heat sources >50°C. Carrier to provide ADR-equipped tractor and trained driver."
                  edit autofilled hint="From shipping order template T-LUBE-EU-3" />
      </Card>
      <Card style={{ padding: 16 }}>
        <FieldRow label="Box 19 · Special agreements" value="Driver has 4h free waiting at Kapıkule; €15/h thereafter." edit autofilled />
        <FieldRow label="Box 22 · Sender's signature" value="To be signed at issuance · digital seal Cambro TR" autofilled />
      </Card>
    </div>
  </div>
);

const CarriageStep = ({ s }) => (
  <div className="col gap-3" style={{ maxWidth: 720 }}>
    <div>
      <div className="text-lg fw-600" style={{ marginBottom: 4 }}>Carriage (Boxes 4, 14–17)</div>
      <div className="text-sm text-muted">Vehicle and route. The driver will sign a touch-screen receipt at delivery.</div>
    </div>

    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
      <Card style={{ padding: 16 }}>
        <FieldRow label="Box 4 · Place / date of taking over"
                  value="Gebze, TR · 2026-05-06 09:15 EET" mono autofilled edit />
        <FieldRow label="Box 3 · Place of delivery" value="Shumen, BG · planned 2026-05-09 14:00 EEST" mono autofilled edit />
      </Card>
      <Card style={{ padding: 16 }}>
        <FieldRow label="Box 14 · Vehicle"  value={`${s.vehicle} · MAN TGX 18.510 · ADR-FL`} mono autofilled />
        <FieldRow label="Box 15 · Trailer"  value="34 SF 7820 · tank semi-trailer · 28 m³" mono autofilled />
        <FieldRow label="Box 17 · Driver"   value={`${s.driver} · DL TR-44229918 · ADR cert valid 2027-03-12`} autofilled />
      </Card>
    </div>

    <Card style={{ padding: 16 }}>
      <div className="row gap-2" style={{ marginBottom: 10, alignItems: 'center' }}>
        <I.globe size={14} className="text-muted" />
        <div className="text-sm fw-600">Routing</div>
        <div className="flex-1" />
        <button className="btn btn-ghost btn-xs">Edit waypoints</button>
      </div>
      <div className="row gap-2" style={{ alignItems: 'center', flexWrap: 'wrap' }}>
        <span className="badge badge-success">Gebze, TR</span>
        <I.arrowRight size={12} className="text-muted" />
        <span className="badge badge-neutral">İstanbul O-7</span>
        <I.arrowRight size={12} className="text-muted" />
        <span className="badge badge-warning"><I.stamp size={11}/>Kapıkule customs</span>
        <I.arrowRight size={12} className="text-muted" />
        <span className="badge badge-neutral">E80 / Plovdiv</span>
        <I.arrowRight size={12} className="text-muted" />
        <span className="badge badge-success">Shumen, BG</span>
      </div>
      <div className="row gap-3" style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--border)' }}>
        <KV label="Total distance">1,340 km</KV>
        <KV label="Estimated transit">52 h</KV>
        <KV label="Driver hours (EU 561)">38 h driving · 14 h rest</KV>
      </div>
    </Card>
  </div>
);

const ReviewStep = ({ s }) => (
  <div className="col gap-3" style={{ maxWidth: 720 }}>
    <div>
      <div className="text-lg fw-600" style={{ marginBottom: 4 }}>Review & issue</div>
      <div className="text-sm text-muted">Final pre-issue checks. The eCMR becomes legally binding once signed by the consignor and carrier.</div>
    </div>

    {/* validation list */}
    <Card style={{ padding: 16 }}>
      <div className="text-sm fw-600" style={{ marginBottom: 10 }}>Pre-issue validations</div>
      {[
        { ok: true, t: 'All 24 mandatory boxes complete' },
        { ok: true, t: 'ADR Section 14 of MSDS matches Box 9 (UN1268, class 3, PG II)' },
        { ok: true, t: 'Sanctions screen passed for consignee + driver (G1)' },
        { ok: true, t: 'Insurance liability ≥ SDR cover required for cargo value (G3)' },
        { ok: false, t: 'A.TR reference number missing on accompanying Beyanname', warn: true,
          fix: 'Customs at Kapıkule will request this. Add it now to avoid a hold.' },
      ].map((v, i) => (
        <div key={i} className="row gap-3" style={{ padding: '8px 0', borderTop: i ? '1px solid var(--border)' : 0, alignItems: 'flex-start' }}>
          <div style={{ flex: '0 0 auto', width: 22, height: 22, borderRadius: 999,
                        background: v.ok ? 'var(--success-50)' : v.warn ? 'var(--warning-50)' : 'var(--danger-50)',
                        color: v.ok ? 'var(--success)' : v.warn ? 'var(--warning-700)' : 'var(--danger-700)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {v.ok ? <I.check size={11}/> : <I.alert size={11}/>}
          </div>
          <div className="col gap-1 flex-1">
            <div className="text-sm">{v.t}</div>
            {v.fix && <div className="text-xs text-muted">{v.fix}</div>}
          </div>
          {!v.ok && <button className="btn btn-xs">Fix now</button>}
        </div>
      ))}
    </Card>

    <Card style={{ padding: 16 }}>
      <div className="text-sm fw-600" style={{ marginBottom: 10 }}>Signing & distribution</div>
      <div className="col gap-3">
        <div className="row gap-3" style={{ alignItems: 'center' }}>
          <input type="checkbox" defaultChecked style={{ accentColor: 'hsl(220 70% 35%)' }} />
          <div className="col flex-1 gap-1">
            <div className="text-sm fw-500">Send sender signing link to <b>contracts@cambro.com.tr</b></div>
            <div className="text-xs text-muted">Digital seal · valid eIDAS QES</div>
          </div>
        </div>
        <div className="row gap-3" style={{ alignItems: 'center' }}>
          <input type="checkbox" defaultChecked style={{ accentColor: 'hsl(220 70% 35%)' }} />
          <div className="col flex-1 gap-1">
            <div className="text-sm fw-500">Send driver signing link to <b>+90 532 ••• 4421</b></div>
            <div className="text-xs text-muted">Mobile-first signature pad · captures GPS at signing</div>
          </div>
        </div>
        <div className="row gap-3" style={{ alignItems: 'center' }}>
          <input type="checkbox" defaultChecked style={{ accentColor: 'hsl(220 70% 35%)' }} />
          <div className="col flex-1 gap-1">
            <div className="text-sm fw-500">Auto-deliver consignee copy on POD signing</div>
            <div className="text-xs text-muted">Email + portal access for Cambro Özay BG EOOD</div>
          </div>
        </div>
      </div>
    </Card>
  </div>
);

const ECMRPreview = ({ s }) => (
  <div style={{
    background: 'white', borderRadius: 8,
    padding: 18, border: '1px solid var(--border)',
    boxShadow: 'var(--shadow-sm)',
    fontSize: 11.5, lineHeight: 1.5,
  }}>
    <div className="row gap-2" style={{ alignItems: 'flex-start', marginBottom: 10, paddingBottom: 10, borderBottom: '2px solid var(--ink)' }}>
      <div className="col gap-1 flex-1">
        <div className="text-xs fw-700 text-muted" style={{ letterSpacing: '0.08em' }}>CMR · INTERNATIONAL CONSIGNMENT NOTE</div>
        <div className="fw-700 text-sm">Lettre de voiture internationale</div>
        <div className="text-xs text-muted">Convention CMR · 19 May 1956 · Geneva</div>
      </div>
      <div className="col" style={{ alignItems: 'flex-end' }}>
        <div className="mono text-xs">No. CMR-2026-{s.id.slice(-5)}</div>
        <div className="text-xs text-muted">Page 1 of 1</div>
      </div>
    </div>

    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
      <PreviewBlock n="1" title="Sender">
        <div>Cambro Lubricants Sanayi A.Ş.</div>
        <div className="text-muted">Kocaeli OSB, 41400 Gebze, TR</div>
        <div className="mono text-xs text-muted">VAT TR 215 4488 902</div>
      </PreviewBlock>
      <PreviewBlock n="2" title="Consignee">
        <div>Cambro Özay BG EOOD</div>
        <div className="text-muted">9700 Shumen, BG</div>
        <div className="mono text-xs text-muted">EORI BG 175 444 122</div>
      </PreviewBlock>
      <PreviewBlock n="3" title="Place of delivery">
        <div>Shumen, BG</div>
        <div className="mono text-xs text-muted">2026-05-09 14:00</div>
      </PreviewBlock>
      <PreviewBlock n="4" title="Place / date of taking over">
        <div>Gebze, TR</div>
        <div className="mono text-xs text-muted">2026-05-06 09:15</div>
      </PreviewBlock>
      <PreviewBlock n="5" title="Carrier">
        <div>{s.carrier}</div>
        <div className="mono text-xs text-muted">License TR-FCL-2204-118</div>
      </PreviewBlock>
      <PreviewBlock n="14" title="Vehicle / Trailer">
        <div className="mono">{s.vehicle}</div>
        <div className="mono text-muted">34 SF 7820</div>
      </PreviewBlock>
    </div>

    <div style={{ marginTop: 8 }}>
      <PreviewBlock n="6–13" title="Goods">
        <div className="row gap-2" style={{ paddingBottom: 4, borderBottom: '1px dashed var(--border)' }}>
          <div className="flex-1">Lubricant base oil — Group II</div>
          <div className="mono">UN1268 · cl.3 · PG II</div>
          <div className="mono">9,840 kg</div>
        </div>
        <div className="row gap-2" style={{ paddingTop: 4 }}>
          <div className="flex-1">Hydraulic fluid concentrate</div>
          <div className="mono">UN1993 · cl.3 · PG II</div>
          <div className="mono">8,610 kg</div>
        </div>
      </PreviewBlock>
    </div>

    <div style={{ marginTop: 8, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
      <PreviewBlock n="22" title="Sender signature">
        <div style={{ height: 36, border: '1px dashed var(--border-strong)', borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--muted)', fontSize: 10 }}>Pending</div>
      </PreviewBlock>
      <PreviewBlock n="23" title="Carrier signature">
        <div style={{ height: 36, border: '1px dashed var(--border-strong)', borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--muted)', fontSize: 10 }}>Pending</div>
      </PreviewBlock>
      <PreviewBlock n="24" title="Consignee signature">
        <div style={{ height: 36, border: '1px dashed var(--border-strong)', borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--muted)', fontSize: 10 }}>On delivery</div>
      </PreviewBlock>
    </div>
  </div>
);

window.ECMRDialog = ECMRDialog;
