/* Viamar — branded sign-in dialog
 *
 * Replaces the window.prompt() email dialog used by ViamarAPI.promptRecovery.
 * Built with the app's own design system (tokens window.T, fonts FD/FB/FM) —
 * shadcn-quality, no bundler needed.
 *
 * Published as window.ViamarSignInDialog = { open(opts) -> Promise, Card }.
 * `Card` is the inner email→link form without the modal backdrop, so the
 * /login page can render the exact same internals inline (no duplicated
 * logic). Card props: initialEmail, onDone, returnPath (forwarded to
 * recoverSession as return_path), showCancel (default true), autoClose
 * (default true — auto-dismiss ~2.5s after the link is sent).
 *
 * The open() promise resolves with the same shape promptRecovery's callers expect:
 *   - { success: false, cancelled: true }  when the user dismisses
 *   - the /app/sessions/recover response   after a link is sent
 * It rejects only if recovery is unavailable; in-dialog API failures show an
 * inline error with retry instead of rejecting, so callers never see a burst
 * of unhandled rejections from a user retry loop.
 *
 * Rendered into a dedicated div appended to document.body via a separate
 * ReactDOM.createRoot — works from both the desktop and mobile shells.
 * Entrance animation: transform translateY only (hard rule — no opacity-from-0).
 */
