/* Viamar PWA — Track list + shipment detail */

function RouteMap({ s }) {
  // simple arc route on a slate "sea" field
  const W = 320, H = 150, x1 = 38, y1 = 96, x2 = 282, y2 = 54;
  const cx = (x1 + x2) / 2, cy = Math.min(y1, y2) - 46;
  const t = s.progress / 100;
  // quadratic bezier point at t
  const bx = (1 - t) * (1 - t) * x1 + 2 * (1 - t) * t * cx + t * t * x2;
  const by = (1 - t) * (1 - t) * y1 + 2 * (1 - t) * t * cy + t * t * y2;
  return (
    <div style={{ borderRadius: 18, overflow: 'hidden', background: T.navy3, position: 'relative' }}>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ display: 'block', width: '100%' }}>
        <defs>
          <pattern id="dots" width="14" height="14" patternUnits="userSpaceOnUse">
            <circle cx="2" cy="2" r="1" fill="rgba(255,255,255,0.08)" />
          </pattern>
        </defs>
        <rect width={W} height={H} fill="url(#dots)" />
        {/* land masses (abstract blobs) */}
        <path d="M-5 70 Q30 50 60 64 Q80 74 70 96 Q50 120 20 112 Q-10 104 -5 70Z" fill="rgba(255,255,255,0.06)" />
        <path d="M250 30 Q300 24 330 44 L330 90 Q290 84 262 70 Q244 50 250 30Z" fill="rgba(255,255,255,0.06)" />
        {/* full route dashed */}
        <path d={`M${x1} ${y1} Q${cx} ${cy} ${x2} ${y2}`} fill="none" stroke="rgba(255,255,255,0.3)" strokeWidth="1.6" strokeDasharray="3 5" strokeLinecap="round" />
        {/* progress solid */}
        <path d={`M${x1} ${y1} Q${cx} ${cy} ${x2} ${y2}`} fill="none" stroke={T.red} strokeWidth="2.4" strokeLinecap="round" strokeDasharray={`${t * 360} 999`} />
        {/* endpoints */}
        <circle cx={x1} cy={y1} r="5" fill="#fff" /><circle cx={x1} cy={y1} r="2.4" fill={T.navy} />
        <circle cx={x2} cy={y2} r="5" fill="#fff" /><circle cx={x2} cy={y2} r="2.4" fill={T.red} />
      </svg>
      {/* ship marker */}
      <div style={{ position: 'absolute', left: `${(bx / W) * 100}%`, top: `${(by / H) * 100}%`, transform: 'translate(-50%,-50%)', width: 30, height: 30, borderRadius: '50%', background: '#fff', boxShadow: '0 3px 10px rgba(0,0,0,0.35)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name="ship" size={17} color={T.red} stroke={2} />
      </div>
      {/* labels */}
      <div style={{ position: 'absolute', left: 12, bottom: 10, fontFamily: FM, fontSize: 10, color: 'rgba(255,255,255,0.85)', letterSpacing: 0.5 }}>{s.fromPort}</div>
      <div style={{ position: 'absolute', right: 12, top: 28, fontFamily: FM, fontSize: 10, color: '#fff', letterSpacing: 0.5 }}>{s.toPort}</div>
    </div>
  );
}

