/* Viamar Desktop — Vehicle Export, end-to-end case view.
   Renders for car/bike shipments in place of the generic detail panel.
   Surfaces the full 8-stage journey grounded in real Viamar policy:
   AI quote → documents cleared → pickup → intake → in-house loading
   → sailing → customs → delivery. */

// Enriched, vehicle-specific case data derived from a shipment.
function vehicleCase(s) {
  const data = {
    'VMR-48217': {
      vin: 'WBS33AZ08PCM12345', year: '2023', make: 'BMW', model: 'M4 Competition',
      colour: 'Brooklyn Grey', length: '4.79 m', weight: '1,725 kg', condition: 'Clean · 0 flags',
      consignee: 'Klajdi Hoxha · Bremerhaven, DE', insured: '$118,000 CAD', stage: 6,
    },
    'VMR-47788': {
      vin: '1HD1KB4197Y612345', year: '2021', make: 'Harley-Davidson', model: 'Road Glide',
      colour: 'Vivid Black', length: '2.43 m', weight: '380 kg', condition: 'Clean · 0 flags',
      consignee: 'Andre Brown · Kingston, JM', insured: '$34,000 CAD', stage: 8,
    },
  };
  return data[s.id] || {
    vin: '—', year: '', make: s.cargo.split(' ')[0], model: s.cargo, colour: '—',
    length: '—', weight: '—', condition: 'Pending intake', consignee: s.to, insured: 'Optional', stage: 2,
  };
}

const VEHICLE_STAGES = [
  { t: 'Quote & price', ic: 'spark' },
  { t: 'Documents', ic: 'doc' },
  { t: 'Pickup', ic: 'truck' },
  { t: 'Intake', ic: 'camera' },
  { t: 'Loaded', ic: 'box' },
  { t: 'Sailing', ic: 'ship' },
  { t: 'Customs', ic: 'shield' },
  { t: 'Delivered', ic: 'checkC' },
];

