/* Viamar — airline-style "gateway" cold-start screen.
 *
 * The first screen a cold (not-signed-in) visitor sees at the app root: a clean
 * fork, NOT the dashboard. Minimal options, like an airline home page:
 *   • Get a quote   (red, primary)  → /new-quote/
 *   • Sign in / Track (navy outline) → ViamarSignInDialog.open() or /login/
 *   • Track by reference (no login)  → GET /app/track?ref=&email=
 *
 * Published as window.ViamarGateway (a React component) with a
 * ViamarGateway.mount(el) helper. Depends on the shared tokens/primitives from
 * app/components.jsx (T, FD/FB/FM, ViamarLogo, Icon), env.js (VIAMAR_API_BASE)
 * and, when present, sign-in-dialog.jsx (ViamarSignInDialog).
 *
 * Hard rules honoured: entrance animations animate transform only (never
 * opacity-from-0); no scrollIntoView; the global styles object has a unique
 * name (gatewayStyles), never `const styles`.
 */
(function () {
  var T = window.T || {};
  var FD = window.FD || "'Archivo Expanded','Archivo',system-ui,sans-serif";
  var FB = window.FB || "'Archivo',system-ui,sans-serif";
  var FM = window.FM || "'Space Mono',ui-monospace,monospace";

  var NAVY = T.navy || '#0A1B2E';
  var INK = T.ink || '#0A1B2E';
  var RED = T.red || '#DD1C24';
  var PAPER = '#F7F4ED';
  var BODY = T.body || '#3A4A59';
  var MUTED = T.muted || '#6B7B8B';
  var LINE = T.line || '#E5E8EC';
  var GREEN = T.green || '#2E8B6F';
  var AMBER = T.amber || '#E0922F';

  var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  // ── Inject keyframes once. Entrances translate only (hard rule). ──────────
  function ensureGatewayStyles() {
    if (document.getElementById('viamar-gateway-style')) return;
    var st = document.createElement('style');
    st.id = 'viamar-gateway-style';
    st.textContent =
      '@keyframes gatewayRise { from { transform: translateY(20px); } to { transform: translateY(0); } }\n' +
      '@keyframes gatewayRiseSm { from { transform: translateY(12px); } to { transform: translateY(0); } }\n' +
      '@keyframes gatewaySpin { to { transform: rotate(360deg); } }\n' +
      '.gw-rise { animation: gatewayRise .42s cubic-bezier(.22,.61,.36,1) both; }\n' +
      '.gw-rise-1 { animation: gatewayRise .42s cubic-bezier(.22,.61,.36,1) .06s both; }\n' +
      '.gw-rise-2 { animation: gatewayRise .42s cubic-bezier(.22,.61,.36,1) .12s both; }\n' +
      '.gw-rise-3 { animation: gatewayRise .42s cubic-bezier(.22,.61,.36,1) .18s both; }\n' +
      '.gw-rise-sm { animation: gatewayRiseSm .34s cubic-bezier(.22,.61,.36,1) both; }\n' +
      '.gw-spin { animation: gatewaySpin .8s linear infinite; }\n';
    document.head.appendChild(st);
  }

  // ── Style object (uniquely named — never `styles`). ───────────────────────
  var gatewayStyles = {
    shell: {
      minHeight: '100vh', width: '100%', background: PAPER,
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      fontFamily: FB, color: INK,
    },
    topbar: {
      width: '100%', background: NAVY,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '14px 22px', boxSizing: 'border-box',
    },
    inner: {
      width: '100%', maxWidth: 760, padding: '40px 20px 56px',
      boxSizing: 'border-box', display: 'flex', flexDirection: 'column', gap: 26,
    },
    tagline: {
      fontFamily: FB, fontSize: 15.5, color: BODY, lineHeight: 1.55, maxWidth: 460,
    },
    forkRow: {
      display: 'flex', gap: 14, flexWrap: 'wrap',
    },
    card: {
      background: '#fff', borderRadius: 20, border: '1px solid ' + (T.line2 || '#EEF1F4'),
      boxShadow: '0 1px 2px rgba(10,27,46,0.04), 0 8px 24px rgba(10,27,46,0.05)',
      padding: 22, boxSizing: 'border-box',
    },
    input: {
      width: '100%', padding: '13px 15px', borderRadius: 12,
      border: '1.5px solid ' + LINE, outline: 'none',
      fontFamily: FB, fontSize: 15, color: INK, background: '#fff',
      boxSizing: 'border-box',
    },
    label: {
      fontFamily: FM, fontSize: 10.5, fontWeight: 700, letterSpacing: '.12em',
      textTransform: 'uppercase', color: MUTED, marginBottom: 6, display: 'block',
    },
  };

  // ── Navigation helpers ────────────────────────────────────────────────────
  function go(path) {
    window.location.href = path;
  }

  function openSignIn() {
    if (window.ViamarSignInDialog && window.ViamarSignInDialog.open) {
      window.ViamarSignInDialog.open({ returnPath: '/desktop/' });
    } else {
      go('/login/');
    }
  }

  // ── Big fork button (red primary / navy outline) ──────────────────────────
  function ForkButton(props) {
    var pressState = React.useState(false);
    var pressed = pressState[0], setPressed = pressState[1];
    var primary = props.variant === 'primary';
    var base = {
      flex: '1 1 240px', minWidth: 0,
      display: 'flex', flexDirection: 'column', gap: 6,
      textAlign: 'left', cursor: 'pointer',
      border: 0, borderRadius: 18, padding: '20px 22px',
      fontFamily: FB, transition: 'transform .12s ease, box-shadow .2s ease',
      transform: pressed ? 'scale(0.98)' : 'scale(1)',
    };
    var variantStyle = primary
      ? { background: RED, color: '#fff', boxShadow: '0 10px 28px rgba(221,28,36,0.30)' }
      : { background: 'transparent', color: NAVY, boxShadow: 'inset 0 0 0 1.5px ' + NAVY };
    return React.createElement('button', {
      type: 'button',
      onClick: props.onClick,
      onMouseDown: function () { setPressed(true); },
      onMouseUp: function () { setPressed(false); },
      onMouseLeave: function () { setPressed(false); },
      style: Object.assign({}, base, variantStyle, props.style || {}),
    }, [
      React.createElement('span', {
        key: 'h',
        style: { fontFamily: FD, fontWeight: 900, fontSize: 19, letterSpacing: '-.01em' },
      }, props.title),
      React.createElement('span', {
        key: 's',
        style: {
          fontFamily: FB, fontSize: 13, lineHeight: 1.4,
          color: primary ? 'rgba(255,255,255,0.85)' : MUTED,
        },
      }, props.sub),
    ]);
  }

  // ── Track-by-reference status card pieces ────────────────────────────────
  function priceLine(data) {
    if (data.price_status === 'in_review') {
      return { tone: AMBER, text: 'Quote in review — your agent is preparing your price' };
    }
    if (data.final_price != null && data.final_price !== '') {
      var cur = (data.currency || 'CAD').toUpperCase();
      var amount = typeof data.final_price === 'number'
        ? data.final_price.toLocaleString('en-CA')
        : String(data.final_price);
      return { tone: GREEN, text: 'Your quote: $' + amount + ' ' + cur };
    }
    return null;
  }

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

  function StatusCard(props) {
    var data = props.data;
    var origin = data.origin || 'Origin';
    var destCity = data.destination_city || '';
    var destCountry = data.destination_country || '';
    var dest = [destCity, destCountry].filter(Boolean).join(', ') || data.destination || 'Destination';

    var milestones = Array.isArray(data.milestones) ? data.milestones : [];
    var currentId = data.current_milestone;
    var current = null;
    for (var i = 0; i < milestones.length; i++) {
      if (currentId && milestones[i].milestone === currentId) { current = milestones[i]; break; }
    }
    if (!current && milestones.length) current = milestones[milestones.length - 1];

    var price = priceLine(data);
    var shipment = data.shipment || null;

    return React.createElement('div', {
      className: 'gw-rise-sm',
      style: {
        marginTop: 16, borderRadius: 16, border: '1px solid ' + LINE,
        background: PAPER, overflow: 'hidden',
      },
    }, [
      // Header — ref + route
      React.createElement('div', {
        key: 'head',
        style: { background: NAVY, color: '#fff', padding: '16px 18px' },
      }, [
        React.createElement('div', {
          key: 'ref',
          style: { fontFamily: FM, fontSize: 10.5, letterSpacing: '.12em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)', fontWeight: 700 },
        }, data.ref || 'Shipment'),
        React.createElement('div', {
          key: 'route',
          style: { fontFamily: FD, fontWeight: 900, fontSize: 18, letterSpacing: '-.01em', marginTop: 4, lineHeight: 1.2 },
        }, [origin, React.createElement('span', { key: 'arr', style: { color: RED, margin: '0 8px' } }, '→'), dest]),
        (data.cargo_type || data.method) ? React.createElement('div', {
          key: 'meta',
          style: { fontFamily: FB, fontSize: 12.5, color: 'rgba(255,255,255,0.72)', marginTop: 6 },
        }, [data.cargo_type, data.method].filter(Boolean).join(' · ')) : null,
      ].filter(Boolean)),

      // Body
      React.createElement('div', { key: 'body', style: { padding: '16px 18px', display: 'flex', flexDirection: 'column', gap: 14 } }, [
        price ? React.createElement('div', {
          key: 'price',
          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 ' + LINE,
          },
        }, price.text) : null,

        current ? React.createElement('div', { key: 'cur', style: { display: 'flex', flexDirection: 'column', gap: 3 } }, [
          React.createElement('div', {
            key: 'l',
            style: { fontFamily: FD, fontWeight: 800, fontSize: 15, color: INK },
          }, current.label || 'In progress'),
          current.detail ? React.createElement('div', {
            key: 'd',
            style: { fontFamily: FB, fontSize: 13, color: BODY, lineHeight: 1.5 },
          }, current.detail) : null,
        ].filter(Boolean)) : null,

        shipment ? React.createElement('div', {
          key: 'ship',
          style: { display: 'flex', gap: 18, flexWrap: 'wrap', fontFamily: FB, fontSize: 13, color: BODY },
        }, [
          shipment.eta ? React.createElement('span', { key: 'eta' }, [
            React.createElement('span', { key: 'k', style: { color: MUTED } }, 'ETA: '),
            shipment.eta,
          ]) : null,
          shipment.vessel ? React.createElement('span', { key: 'ves' }, [
            React.createElement('span', { key: 'k', style: { color: MUTED } }, 'Vessel: '),
            shipment.vessel,
          ]) : null,
          shipment.status ? React.createElement('span', { key: 'st' }, [
            React.createElement('span', { key: 'k', style: { color: MUTED } }, 'Status: '),
            shipment.status,
          ]) : null,
        ].filter(Boolean)) : null,

        // Compact milestone timeline
        milestones.length ? React.createElement('div', { key: 'tl', style: { display: 'flex', flexDirection: 'column', gap: 0, marginTop: 2 } },
          milestones.map(function (m, idx) {
            var isCurrent = current && m.milestone === current.milestone;
            var last = idx === milestones.length - 1;
            return React.createElement('div', {
              key: m.milestone || idx,
              style: { display: 'flex', gap: 12, alignItems: 'stretch' },
            }, [
              React.createElement('div', { key: 'rail', style: { display: 'flex', flexDirection: 'column', alignItems: 'center', width: 14 } }, [
                React.createElement('span', {
                  key: 'dot',
                  style: {
                    width: 10, height: 10, borderRadius: '50%', flexShrink: 0, marginTop: 4,
                    background: isCurrent ? RED : GREEN,
                    boxShadow: isCurrent ? '0 0 0 4px rgba(221,28,36,0.16)' : 'none',
                  },
                }),
                !last ? React.createElement('span', {
                  key: 'ln',
                  style: { width: 2, flex: 1, background: LINE, marginTop: 2, minHeight: 14 },
                }) : null,
              ].filter(Boolean)),
              React.createElement('div', { key: 'txt', style: { paddingBottom: last ? 0 : 12, flex: 1 } }, [
                React.createElement('div', {
                  key: 'l',
                  style: { fontFamily: FB, fontWeight: isCurrent ? 800 : 600, fontSize: 13.5, color: isCurrent ? INK : BODY },
                }, m.label || m.milestone),
                React.createElement('div', { key: 'meta', style: { display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 1 } }, [
                  m.detail ? React.createElement('span', {
                    key: 'd',
                    style: { fontFamily: FB, fontSize: 12, color: MUTED, lineHeight: 1.45 },
                  }, m.detail) : null,
                  formatStamp(m.created_at) ? React.createElement('span', {
                    key: 's',
                    style: { fontFamily: FM, fontSize: 10.5, color: T.faint || '#9AA7B4' },
                  }, formatStamp(m.created_at)) : null,
                ].filter(Boolean)),
              ]),
            ]);
          })
        ) : null,
      ].filter(Boolean)),
    ]);
  }

  // ── Track-by-reference block ──────────────────────────────────────────────
  function TrackBlock() {
    var refState = React.useState('');
    var ref = refState[0], setRef = refState[1];
    var emailState = React.useState('');
    var email = emailState[0], setEmail = emailState[1];
    var phaseState = React.useState('idle'); // 'idle' | 'loading' | 'done'
    var phase = phaseState[0], setPhase = phaseState[1];
    var resultState = React.useState(null);
    var result = resultState[0], setResult = resultState[1];
    var errState = React.useState(null);
    var err = errState[0], setErr = errState[1];

    function track() {
      var r = (ref || '').trim();
      var 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');

      var base = (window.VIAMAR_API_BASE || '').replace(/\/+$/, '');
      if (!base) {
        setPhase('done');
        setResult({ found: false });
        return;
      }
      var url = base + '/app/track?ref=' + encodeURIComponent(r) + '&email=' + encodeURIComponent(e);
      fetch(url, { headers: { 'Content-Type': 'application/json' } })
        .then(function (res) { return res.json().catch(function () { return {}; }); })
        .then(function (json) {
          setResult(json || { found: false });
          setPhase('done');
        })
        .catch(function () {
          setResult({ found: false, _network: true });
          setPhase('done');
        });
    }

    var loading = phase === 'loading';
    var notFound = phase === 'done' && result && !result.found;
    var found = phase === 'done' && result && result.found;

    return React.createElement('div', { className: 'gw-rise-2', style: gatewayStyles.card }, [
      React.createElement('div', { key: 'head', style: { display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 14 } }, [
        React.createElement('div', {
          key: 'k',
          style: { fontFamily: FM, fontSize: 10.5, fontWeight: 700, letterSpacing: '.14em', textTransform: 'uppercase', color: RED },
        }, 'Track a shipment'),
        React.createElement('div', {
          key: 't',
          style: { fontFamily: FD, fontWeight: 900, fontSize: 18, color: INK, letterSpacing: '-.01em' },
        }, 'Check status — no sign-in needed'),
      ]),

      React.createElement('div', { key: 'fields', style: { display: 'flex', gap: 12, flexWrap: 'wrap' } }, [
        React.createElement('div', { key: 'r', style: { flex: '1 1 200px', minWidth: 0 } }, [
          React.createElement('label', { key: 'l', htmlFor: 'gw-ref', style: gatewayStyles.label }, 'Reference'),
          React.createElement('input', {
            key: 'i', id: 'gw-ref', type: 'text', value: ref,
            placeholder: 'VMR-12345', autoComplete: 'off', spellCheck: false,
            disabled: loading,
            onChange: function (ev) { setRef(ev.target.value); if (err) setErr(null); },
            onKeyDown: function (ev) { if (ev.key === 'Enter' && !loading) track(); },
            style: gatewayStyles.input,
          }),
        ]),
        React.createElement('div', { key: 'e', style: { flex: '1 1 200px', minWidth: 0 } }, [
          React.createElement('label', { key: 'l', htmlFor: 'gw-email', style: gatewayStyles.label }, 'Email'),
          React.createElement('input', {
            key: 'i', id: 'gw-email', type: 'email', value: email,
            placeholder: 'you@example.com', autoComplete: 'email', spellCheck: false,
            disabled: loading,
            onChange: function (ev) { setEmail(ev.target.value); if (err) setErr(null); },
            onKeyDown: function (ev) { if (ev.key === 'Enter' && !loading) track(); },
            style: gatewayStyles.input,
          }),
        ]),
      ]),

      err ? React.createElement('div', {
        key: 'err',
        style: { fontFamily: FB, fontSize: 12.5, fontWeight: 600, color: RED, marginTop: 10 },
      }, err) : null,

      React.createElement('button', {
        key: 'btn',
        type: 'button',
        onClick: track,
        disabled: loading,
        style: {
          marginTop: 14, width: '100%', background: loading ? 'rgba(10,27,46,0.55)' : NAVY,
          color: '#fff', border: 0, padding: '14px 22px', borderRadius: 12,
          fontFamily: FB, fontWeight: 800, fontSize: 14.5, cursor: loading ? 'default' : 'pointer',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 9,
        },
      }, loading
        ? [React.createElement('span', {
            key: 'sp', className: 'gw-spin',
            style: { width: 15, height: 15, borderRadius: '50%', border: '2px solid rgba(255,255,255,0.4)', borderTopColor: '#fff', display: 'inline-block' },
          }), 'Checking…']
        : 'Track'),

      notFound ? React.createElement('div', {
        key: 'nf',
        className: 'gw-rise-sm',
        role: 'status',
        style: {
          marginTop: 14, background: 'rgba(221,28,36,0.06)', border: '1px solid rgba(221,28,36,0.2)',
          borderRadius: 12, padding: '12px 14px', fontFamily: FB, fontSize: 13, color: BODY, lineHeight: 1.5,
        },
      }, "We couldn't find a shipment with that reference and email. Double-check both, or sign in.") : null,

      found ? React.createElement(StatusCard, { key: 'sc', data: result }) : null,
    ].filter(Boolean));
  }

  // ── Brand wordmark for the top bar ────────────────────────────────────────
  function Wordmark(props) {
    if (window.ViamarLogo) {
      return React.createElement(window.ViamarLogo, { width: props.width || 120, onDark: true });
    }
    return React.createElement('span', {
      style: { fontFamily: FD, fontWeight: 900, fontSize: props.fs || 20, color: '#fff', letterSpacing: '-.01em' },
    }, ['VIA', React.createElement('span', { key: 'r', style: { color: RED } }, 'MAR')]);
  }

  // ── Root component ────────────────────────────────────────────────────────
  function ViamarGateway() {
    React.useEffect(function () {
      ensureGatewayStyles();
      if (window.ViamarAnalytics && ViamarAnalytics.track) {
        try { ViamarAnalytics.track('gateway_viewed', {}); } catch (e) {}
      }
    }, []);

    return React.createElement('div', { style: gatewayStyles.shell }, [
      // Top bar
      React.createElement('div', { key: 'top', style: gatewayStyles.topbar }, [
        React.createElement('a', {
          key: 'logo', href: 'https://www.viamar.ca/', style: { textDecoration: 'none', display: 'flex' },
        }, React.createElement(Wordmark, { width: 118 })),
        React.createElement('span', {
          key: 'tag',
          style: { fontFamily: FM, fontSize: 10.5, letterSpacing: '.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.65)', fontWeight: 700 },
        }, 'Customer portal'),
      ]),

      // Content
      React.createElement('div', { key: 'inner', style: gatewayStyles.inner }, [
        // Hero
        React.createElement('div', { key: 'hero', className: 'gw-rise', style: { display: 'flex', flexDirection: 'column', gap: 12 } }, [
          React.createElement('div', {
            key: 'k',
            style: { fontFamily: FM, fontSize: 11, fontWeight: 700, letterSpacing: '.16em', textTransform: 'uppercase', color: RED },
          }, 'Since 1976 · CIFFA & FIATA member'),
          React.createElement('div', {
            key: 'h',
            style: { fontFamily: FD, fontWeight: 900, fontSize: 34, lineHeight: 1.1, letterSpacing: '-.02em', color: INK, maxWidth: 520 },
          }, 'Ship anything, anywhere — by sea, land or air.'),
          React.createElement('div', { key: 't', style: gatewayStyles.tagline },
            "Viamar Scilla moves cars, household goods and cargo worldwide from our own Vaughan facility. Get a quote in minutes, or track a shipment already on its way."),
        ]),

        // The fork — two big choices
        React.createElement('div', { key: 'fork', className: 'gw-rise-1', style: gatewayStyles.forkRow }, [
          React.createElement(ForkButton, {
            key: 'quote', variant: 'primary',
            title: 'Get a quote', sub: 'Cars, moving & cargo — priced in minutes',
            onClick: function () { go('/new-quote/'); },
          }),
          React.createElement(ForkButton, {
            key: 'signin', variant: 'outline',
            title: 'Sign in / Track', sub: 'Open your portal — quotes, docs & live status',
            onClick: openSignIn,
          }),
        ]),

        // Track by reference
        React.createElement(TrackBlock, { key: 'track' }),

        // Tertiary demo link — logs into a seeded REAL demo account (falls back
        // to the ?demo=1 mock view if the demo endpoint is unreachable).
        React.createElement('div', { key: 'demo', className: 'gw-rise-3', style: { textAlign: 'center', marginTop: 4 } },
          React.createElement('a', {
            href: '/desktop/?demo=1',
            onClick: function (e) {
              e.preventDefault();
              var API = window.VIAMAR_API_BASE || '';
              fetch(API + '/app/demo').then(function (r) { return r.json(); }).then(function (d) {
                if (d && d.session_token) {
                  try {
                    localStorage.setItem('viamar.customer.session.v1', JSON.stringify({
                      success: true, session_id: d.session_id, session_token: d.session_token,
                      customer: d.customer || { name: 'Demo Customer', email: 'demo@viamar.ca' },
                    }));
                  } catch (err) {}
                  window.location.href = '/desktop/';
                } else {
                  window.location.href = '/desktop/?demo=1';
                }
              }).catch(function () { window.location.href = '/desktop/?demo=1'; });
            },
            style: { fontFamily: FB, fontSize: 13, color: MUTED, textDecoration: 'none', fontWeight: 600 },
          }, 'View live demo →')
        ),

        // Footer line
        React.createElement('div', {
          key: 'foot',
          style: { fontFamily: FM, fontSize: 11, letterSpacing: '.04em', color: T.faint || '#9AA7B4', lineHeight: 1.7, textAlign: 'center', marginTop: 10 },
        }, [
          'Vaughan, ON · ',
          React.createElement('a', { key: 'tel', href: 'tel:+18002777570', style: { color: MUTED, textDecoration: 'none', fontWeight: 700 } }, '1-800-277-7570'),
        ]),
      ]),
    ]);
  }

  ViamarGateway.mount = function (el) {
    ensureGatewayStyles();
    var target = typeof el === 'string' ? document.getElementById(el) : el;
    if (!target) return null;
    var root = ReactDOM.createRoot(target);
    root.render(React.createElement(ViamarGateway));
    return root;
  };

  window.ViamarGateway = ViamarGateway;
})();