function Timeline({ steps }) {
  return (
    <div style={{ position: 'relative', paddingLeft: 4 }}>
      {steps.map((st, i) => {
        const last = i === steps.length - 1;
        const color = st.active ? T.red : st.done ? T.green : T.line;
        return (
          <div key={i} style={{ display: 'flex', gap: 14, position: 'relative' }}>
            {/* spine */}
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
              <div style={{ width: 22, height: 22, borderRadius: '50%', background: st.done || st.active ? color : '#fff', border: st.done || st.active ? 'none' : '2px solid ' + T.line, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, zIndex: 1, boxShadow: st.active ? '0 0 0 4px rgba(221,28,36,0.15)' : 'none' }}>
                {st.done && !st.active && <Icon name="check" size={12} color="#fff" stroke={3} />}
                {st.active && <div style={{ width: 7, height: 7, borderRadius: '50%', background: '#fff' }} />}
              </div>
              {!last && <div style={{ width: 2, flex: 1, minHeight: 26, background: st.done ? T.green : T.line }} />}
            </div>
            <div style={{ paddingBottom: last ? 0 : 20, flex: 1 }}>
              <div style={{ fontFamily: FB, fontWeight: st.active ? 800 : 600, fontSize: 14, color: st.done || st.active ? T.ink : T.faint }}>{st.t}</div>
              <div style={{ fontFamily: FM, fontSize: 10.5, color: st.active ? T.red : T.muted, letterSpacing: 0.3, marginTop: 1 }}>{st.d}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function ShipmentDetail({ s, onBack }) {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: T.paper }}>
      <div style={{ background: T.navy, padding: '54px 20px 20px', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16 }}>
          <div onClick={onBack} style={{ width: 38, height: 38, borderRadius: 11, background: 'rgba(255,255,255,0.08)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
            <Icon name="chevL" size={20} color="#fff" stroke={2.2} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: FM, fontSize: 10.5, color: 'rgba(255,255,255,0.55)', letterSpacing: 0.5 }}>{s.id}</div>
          </div>
          <Status kind={s.kind} />
        </div>
        <Display size={22} color="#fff">{s.cargo}</Display>
        <div style={{ fontFamily: FB, fontSize: 13, color: 'rgba(255,255,255,0.6)', marginTop: 4 }}>{s.from} → {s.to} · {s.method}</div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '18px 20px 28px' }}>
        <RouteMap s={s} />

        {/* ETA strip */}
        <div style={{ display: 'flex', gap: 10, margin: '14px 0 22px' }}>
          {[['ETA', s.eta, 'clock'], ['Vessel', s.vessel, 'anchor'], ['BL Ref', s.ref, 'doc']].map(([l, v, ic], i) => (
            <div key={i} style={{ flex: 1, background: '#fff', borderRadius: 14, padding: '12px 13px', border: '1px solid ' + T.line2 }}>
              <Icon name={ic} size={16} color={T.navy3} stroke={1.9} />
              <div style={{ fontFamily: FM, fontSize: 8.5, letterSpacing: 0.8, color: T.faint, textTransform: 'uppercase', marginTop: 7 }}>{l}</div>
              <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 12, color: T.ink, lineHeight: 1.25, marginTop: 2 }}>{v}</div>
            </div>
          ))}
        </div>

        {s.photos > 0 && (
          <div style={{ marginBottom: 22 }}>
            <SectionHead title={`Loading photos`} action={`${s.photos} photos`} />
            <div style={{ display: 'flex', gap: 9, overflowX: 'auto', scrollbarWidth: 'none' }}>
              {['Vehicle secured in container', 'Wheel straps & blocking', 'Container seal #', 'Pre-load inspection'].map((p, i) => (
                <AssetImage key={i} src={[ASSETS.container, ASSETS.warehouse, ASSETS.truck, ASSETS.aiScan][i]} alt={p} style={{ minWidth: 138, height: 104, borderRadius: 13, flexShrink: 0 }} />
              ))}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 10, fontFamily: FB, fontSize: 12, color: T.muted }}>
              <Icon name="shield" size={15} color={T.green} stroke={2} />
              Every shipment is photo-documented before sailing.
            </div>
          </div>
        )}

        <SectionHead title="Shipment timeline" />
        <Card><Timeline steps={s.steps} /></Card>

        <div style={{ marginTop: 18 }}>
          <Btn full variant="navy" icon="phone">Message my agent</Btn>
        </div>
      </div>
    </div>
  );
}

function TrackListRow({ s, onOpen }) {
  return (
    <div onClick={onOpen} style={{ background: '#fff', borderRadius: 16, padding: 15, border: '1px solid ' + T.line2, cursor: 'pointer', marginBottom: 11, boxShadow: '0 1px 2px rgba(10,27,46,0.04)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
        <div style={{ width: 40, height: 40, borderRadius: 11, background: T.paper, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name={s.cargoType} size={22} color={T.navy} stroke={1.9} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 14.5, color: T.ink }}>{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: 8 }}>
        <span style={{ fontFamily: FM, fontSize: 11, color: T.faint }}>{s.fromPort}</span>
        <div style={{ flex: 1 }}><Progress value={s.progress} h={4} /></div>
        <span style={{ fontFamily: FM, fontSize: 11, color: T.faint }}>{s.toPort}</span>
      </div>
    </div>
  );
}

function TrackScreen({ onOpenShipment }) {
  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');
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: T.paper }}>
      <div style={{ background: T.navy, padding: '54px 20px 18px', flexShrink: 0 }}>
        <Kicker color={T.red} style={{ marginBottom: 7 }}>Live tracking</Kicker>
        <Display size={26} color="#fff">Your shipments</Display>
        <div style={{ display: 'flex', gap: 6, background: 'rgba(255,255,255,0.07)', borderRadius: 12, padding: 4, marginTop: 16 }}>
          {[['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 ? T.navy : 'rgba(255,255,255,0.6)', background: tab === id ? '#fff' : 'transparent', transition: 'all .2s' }}>{lbl}</div>
          ))}
        </div>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: '18px 20px 28px' }}>
        {list.map(s => <TrackListRow key={s.id} s={s} onOpen={() => onOpenShipment(s)} />)}
      </div>
    </div>
  );
}

Object.assign(window, { RouteMap, Timeline, ShipmentDetail, TrackScreen });