function StageTracker({ current }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', background: '#fff', borderRadius: 18, border: '1px solid ' + T.line2, padding: '20px 22px', boxShadow: '0 1px 2px rgba(10,27,46,0.04)' }}>
      {VEHICLE_STAGES.map((st, i) => {
        const idx = i + 1, done = idx < current, active = idx === current;
        const c = done ? T.green : active ? T.red : T.line;
        return (
          <React.Fragment key={i}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, width: 64, flexShrink: 0 }}>
              <div style={{ width: 40, height: 40, borderRadius: '50%', flexShrink: 0,
                background: done ? T.green : active ? T.red : '#fff',
                border: (done || active) ? 'none' : '2px solid ' + T.line,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                boxShadow: active ? '0 0 0 5px rgba(221,28,36,0.14)' : 'none' }}>
                {done ? <Icon name="check" size={18} color="#fff" stroke={3} />
                  : <Icon name={st.ic} size={19} color={active ? '#fff' : T.faint} stroke={2} />}
              </div>
              <span style={{ fontFamily: FM, fontSize: 9.5, letterSpacing: 0.2, color: active ? T.ink : done ? T.body : T.faint, fontWeight: active ? 700 : 400, textAlign: 'center', lineHeight: 1.25 }}>{st.t}</span>
            </div>
            {i < VEHICLE_STAGES.length - 1 && (
              <div style={{ flex: 1, height: 2.5, background: idx < current ? T.green : T.line, borderRadius: 2, marginTop: 19 }} />
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

function MiniStat({ label, value }) {
  return (
    <div style={{ flex: 1 }}>
      <div style={{ fontFamily: FM, fontSize: 8.5, letterSpacing: 0.8, color: T.faint, textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 13, color: T.ink, marginTop: 3 }}>{value}</div>
    </div>
  );
}

function VehicleCase({ s, onMessage }) {
  const v = vehicleCase(s);
  const delivered = s.kind === 'delivered';
  const nextStep = (s.steps || []).find(st => !st.done) ;
  return (
    <div key={s.id} className="fadein" style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 20 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
            <span style={{ fontFamily: FM, fontSize: 11, color: T.muted, letterSpacing: 0.5 }}>{s.id}</span>
            <span style={{ fontFamily: FM, fontSize: 9.5, fontWeight: 700, color: T.navy3, background: 'rgba(27,58,87,0.08)', padding: '3px 9px', borderRadius: 999, letterSpacing: 0.5, textTransform: 'uppercase' }}>Vehicle export</span>
          </div>
          <Display size={26} color={T.ink}>{s.cargo}</Display>
          <div style={{ fontFamily: FB, fontSize: 14, color: T.body, marginTop: 6 }}>{s.from} → {s.to} · {s.method}</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
          <Status kind={s.kind} />
          <Btn variant="navy" size="sm" icon="phone" onClick={onMessage}>Message agent</Btn>
        </div>
      </div>

      {/* stage tracker */}
      <StageTracker current={v.stage} />

      <PaymentBar s={s} />

      {/* tracking + identity */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 18, alignItems: 'stretch' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <RouteMap s={s} />
          <div style={{ display: 'flex', gap: 10 }}>
            {[['ETA', s.eta], ['Vessel', s.vessel], ['BL ref', s.ref]].map(([l, val], i) => (
              <div key={i} style={{ flex: 1, background: '#fff', borderRadius: 13, padding: '11px 14px', border: '1px solid ' + T.line2 }}>
                <MiniStat label={l} value={val} />
              </div>
            ))}
          </div>
        </div>
        {/* vehicle identity */}
        <div style={{ background: T.navy, borderRadius: 16, padding: 20, display: 'flex', flexDirection: 'column' }}>
          <Kicker color={T.red} style={{ marginBottom: 12 }}>Vehicle identity</Kicker>
          <div style={{ fontFamily: FD, fontWeight: 800, fontSize: 18, color: '#fff', fontStretch: '110%', lineHeight: 1.1 }}>{v.year} {v.make} {v.model}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, marginBottom: 16 }}>
            <span style={{ fontFamily: FM, fontSize: 10, color: 'rgba(255,255,255,0.5)', letterSpacing: 0.5 }}>VIN</span>
            <span style={{ fontFamily: FM, fontSize: 12, color: '#fff', letterSpacing: 0.5 }}>{v.vin}</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px 14px' }}>
            {[['Colour', v.colour], ['Length', v.length], ['Weight', v.weight], ['Condition', v.condition]].map(([l, val], i) => (
              <div key={i}>
                <div style={{ fontFamily: FM, fontSize: 8.5, letterSpacing: 0.8, color: 'rgba(255,255,255,0.45)', textTransform: 'uppercase' }}>{l}</div>
                <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 12.5, color: '#fff', marginTop: 3 }}>{val}</div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 'auto', paddingTop: 16, display: 'flex', alignItems: 'center', gap: 8, borderTop: '1px solid rgba(255,255,255,0.1)', marginTop: 16 }}>
            <Icon name="shield" size={15} color={T.gold} stroke={2} />
            <span style={{ fontFamily: FB, fontSize: 11.5, color: 'rgba(255,255,255,0.65)' }}>Insured value · {v.insured}</span>
          </div>
        </div>
      </div>

      {/* loading photos — the trust centerpiece */}
      <div>
        <SectionHead title="Loading photos" action={s.photos > 0 ? `${s.photos} on file` : 'Pending load'} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          {['Vehicle secured in container', 'Wheel straps & blocking', 'Container seal number', 'Pre-load inspection', 'VIN plate verification', 'Doors sealed & loaded'].map((cap, i) => (
            <AssetImage key={i} src={[ASSETS.container, ASSETS.warehouse, ASSETS.truck, ASSETS.aiScan, ASSETS.container, ASSETS.warehouse][i]} alt={cap} style={{ width: '100%', height: 118, borderRadius: 13 }} />
          ))}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 11, fontFamily: FB, fontSize: 12.5, color: T.muted }}>
          <Icon name="shield" size={15} color={T.green} stroke={2} />
          We load our own containers in-house and photo-document every vehicle before the doors are sealed.
        </div>
      </div>

      {/* timeline + documents vault */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, alignItems: 'start' }}>
        <div>
          <SectionHead title="Journey timeline" />
          <Card><Timeline steps={s.steps} /></Card>
        </div>
        <div>
          <SectionHead title="Document vault" />
          <Card pad={0} style={{ overflow: 'hidden' }}>
            {complianceDocsFor(s).map(([t, ic, val], i) => {
              const good = /Verified|Cleared|Closed|BL-/.test(val) || /^[A-Z]{2}-/.test(val);
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 16px', borderTop: i ? '1px solid ' + T.line2 : 'none' }}>
                  <div style={{ width: 32, height: 32, borderRadius: 9, background: T.paper, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={ic} size={16} color={T.navy} stroke={1.9} /></div>
                  <span style={{ flex: 1, fontFamily: FB, fontWeight: 600, fontSize: 13, color: T.ink }}>{t}</span>
                  <span style={{ fontFamily: FM, fontSize: 10, color: good ? T.green : T.amber, background: good ? 'rgba(46,139,111,0.1)' : 'rgba(224,146,47,0.12)', padding: '4px 9px', borderRadius: 7 }}>{val}</span>
                </div>
              );
            })}
          </Card>
        </div>
      </div>

      {/* customs & fees + next steps */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, alignItems: 'start' }}>
        <div>
          <SectionHead title="Customs & charges" />
          <Card>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
              {[
                ['shield', 'Customs inspection', delivered ? 'Not selected' : 'Standard odds ~10–15%'],
                ['doc', 'Destination clearance', /Germany|Italy|Portugal|DE|IT|PT|Bremerhaven|Genoa|Lisbon/.test(s.to + s.toPort) ? 'ICS2 filed · included' : 'Included'],
                ['anchor', 'Demurrage / detention', 'None to date · passed at cost'],
              ].map(([ic, l, val], i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                  <div style={{ width: 32, height: 32, borderRadius: 9, background: T.paper, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={ic} size={16} color={T.navy3} stroke={1.9} /></div>
                  <span style={{ flex: 1, fontFamily: FB, fontWeight: 600, fontSize: 13, color: T.ink }}>{l}</span>
                  <span style={{ fontFamily: FM, fontSize: 11, color: T.muted }}>{val}</span>
                </div>
              ))}
            </div>
            <div style={{ fontFamily: FB, fontSize: 11.5, color: T.muted, lineHeight: 1.5, marginTop: 14, paddingTop: 14, borderTop: '1px solid ' + T.line2 }}>
              Any third-party customs or terminal charges are passed on <span style={{ color: T.ink, fontWeight: 700 }}>at cost — never marked up</span>. You're notified before anything is incurred.
            </div>
          </Card>
        </div>
        <div>
          <SectionHead title={delivered ? 'Delivered' : 'What happens next'} />
          <Card style={{ background: delivered ? '#fff' : T.navy, border: delivered ? '1px solid ' + T.line2 : 'none' }}>
            {delivered ? (
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 14 }}>
                  <div style={{ width: 42, height: 42, borderRadius: '50%', background: 'rgba(46,139,111,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="checkC" size={24} color={T.green} stroke={2} /></div>
                  <div>
                    <div style={{ fontFamily: FD, fontWeight: 800, fontSize: 16, color: T.ink, fontStretch: '110%' }}>Delivered to {v.consignee.split('·')[1] || s.to}</div>
                    <div style={{ fontFamily: FB, fontSize: 12, color: T.muted }}>{s.eta}</div>
                  </div>
                </div>
                <Btn full variant="ghost" icon="star">Leave a review</Btn>
              </div>
            ) : (
              <div>
                <div style={{ fontFamily: FM, fontSize: 10, letterSpacing: 0.8, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase', marginBottom: 8 }}>Next milestone</div>
                <div style={{ fontFamily: FD, fontWeight: 800, fontSize: 19, color: '#fff', fontStretch: '110%', marginBottom: 4 }}>{nextStep ? nextStep.t : 'Arrival'}</div>
                <div style={{ fontFamily: FB, fontSize: 13, color: 'rgba(255,255,255,0.62)', lineHeight: 1.5, marginBottom: 16 }}>
                  Estimated {nextStep ? nextStep.d : s.eta}. Your consignee — {v.consignee} — will be contacted ahead of arrival to arrange curbside delivery.
                </div>
                <div style={{ display: 'flex', gap: 10 }}>
                  <Btn variant="primary" size="sm" icon="bell">Notify me</Btn>
                  <Btn variant="ghost" size="sm" icon="doc" style={{ color: '#fff', boxShadow: 'inset 0 0 0 1.5px rgba(255,255,255,0.22)' }}>View BL</Btn>
                </div>
              </div>
            )}
          </Card>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { VehicleCase, vehicleCase });
