/* Viamar Mobile — Shipment detail with contact-point action tools + timeline */

// Compact vertical stage timeline
function MTimeline({ steps }) {
  return (
    <div>
      {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: 13 }}>
            <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, 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: 24, background: st.done ? T.green : T.line }} />}
            </div>
            <div style={{ paddingBottom: last ? 0 : 18, 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, marginTop: 1 }}>{st.d}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function ToolTile({ icon, label, sub, onClick, accent }) {
  return (
    <div onClick={onClick} style={{ flex: 1, background: '#fff', border: '1px solid ' + T.line2, borderRadius: 16, padding: '14px 14px', cursor: 'pointer', boxShadow: '0 1px 2px rgba(10,27,46,0.04)' }}>
      <div style={{ width: 38, height: 38, borderRadius: 11, background: accent ? 'rgba(221,28,36,0.1)' : T.paper, display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 10 }}>
        <Icon name={icon} size={20} color={accent ? T.red : T.navy} stroke={1.9} />
      </div>
      <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 13.5, color: T.ink }}>{label}</div>
      {sub && <div style={{ fontFamily: FB, fontSize: 11, color: T.muted, marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

const SHIP_PRICE = { 'VMR-48217': 1850, 'VMR-48090': 1320, 'VMR-47788': 1400 };

function PaySheet({ s, onClose, onPaid }) {
  const amount = SHIP_PRICE[s.id] || 1320;
  const [method, setMethod] = React.useState('card');
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 95, background: 'rgba(6,16,28,0.5)', display: 'flex', alignItems: 'flex-end' }}>
      <div className="m-up" onClick={e => e.stopPropagation()} style={{ width: '100%', background: T.paper, borderRadius: '26px 26px 0 0', padding: '10px 20px 40px' }}>
        <div style={{ width: 38, height: 5, borderRadius: 999, background: T.line, margin: '0 auto 18px' }} />
        <div style={{ fontFamily: FD, fontWeight: 800, fontSize: 21, color: T.ink, fontStretch: '110%' }}>Approve &amp; prepay</div>
        <div style={{ fontFamily: FB, fontSize: 13, color: T.muted, marginTop: 4, marginBottom: 18 }}>{s.cargo} · {s.to}</div>
        <div style={{ background: T.navy, borderRadius: 16, padding: 18, display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 16 }}>
          <span style={{ fontFamily: FB, fontSize: 13, color: 'rgba(255,255,255,0.6)', flex: 1 }}>Confirmed total · PREPAID</span>
          <span style={{ fontFamily: FD, fontWeight: 900, fontSize: 30, color: '#fff', fontStretch: '120%' }}>${amount.toLocaleString()}</span>
          <span style={{ fontFamily: FM, fontSize: 11, color: 'rgba(255,255,255,0.5)' }}>CAD</span>
        </div>
        <div style={{ display: 'flex', gap: 8, marginBottom: 18 }}>
          {[['card', 'Card'], ['etransfer', 'e-Transfer'], ['wire', 'Wire']].map(([id, lbl]) => {
            const on = method === id;
            return <div key={id} onClick={() => setMethod(id)} style={{ flex: 1, textAlign: 'center', padding: '12px 8px', borderRadius: 13, border: `2px solid ${on ? T.red : T.line2}`, background: '#fff', fontFamily: FB, fontWeight: 700, fontSize: 13, color: on ? T.ink : T.muted, cursor: 'pointer' }}>{lbl}</div>;
          })}
        </div>
        <Btn full variant="primary" icon="shield" onClick={() => onPaid(amount, method)}>Pay ${amount.toLocaleString()} &amp; confirm</Btn>
        <div style={{ fontFamily: FB, fontSize: 11, color: T.muted, textAlign: 'center', marginTop: 12, lineHeight: 1.45 }}>Prepaid in full. No documents are released until payment clears.</div>
      </div>
    </div>
  );
}

function docsForMobile(s) {
  if (s.cargoType === 'car' || s.cargoType === 'bike') return [
    ['Proof of ownership', 'Verified'], ['Bill of sale · lien-free', 'Verified'], ['Canadian photo ID', 'Verified'], ['Bill of lading', s.ref !== '—' ? s.ref : 'Pending'],
  ];
  return [
    ['Packing list', 'Verified'], ['Prohibited-items declaration', 'Verified'], ['Commercial invoice', s.kind === 'review' ? 'Needed' : 'Attached'], ['Bill of lading', s.ref !== '—' ? s.ref : 'Pending'],
  ];
}

