/* Viamar Desktop — Track (master-detail) */

function TrackRow({ s, active, onClick }) {
  return (
    <div onClick={onClick} style={{
      background: active ? '#fff' : 'transparent', borderRadius: 14, padding: 15, cursor: 'pointer',
      border: active ? '2px solid ' + T.red : '2px solid transparent',
      boxShadow: active ? '0 8px 22px rgba(221,28,36,0.1)' : 'none', transition: 'background .15s',
    }}
    onMouseEnter={e => { if (!active) e.currentTarget.style.background = '#fff'; }}
    onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 13 }}>
        <div style={{ width: 42, height: 42, borderRadius: 12, background: T.paper, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name={s.cargoType} size={23} color={T.navy} stroke={1.9} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 14.5, color: T.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.cargo}</div>
          <div style={{ fontFamily: FM, fontSize: 10.5, color: T.muted }}>{s.id} · {s.to}</div>
        </div>
        <Status kind={s.kind} />
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
        <span style={{ fontFamily: FM, fontSize: 10.5, color: T.faint }}>{s.fromPort}</span>
        <div style={{ flex: 1 }}><Progress value={s.progress} h={4} /></div>
        <span style={{ fontFamily: FM, fontSize: 10.5, color: T.faint }}>{s.toPort}</span>
      </div>
    </div>
  );
}

function DetailPanel({ s, onMessage }) {
  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={{ fontFamily: FM, fontSize: 11, color: T.muted, letterSpacing: 0.5, marginBottom: 6 }}>{s.id}</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>

      {/* map + ETA */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.7fr 1fr', gap: 18, alignItems: 'stretch' }}>
        <RouteMap s={s} />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {[['ETA', s.eta, 'clock'], ['Vessel', s.vessel, 'anchor'], ['BL reference', s.ref, 'doc']].map(([l, v, ic], i) => (
            <div key={i} style={{ flex: 1, background: '#fff', borderRadius: 14, padding: '13px 16px', border: '1px solid ' + T.line2, display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: T.paper, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name={ic} size={18} color={T.navy3} stroke={1.9} />
              </div>
              <div>
                <div style={{ fontFamily: FM, fontSize: 8.5, letterSpacing: 0.8, color: T.faint, textTransform: 'uppercase' }}>{l}</div>
                <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 14, color: T.ink, marginTop: 2 }}>{v}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <PaymentBar s={s} />

      {/* photos */}
      {s.photos > 0 && (
        <div>
          <SectionHead title="Loading photos" action={`${s.photos} photos`} />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
            {['Vehicle secured in container', 'Wheel straps & blocking', 'Container seal number', 'Pre-load inspection'].map((p, i) => (
              <AssetImage key={i} src={[ASSETS.container, ASSETS.warehouse, ASSETS.truck, ASSETS.aiScan][i]} alt={p} style={{ height: 120, 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} />
            Every shipment is photo-documented before sailing.
          </div>
        </div>
      )}

      {/* timeline */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, alignItems: 'start' }}>
        <div>
          <SectionHead title="Shipment timeline" />
          <Card><Timeline steps={s.steps} /></Card>
        </div>
        <div>
          <SectionHead title="Documents & compliance" />
          <Card pad={0} style={{ overflow: 'hidden' }}>
            {complianceDocsFor(s).map(([t, ic, v], i) => {
              const good = /Verified|Cleared|Closed|BL-/.test(v) || /^[A-Z]{2}-/.test(v);
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 18px', borderTop: i ? '1px solid ' + T.line2 : 'none' }}>
                  <div style={{ width: 34, height: 34, borderRadius: 9, background: T.paper, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={ic} size={17} color={T.navy} stroke={1.9} /></div>
                  <span style={{ flex: 1, fontFamily: FB, fontWeight: 600, fontSize: 13.5, color: T.ink }}>{t}</span>
                  <span style={{ fontFamily: FM, fontSize: 10.5, 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, letterSpacing: 0.2 }}>{v}</span>
                </div>
              );
            })}
          </Card>
        </div>
      </div>
    </div>
  );
}

function TrackScreenDesktop({ selected, onSelect, onMessage }) {
  const [tab, setTab] = React.useState('active');
  const [live, setLive] = React.useState(null);
  React.useEffect(() => {
    let ok = true;
    if (window.ViamarStore) ViamarStore.syncCustomerState().then(list => { if (ok) setLive(list); });
    return () => { ok = false; };
  }, []);
  const source = live && live.length ? live : SHIPMENTS;
  const list = source.filter(s => tab === 'active' ? s.kind !== 'delivered' : s.kind === 'delivered');
  const sel = (selected && source.find(s => s.id === selected.id)) || list[0] || source[0] || SHIPMENTS[0];
  return (
    <div style={{ display: 'flex', height: '100%' }}>
      {/* master list */}
      <div style={{ width: 360, flexShrink: 0, borderRight: '1px solid ' + T.line, background: '#FBFBFC', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '26px 22px 0' }}>
          <Display size={22} color={T.ink}>Your shipments</Display>
          <div style={{ display: 'flex', gap: 6, background: '#fff', borderRadius: 12, padding: 4, marginTop: 16, border: '1px solid ' + T.line2 }}>
            {[['active', 'Active'], ['delivered', 'Delivered']].map(([id, lbl]) => (
              <div key={id} onClick={() => setTab(id)} style={{ flex: 1, textAlign: 'center', padding: '9px 0', borderRadius: 9, cursor: 'pointer', fontFamily: FB, fontWeight: 700, fontSize: 13, color: tab === id ? '#fff' : T.muted, background: tab === id ? T.navy : 'transparent', transition: 'all .2s' }}>{lbl}</div>
            ))}
          </div>
        </div>
        <div className="vscroll" style={{ flex: 1, overflowY: 'auto', padding: '14px 14px 20px', display: 'flex', flexDirection: 'column', gap: 6 }}>
          {list.map(s => <TrackRow key={s.id} s={s} active={sel.id === s.id} onClick={() => onSelect(s)} />)}
          {list.length === 0 && <div style={{ fontFamily: FB, fontSize: 13, color: T.muted, textAlign: 'center', padding: 30 }}>No {tab} shipments.</div>}
        </div>
      </div>
      {/* detail */}
      <div className="vscroll" style={{ flex: 1, overflowY: 'auto', padding: '30px 36px 48px' }}>
        {(sel.cargoType === 'car' || sel.cargoType === 'bike')
          ? <VehicleCase s={sel} onMessage={onMessage} />
          : <DetailPanel s={sel} onMessage={onMessage} />}
      </div>
    </div>
  );
}

Object.assign(window, { TrackScreenDesktop });
