/* Viamar — Track a shipment by reference + email, no sign-in required.

   Lifted out of the (now-retired) root gateway so the apps own this feature:
   an anonymous visitor can check a shipment's status with just the reference
   and the email it's under. Reuses the live worker contract:

     GET ${VIAMAR_API_BASE}/app/track?ref=<ref>&email=<email>
       -> { found, ref, origin, destination_city, destination_country,
            cargo_type, method, price_status, final_price, currency,
            current_milestone, milestones:[{ milestone, label, detail, created_at }],
            shipment:{ eta, vessel, status } }

   Published as window.ViamarTrackByRef = { TrackByRef }. Self-contained: uses
   the shared tokens (T/FB/FD/FM) that every shell loads via components.jsx. */
(function () {
  const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  function apiBase() {
    if (window.ViamarAPI && window.ViamarAPI.apiBase) return (window.ViamarAPI.apiBase() || '').replace(/\/+$/, '');
    return (window.VIAMAR_API_BASE || (window.localStorage && localStorage.getItem('viamar.api.base')) || '').replace(/\/+$/, '');
  }

  function fmtStamp(iso) {
    if (!iso) return '';
    try { const d = new Date(iso); return isNaN(d.getTime()) ? '' : d.toLocaleDateString('en-CA', { month: 'short', day: 'numeric' }); }
    catch (e) { return ''; }
  }

  function priceLine(data) {
    if (data.price_status === 'in_review') return { tone: T.amber || '#E0922F', text: 'Quote in review — your agent is preparing your price' };
    if (data.final_price != null && data.final_price !== '') {
      const cur = (data.currency || 'CAD').toUpperCase();
      const amt = typeof data.final_price === 'number' ? data.final_price.toLocaleString('en-CA') : String(data.final_price);
      return { tone: T.green || '#2E8B6F', text: 'Your quote: $' + amt + ' ' + cur };
    }
    return null;
  }

  function StatusCard({ data }) {
    const origin = data.origin || 'Origin';
    const dest = [data.destination_city, data.destination_country].filter(Boolean).join(', ') || data.destination || 'Destination';
    const milestones = Array.isArray(data.milestones) ? data.milestones : [];
    let current = milestones.find(m => data.current_milestone && m.milestone === data.current_milestone) || milestones[milestones.length - 1] || null;
    const price = priceLine(data);
    const shipment = data.shipment || null;
    return (
      <div style={{ marginTop: 16, borderRadius: 16, border: '1px solid ' + T.line2, background: T.paper, overflow: 'hidden' }}>
        <div style={{ background: T.navy, color: '#fff', padding: '16px 18px' }}>
          <div style={{ fontFamily: FM, fontSize: 10.5, letterSpacing: '.12em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)', fontWeight: 700 }}>{data.ref || 'Shipment'}</div>
          <div style={{ fontFamily: FD, fontWeight: 900, fontSize: 18, letterSpacing: '-.01em', marginTop: 4, lineHeight: 1.2 }}>{origin}<span style={{ color: T.red, margin: '0 8px' }}>→</span>{dest}</div>
          {(data.cargo_type || data.method) && <div style={{ fontFamily: FB, fontSize: 12.5, color: 'rgba(255,255,255,0.72)', marginTop: 6 }}>{[data.cargo_type, data.method].filter(Boolean).join(' · ')}</div>}
        </div>
        <div style={{ padding: '16px 18px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          {price && <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 14, color: price.tone, background: 'rgba(0,0,0,0.03)', borderRadius: 10, padding: '10px 12px', border: '1px solid ' + T.line2 }}>{price.text}</div>}
          {current && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
              <div style={{ fontFamily: FD, fontWeight: 800, fontSize: 15, color: T.ink }}>{current.label || 'In progress'}</div>
              {current.detail && <div style={{ fontFamily: FB, fontSize: 13, color: T.body, lineHeight: 1.5 }}>{current.detail}</div>}
            </div>
          )}
          {shipment && (
            <div style={{ display: 'flex', gap: 18, flexWrap: 'wrap', fontFamily: FB, fontSize: 13, color: T.body }}>
              {shipment.eta && <span><span style={{ color: T.muted }}>ETA: </span>{shipment.eta}</span>}
              {shipment.vessel && <span><span style={{ color: T.muted }}>Vessel: </span>{shipment.vessel}</span>}
              {shipment.status && <span><span style={{ color: T.muted }}>Status: </span>{shipment.status}</span>}
            </div>
          )}
          {milestones.length > 0 && (
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {milestones.map((m, idx) => {
                const isCur = current && m.milestone === current.milestone;
                const last = idx === milestones.length - 1;
                return (
                  <div key={m.milestone || idx} style={{ display: 'flex', gap: 12, alignItems: 'stretch' }}>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: 14 }}>
                      <span style={{ width: 10, height: 10, borderRadius: '50%', flexShrink: 0, marginTop: 4, background: isCur ? T.red : T.green, boxShadow: isCur ? '0 0 0 4px rgba(221,28,36,0.16)' : 'none' }} />
                      {!last && <span style={{ width: 2, flex: 1, background: T.line2, marginTop: 2, minHeight: 14 }} />}
                    </div>
                    <div style={{ paddingBottom: last ? 0 : 12, flex: 1 }}>
                      <div style={{ fontFamily: FB, fontWeight: isCur ? 800 : 600, fontSize: 13.5, color: isCur ? T.ink : T.body }}>{m.label || m.milestone}</div>
                      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 1 }}>
                        {m.detail && <span style={{ fontFamily: FB, fontSize: 12, color: T.muted, lineHeight: 1.45 }}>{m.detail}</span>}
                        {fmtStamp(m.created_at) && <span style={{ fontFamily: FM, fontSize: 10.5, color: T.faint }}>{fmtStamp(m.created_at)}</span>}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    );
  }

  // Self-contained track form + result. `title`/`compact` are optional.
  function TrackByRef({ title }) {
    const [ref, setRef] = React.useState('');
    const [email, setEmail] = React.useState('');
    const [phase, setPhase] = React.useState('idle'); // idle | loading | done
    const [result, setResult] = React.useState(null);
    const [err, setErr] = React.useState(null);

    const run = () => {
      const r = (ref || '').trim(), e = (email || '').trim();
      if (!r) { setErr('Enter your shipment reference.'); return; }
      if (!EMAIL_RE.test(e)) { setErr('Enter the email on the shipment.'); return; }
      setErr(null); setResult(null); setPhase('loading');
      if (window.ViamarAnalytics) ViamarAnalytics.track('track_by_ref_submitted', {});
      const base = apiBase();
      if (!base) { setPhase('done'); setResult({ found: false }); return; }
      fetch(base + '/app/track?ref=' + encodeURIComponent(r) + '&email=' + encodeURIComponent(e), { headers: { 'Content-Type': 'application/json' } })
        .then(res => res.json().catch(() => ({})))
        .then(json => { setResult(json || { found: false }); setPhase('done'); })
        .catch(() => { setResult({ found: false }); setPhase('done'); });
    };

    const loading = phase === 'loading';
    const notFound = phase === 'done' && result && !result.found;
    const found = phase === 'done' && result && result.found;
    const inputStyle = { width: '100%', boxSizing: 'border-box', border: '1.5px solid ' + T.line, borderRadius: 11, padding: '12px 14px', fontSize: 16, color: T.ink, outline: 'none', background: '#fff', fontFamily: FB, marginBottom: 9 };

    return (
      <div style={{ background: '#fff', border: '1px solid ' + T.line2, borderRadius: 16, padding: 18, boxShadow: '0 1px 2px rgba(10,27,46,0.04)' }}>
        <div style={{ fontFamily: FD, fontWeight: 800, fontSize: 16, color: T.ink, fontStretch: '110%' }}>{title || 'Track a shipment'}</div>
        <div style={{ fontFamily: FB, fontSize: 12.5, color: T.muted, marginTop: 3, marginBottom: 14 }}>No sign-in needed — enter your reference and the email it's under.</div>
        <input value={ref} onChange={e => setRef(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') run(); }} placeholder="Shipment reference (e.g. QT-25531)" aria-label="Shipment reference" style={inputStyle} />
        <input value={email} onChange={e => setEmail(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') run(); }} placeholder="Email on the shipment" aria-label="Email" type="email" style={inputStyle} />
        {err && <div style={{ fontFamily: FB, fontSize: 12, color: T.red, marginBottom: 9 }}>{err}</div>}
        <button onClick={run} disabled={loading} style={{ width: '100%', border: 0, borderRadius: 11, padding: '13px 16px', background: loading ? T.line : T.red, color: '#fff', fontFamily: FB, fontWeight: 800, fontSize: 14, cursor: loading ? 'default' : 'pointer', boxShadow: loading ? 'none' : '0 4px 12px rgba(221,28,36,0.28)' }}>
          {loading ? 'Checking…' : 'Check status'}
        </button>
        {notFound && (
          <div style={{ fontFamily: FB, fontSize: 12.5, color: T.body, marginTop: 12, lineHeight: 1.5, background: 'rgba(221,28,36,0.06)', border: '1px solid rgba(221,28,36,0.18)', borderRadius: 10, padding: '11px 13px' }}>
            We couldn't find a shipment with that reference and email. Double-check both, or call us at <a href="tel:+18002777570" style={{ color: T.red, fontWeight: 700 }}>1-800-277-7570</a>.
          </div>
        )}
        {found && <StatusCard data={result} />}
      </div>
    );
  }

  window.ViamarTrackByRef = { TrackByRef, StatusCard };
})();