function ShipmentDetailMobile({ s, onBack, onChat, onPay }) {
  const active = (s.steps || []).find(x => x.active);
  const next = (s.steps || []).find(x => !x.done);
  const pending = s.kind === 'review';
  return (
    <div className="m-screen" style={{ height: '100%', display: 'flex', flexDirection: 'column', background: T.paper }}>
      {/* header */}
      <div style={{ background: T.navy, padding: '54px 18px 20px', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 13, marginBottom: 14 }}>
          <div onClick={onBack} style={{ width: 34, height: 34, borderRadius: 10, background: 'rgba(255,255,255,0.08)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
            <Icon name="chevL" size={19} color="#fff" stroke={2.2} />
          </div>
          <div style={{ flex: 1, fontFamily: FM, fontSize: 10.5, color: 'rgba(255,255,255,0.55)', letterSpacing: 0.5 }}>{s.id}</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>
        {/* status strip */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 16, background: 'rgba(255,255,255,0.06)', borderRadius: 14, padding: '13px 15px' }}>
          <div style={{ width: 40, height: 40, borderRadius: 11, background: T.red, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name={pending ? 'clock' : 'ship'} size={21} color="#fff" stroke={2} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: FM, fontSize: 9, letterSpacing: 1, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase' }}>{pending ? 'Awaiting confirmation' : 'Happening now'}</div>
            <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 14.5, color: '#fff' }}>{active ? active.t : (next ? next.t : 'In review')}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontFamily: FM, fontSize: 9, letterSpacing: 1, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase' }}>ETA</div>
            <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 13, color: '#fff' }}>{s.eta}</div>
          </div>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '18px 18px 30px' }}>
        {/* contact-point tools */}
        {pending && (
          <div onClick={() => onPay(s)} style={{ display: 'flex', alignItems: 'center', gap: 13, background: T.red, borderRadius: 16, padding: '15px 16px', marginBottom: 14, cursor: 'pointer', boxShadow: '0 8px 22px rgba(221,28,36,0.3)' }}>
            <div style={{ width: 40, height: 40, borderRadius: 11, background: 'rgba(255,255,255,0.2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="shield" size={21} color="#fff" stroke={2} /></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 14.5, color: '#fff' }}>Approve quote & prepay</div>
              <div style={{ fontFamily: FB, fontSize: 11.5, color: 'rgba(255,255,255,0.85)' }}>Lock your price and release the booking</div>
            </div>
            <Icon name="chevR" size={20} color="#fff" stroke={2.4} />
          </div>
        )}
        <div style={{ display: 'flex', gap: 11, marginBottom: 11 }}>
          <ToolTile icon="phone" label="Message agent" sub="Marco · online" accent onClick={onChat} />
          <ToolTile icon="doc" label="Documents" sub={docsForMobile(s).length + ' files'} onClick={onChat} />
        </div>
        <div style={{ display: 'flex', gap: 11, marginBottom: 22 }}>
          <ToolTile icon="camera" label="Loading photos" sub={s.photos > 0 ? s.photos + ' on file' : 'Pending load'} onClick={() => { const el = document.getElementById('m-photos'); if (el) { let p = el.parentElement; while (p && p.scrollHeight <= p.clientHeight) p = p.parentElement; if (p) p.scrollTop = el.offsetTop - 70; } }} />
          <ToolTile icon="pin" label="Share live link" sub="Send tracking" onClick={onChat} />
        </div>

        {/* loading photos */}
        {s.photos > 0 && (
          <div id="m-photos" 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((cap, i) => (
                <AssetImage key={i} src={[ASSETS.container, ASSETS.warehouse, ASSETS.truck, ASSETS.aiScan][i]} alt={cap} style={{ width: 150, height: 104, borderRadius: 13, flexShrink: 0 }} />
              ))}
            </div>
          </div>
        )}

        {/* documents */}
        <div style={{ marginBottom: 22 }}>
          <SectionHead title="Documents" />
          <Card pad={0} style={{ overflow: 'hidden' }}>
            {docsForMobile(s).map(([t, v], i) => {
              const good = /Verified|Attached|BL-/.test(v) || /^[A-Z]{2}-/.test(v);
              const needed = v === 'Needed';
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '13px 15px', borderTop: i ? '1px solid ' + T.line2 : 'none' }}>
                  <Icon name={good ? 'checkC' : needed ? 'plus' : 'doc'} size={18} color={good ? T.green : needed ? T.red : T.muted} stroke={2} />
                  <span style={{ flex: 1, fontFamily: FB, fontWeight: 600, fontSize: 13.5, color: T.ink }}>{t}</span>
                  {needed
                    ? <span onClick={onChat} style={{ fontFamily: FM, fontSize: 10.5, fontWeight: 700, color: '#fff', background: T.red, padding: '5px 11px', borderRadius: 8, textTransform: 'uppercase', cursor: 'pointer' }}>Upload</span>
                    : <span style={{ fontFamily: FM, fontSize: 10.5, color: good ? T.green : T.muted, background: good ? 'rgba(46,139,111,0.1)' : T.paper, padding: '4px 9px', borderRadius: 7 }}>{v}</span>}
                </div>
              );
            })}
          </Card>
        </div>

        {/* timeline */}
        <SectionHead title="Journey" />
        <Card><MTimeline steps={s.steps} /></Card>
      </div>
    </div>
  );
}

Object.assign(window, { ShipmentDetailMobile, PaySheet, MTimeline, docsForMobile });