(function () {
  var dialogHost = null;
  var dialogRoot = null;
  var openPromise = null;

  function ensureKeyframes() {
    if (document.getElementById('viamar-signin-dialog-style')) return;
    var st = document.createElement('style');
    st.id = 'viamar-signin-dialog-style';
    st.textContent =
      '@keyframes viamarSignInCardUp { from { transform: translateY(26px); } to { transform: translateY(0); } }\n' +
      '@keyframes viamarSignInPop { 0% { transform: scale(.5); } 60% { transform: scale(1.12); } 100% { transform: scale(1); } }\n' +
      '.viamar-signin-card { animation: viamarSignInCardUp .34s cubic-bezier(.22,.61,.36,1) both; }\n' +
      '.viamar-signin-pop { animation: viamarSignInPop .5s cubic-bezier(.34,1.56,.64,1) both; }\n';
    document.head.appendChild(st);
  }

  function ensureRoot() {
    if (!dialogRoot) {
      dialogHost = document.createElement('div');
      dialogHost.id = 'viamar-signin-dialog-host';
      document.body.appendChild(dialogHost);
      dialogRoot = ReactDOM.createRoot(dialogHost);
    }
    return dialogRoot;
  }

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

  /* The card itself — branded email→link form with form/sending/sent phases.
     Used by the modal wrapper below and rendered inline by /login. */
  function SignInCard(props) {
    var T = window.T || {};
    var FD = window.FD || "'Archivo Expanded', Archivo, sans-serif";
    var FB = window.FB || 'Archivo, sans-serif';
    var FM = window.FM || "'Space Mono', monospace";
    var navy = T.navy || '#0A1B2E';
    var ink = T.ink || '#0A1B2E';
    var red = T.red || '#DD1C24';
    var green = T.green || '#2E8B6F';
    var muted = T.muted || '#5A6B7F';
    var line2 = T.line2 || '#D7D2C6';

    var emailState = React.useState(props.initialEmail || '');
    var email = emailState[0], setEmail = emailState[1];
    var phaseState = React.useState('form'); // 'form' | 'sending' | 'sent'
    var phase = phaseState[0], setPhase = phaseState[1];
    var errorState = React.useState(null);
    var error = errorState[0], setError = errorState[1];
    var resultRef = React.useRef(null);
    var inputRef = React.useRef(null);
    var onDone = props.onDone || function () {};
    var showCancel = props.showCancel !== false;
    var autoClose = props.autoClose !== false;

    ensureKeyframes(); // idempotent — inline (page) usage needs them too

    // Focus the input on open.
    React.useEffect(function () {
      if (inputRef.current) inputRef.current.focus();
    }, []);

    var cancel = React.useCallback(function () {
      // Closing after the link was sent still counts as success.
      if (resultRef.current) onDone(resultRef.current);
      else onDone({ success: false, cancelled: true });
    }, [onDone]);

    // Let the modal wrapper trigger cancel (backdrop click) without owning state.
    if (props.cancelRef) props.cancelRef.current = cancel;

    // Escape key = cancel (modal only — the inline page has nothing to close).
    React.useEffect(function () {
      if (!showCancel) return;
      function onKey(e) { if (e.key === 'Escape') cancel(); }
      window.addEventListener('keydown', onKey);
      return function () { window.removeEventListener('keydown', onKey); };
    }, [cancel, showCancel]);

    // Success state auto-closes after ~2.5s (modal only).
    React.useEffect(function () {
      if (phase !== 'sent' || !autoClose) return;
      var t = setTimeout(function () { onDone(resultRef.current); }, 2500);
      return function () { clearTimeout(t); };
    }, [phase, onDone, autoClose]);

    function send() {
      var value = (email || '').trim();
      if (!EMAIL_RE.test(value)) {
        setError('Please enter a valid email address.');
        if (inputRef.current) inputRef.current.focus();
        return;
      }
      setError(null);
      setPhase('sending');
      var api = window.ViamarAPI;
      if (!api || !api.recoverSession) {
        setError('Sign-in is unavailable right now. Please call 1-800-277-7570.');
        setPhase('form');
        return;
      }
      api.recoverSession({
        email: value,
        return_path: props.returnPath || undefined,
      }).then(function (res) {
        if (res && res.magic_link) console.log('Viamar recovery link:', res.magic_link);
        resultRef.current = res;
        setPhase('sent');
      }).catch(function (err) {
        setError('Could not send the link: ' + ((err && err.message) || 'network error') + '. Please try again.');
        setPhase('form');
      });
    }

    var sending = phase === 'sending';

    var body;
    if (phase === 'sent') {
      body = React.createElement('div', {
        key: 'sent',
        style: { display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 12, padding: '14px 0 4px' },
      }, [
        React.createElement('div', {
          key: 'check',
          className: 'viamar-signin-pop',
          style: { width: 52, height: 52, borderRadius: '50%', background: green, display: 'flex', alignItems: 'center', justifyContent: 'center' },
        }, React.createElement('svg', { width: 26, height: 26, viewBox: '0 0 24 24', fill: 'none' },
          React.createElement('path', { d: 'M5 12.5l5 5L19 7.5', stroke: '#fff', strokeWidth: 3, strokeLinecap: 'round', strokeLinejoin: 'round' })
        )),
        React.createElement('div', {
          key: 'h',
          style: { fontFamily: FD, fontWeight: 900, fontSize: 19, color: ink, letterSpacing: '-.015em' },
        }, 'Link sent — check your inbox'),
        React.createElement('div', {
          key: 's',
          style: { fontFamily: FB, fontSize: 13.5, color: muted, lineHeight: 1.55, maxWidth: 300 },
        }, 'It can take a minute. The link signs you in instantly.'),
      ]);
    } else {
      body = React.createElement('div', {
        key: 'form',
        style: { display: 'flex', flexDirection: 'column', gap: 14 },
      }, [
        React.createElement('input', {
          key: 'input',
          ref: inputRef,
          type: 'email',
          value: email,
          disabled: sending,
          placeholder: 'you@example.com',
          autoComplete: 'email',
          spellCheck: false,
          onChange: function (e) { setEmail(e.target.value); if (error) setError(null); },
          onKeyDown: function (e) { if (e.key === 'Enter' && !sending) send(); },
          style: {
            width: '100%', padding: '14px 16px', borderRadius: 12,
            border: '1.5px solid ' + (error ? red : line2),
            outline: 'none', fontFamily: FB, fontSize: 15, color: ink,
            background: sending ? (T.paper || '#F7F4ED') : '#fff',
            boxSizing: 'border-box',
          },
        }),
        error ? React.createElement('div', {
          key: 'err',
          style: { fontFamily: FB, fontSize: 12.5, fontWeight: 600, color: red, lineHeight: 1.45, marginTop: -6 },
        }, error) : null,
        React.createElement('button', {
          key: 'send',
          onClick: send,
          disabled: sending,
          style: {
            width: '100%', background: sending ? 'rgba(221,28,36,0.55)' : red, color: '#fff',
            border: 0, padding: '15px 22px', borderRadius: 12, fontFamily: FB,
            fontWeight: 800, fontSize: 14.5, letterSpacing: '.01em',
            cursor: sending ? 'default' : 'pointer',
          },
        }, sending ? 'Sending…' : 'Email me a sign-in link'),
        showCancel ? React.createElement('button', {
          key: 'cancel',
          onClick: cancel,
          style: {
            width: '100%', background: 'transparent', color: muted,
            border: 0, padding: '10px 22px', borderRadius: 12, fontFamily: FB,
            fontWeight: 700, fontSize: 13.5, cursor: 'pointer',
          },
        }, 'Cancel') : null,
      ].filter(Boolean));
    }

    return React.createElement('div', {
      className: 'viamar-signin-card',
      role: showCancel ? 'dialog' : undefined,
      'aria-modal': showCancel ? true : undefined,
      'aria-label': 'Sign in to your portal',
      style: {
        width: '100%', maxWidth: 420, background: '#fff', borderRadius: 20,
        padding: '30px 30px 22px', boxShadow: '0 30px 90px rgba(0,0,0,0.45)',
        display: 'flex', flexDirection: 'column', gap: 16, boxSizing: 'border-box',
      },
    }, [
      // VIAMAR wordmark
      React.createElement('div', { key: 'mark', style: { display: 'flex' } },
        window.ViamarLogo
          ? React.createElement(window.ViamarLogo, { width: 118 })
          : React.createElement('span', {
              style: { fontFamily: FD, fontWeight: 900, fontSize: 20, letterSpacing: '-.01em', color: navy },
            }, ['VIA', React.createElement('span', { key: 'r', style: { color: red } }, 'MAR')])
      ),
      phase !== 'sent' ? React.createElement('div', { key: 'head', style: { display: 'flex', flexDirection: 'column', gap: 8 } }, [
        React.createElement('div', {
          key: 'title',
          style: { fontFamily: FD, fontWeight: 900, fontSize: 22, color: ink, letterSpacing: '-.018em', lineHeight: 1.12 },
        }, 'Sign in to your portal'),
        React.createElement('div', {
          key: 'body',
          style: { fontFamily: FB, fontSize: 13.5, color: muted, lineHeight: 1.55 },
        }, "Enter the email you used for your quote or shipment — we'll send you a secure sign-in link."),
      ]) : null,
      body,
    ].filter(Boolean));
  }

  /* Modal wrapper — fixed backdrop + the card. Backdrop click = cancel. */
  function SignInDialog(props) {
    var cancelRef = React.useRef(null);
    return React.createElement('div', {
      onMouseDown: function (e) {
        if (e.target === e.currentTarget && cancelRef.current) cancelRef.current();
      },
      style: {
        position: 'fixed', inset: 0, zIndex: 9990,
        background: 'rgba(6,16,28,0.55)',
        backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20,
      },
    }, React.createElement(SignInCard, {
      initialEmail: props.initialEmail,
      onDone: props.onDone,
      cancelRef: cancelRef,
    }));
  }

  function closeDialog() {
    if (dialogRoot) dialogRoot.render(null);
    openPromise = null;
  }

  function open(opts) {
    if (openPromise) return openPromise; // already open — share the result
    ensureKeyframes();
    var root = ensureRoot();
    openPromise = new Promise(function (resolve) {
      root.render(React.createElement(SignInDialog, {
        initialEmail: (opts && opts.email) || '',
        onDone: function (res) {
          closeDialog();
          resolve(res || { success: false, cancelled: true });
        },
      }));
    });
    return openPromise;
  }

  window.ViamarSignInDialog = { open: open, Card: SignInCard };
})();
