/* Viamar — useAuth() hook + sign-in primitives
 *
 * Lets every surface render based on real auth state instead of pretending
 * to be Alessandro M. Drops the fake identity for anonymous visitors and
 * pulls real shipments from ViamarStore for logged-in customers.
 *
 * Escape hatch: ?demo=1 in the URL forces "fake account" mode for
 * screenshots and decks (loads mock SHIPMENTS as Alessandro). Without it,
 * anonymous = anonymous.
 *
 * Loaded as window.ViamarAuth: { useAuth, AnonymousWelcome, EmptyShipments, isDemoMode }
 */
(function () {
  function getQueryFlag(name) {
    try {
      return new URLSearchParams(window.location.search).get(name);
    } catch (e) {
      return null;
    }
  }

  function isDemoMode() {
    // ?demo=1 or stored toggle (for stage screenshots without leaking the
    // flag in URLs after the first nav). Default: NOT demo — anonymous
    // users see the empty state.
    if (getQueryFlag('demo') === '1') {
      try { sessionStorage.setItem('viamar.demo', '1'); } catch (e) {}
      return true;
    }
    if (getQueryFlag('demo') === '0') {
      try { sessionStorage.removeItem('viamar.demo'); } catch (e) {}
      return false;
    }
    try { return sessionStorage.getItem('viamar.demo') === '1'; } catch (e) { return false; }
  }

  function useAuth() {
    const [state, setState] = React.useState({
      loading: true,
      session: null,
      customer: null,
      shipments: null,        // null = unknown, [] = empty, [...] = real list
      syncMeta: {},
    });

    React.useEffect(function () {
      let mounted = true;
      let stopCustomerStatePolling = null;

      (async function init() {
        // 1. If ?magic=… is in the URL, exchange it for a session first.
        try {
          if (window.ViamarAPI && ViamarAPI.magicReady) {
            await ViamarAPI.magicReady;
          } else if (window.ViamarAPI && ViamarAPI.consumeMagicFromUrl) {
            await ViamarAPI.consumeMagicFromUrl();
          }
        } catch (e) { /* non-fatal */ }

        // 2. Read current session from localStorage.
        const session = (window.ViamarAPI && ViamarAPI.session) ? ViamarAPI.session() : null;
        const hasToken = !!(session && session.session_token);
        const customer = (session && session.customer) || null;

        // 3. If we have a session, fetch the customer's real shipments.
        let shipments = null;
        let syncMeta = {};
        if (hasToken && window.ViamarStore && ViamarStore.syncCustomerState) {
          try {
            shipments = await ViamarStore.syncCustomerState();
            if (!Array.isArray(shipments)) shipments = [];
          } catch (e) {
            shipments = [];
          }
          if (ViamarStore.getSyncMeta) syncMeta = ViamarStore.getSyncMeta();
          if (mounted && ViamarStore.startCustomerStatePolling) {
            stopCustomerStatePolling = ViamarStore.startCustomerStatePolling({ immediate: false });
          }
        }

        if (mounted) {
          setState({
            loading: false,
            session: session,
            customer: customer,
            shipments: shipments,
            syncMeta: syncMeta,
          });
        }
      })();

      // 4. Listen for store updates (quote submitted, magic-link consumed).
      let refreshInFlight = false;
      const off = (window.ViamarStore && ViamarStore.subscribe)
        ? ViamarStore.subscribe(function () {
            if (!mounted) return;
            const session = (window.ViamarAPI && ViamarAPI.session) ? ViamarAPI.session() : null;
            const customer = (session && session.customer) || null;
            const shipments = window.ViamarStore.getShipments();
            const syncMeta = window.ViamarStore.getSyncMeta ? window.ViamarStore.getSyncMeta() : {};
            setState(function (prev) {
              return Object.assign({}, prev, {
                session: session,
                customer: customer,
                shipments: shipments,
                syncMeta: syncMeta,
              });
            });
            if (session && session.session_token && shipments.length === 0 && !refreshInFlight && ViamarStore.syncCustomerState) {
              refreshInFlight = true;
              ViamarStore.syncCustomerState().then(function (fresh) {
                if (!mounted) return;
                setState(function (prev) {
                  return Object.assign({}, prev, {
                    session: session,
                    customer: customer,
                    shipments: Array.isArray(fresh) ? fresh : [],
                    syncMeta: ViamarStore.getSyncMeta ? ViamarStore.getSyncMeta() : {},
                  });
                });
              }).catch(function () {}).finally(function () {
                refreshInFlight = false;
              });
            }
          })
        : null;

      return function () {
        mounted = false;
        if (typeof stopCustomerStatePolling === 'function') stopCustomerStatePolling();
        if (off) off();
      };
    }, []);

    const signIn = React.useCallback(function () {
      if (!window.ViamarAPI || !ViamarAPI.promptRecovery) return Promise.resolve();
      return ViamarAPI.promptRecovery();
    }, []);

    const retrySync = React.useCallback(function () {
      if (!window.ViamarStore || !ViamarStore.syncCustomerState) return Promise.resolve([]);
      setState(function (prev) {
        return Object.assign({}, prev, { loading: true });
      });
      return ViamarStore.syncCustomerState().then(function (shipments) {
        const session = (window.ViamarAPI && ViamarAPI.session) ? ViamarAPI.session() : null;
        setState(function (prev) {
          return Object.assign({}, prev, {
            loading: false,
            session: session,
            customer: (session && session.customer) || null,
            shipments: Array.isArray(shipments) ? shipments : [],
            syncMeta: ViamarStore.getSyncMeta ? ViamarStore.getSyncMeta() : {},
          });
        });
        return shipments;
      }).catch(function (error) {
        setState(function (prev) {
          return Object.assign({}, prev, {
            loading: false,
            syncMeta: ViamarStore.getSyncMeta
              ? ViamarStore.getSyncMeta()
              : { stale: true, updatedLabel: null },
          });
        });
        throw error;
      });
    }, []);

    const signOut = React.useCallback(function () {
      // ViamarAPI owns the session key ('viamar.customer.session.v1') — use
      // its clearSession so the key never drifts again. ('viamar.session.v1'
      // was a stale key name; kept for cleanup of old browsers.)
      try { if (window.ViamarAPI && ViamarAPI.clearSession) ViamarAPI.clearSession(); } catch (e) {}
      try { if (window.ViamarStore && ViamarStore.clear) ViamarStore.clear(); } catch (e) {}
      try { localStorage.removeItem('viamar.customer.session.v1'); } catch (e) {}
      try { localStorage.removeItem('viamar.session.v1'); } catch (e) {}
      try { localStorage.removeItem('viamar.shipments.v1'); } catch (e) {}
      try { localStorage.removeItem('viamar.api.queue.v1'); } catch (e) {}
      try { sessionStorage.removeItem('viamar.demo'); } catch (e) {}
      window.location.reload();
    }, []);

    // The seeded "View live demo" account is a REAL session (real seeded
    // shipments), so it stays authenticated and is NOT demoMode (which loads
    // mock SHIPMENTS). We only flag it so surfaces can mark it clearly + offer
    // a one-tap exit. Detected by the seeded session_id or the demo email.
    const isDemoAccount = !!(
      state.session && (
        state.session.session_id === 'demo-session-viamar' ||
        (state.customer && state.customer.email === 'demo@viamar.ca')
      )
    );

    const portal = (window.ViamarAuthState && window.ViamarAuthState.resolve)
      ? window.ViamarAuthState.resolve({
          session: state.session,
          demoRequested: isDemoMode(),
          shipments: state.shipments,
          syncMeta: state.syncMeta,
          loading: state.loading,
        })
      : {
          mode: 'anonymous',
          isAuthenticated: false,
          demoMode: false,
          syncStatus: 'idle',
          syncUpdatedLabel: null,
        };

    return Object.assign({}, state, portal, {
      isDemoAccount: isDemoAccount,
      signIn: signIn,
      retrySync: retrySync,
      signOut: signOut,
    });
  }

  // Pure-render landing card for anonymous visitors. Caller wires onQuote /
  // onSignIn so the same component works on desktop + mobile.
  function AnonymousWelcome(props) {
    const { onQuote, onSignIn, compact, headline, subline } = props;
    const T = window.T || {};
    const FD = window.FD || 'Archivo, sans-serif';
    const FB = window.FB || 'Archivo, sans-serif';
    const FM = window.FM || 'Space Mono, monospace';

    return React.createElement('div', {
      style: {
        background: '#fff',
        border: '1px solid ' + (T.line2 || '#D7D2C6'),
        borderRadius: 20,
        padding: compact ? 24 : '36px 32px',
        boxShadow: '0 8px 24px rgba(10,27,46,.06)',
        display: 'flex',
        flexDirection: 'column',
        gap: 18,
        textAlign: compact ? 'left' : 'center',
        alignItems: compact ? 'flex-start' : 'center',
      },
    }, [
      React.createElement('div', {
        key: 'k',
        style: {
          fontFamily: FM, fontSize: 11, letterSpacing: '.14em',
          textTransform: 'uppercase', color: T.red || '#DD1C24', fontWeight: 700,
        },
      }, 'Viamar Portal'),
      React.createElement('div', {
        key: 'h',
        style: {
          fontFamily: FD, fontWeight: 900, fontSize: compact ? 22 : 28,
          color: T.ink || '#0A1B2E', lineHeight: 1.1, letterSpacing: '-.018em',
          maxWidth: 480,
        },
      }, headline || 'Welcome to your shipping portal.'),
      React.createElement('div', {
        key: 's',
        style: {
          fontFamily: FB, fontSize: 14.5, color: T.muted || '#5A6B7F',
          lineHeight: 1.55, maxWidth: 480,
        },
      }, subline || 'Sign in to see your quotes and shipments, or get a new quote in 60 seconds.'),
      React.createElement('div', {
        key: 'a',
        style: { display: 'flex', gap: 10, flexWrap: 'wrap', marginTop: 6 },
      }, [
        React.createElement('button', {
          key: 'q',
          onClick: onQuote,
          style: {
            background: T.red || '#DD1C24', color: '#fff', border: 0,
            padding: '14px 22px', borderRadius: 12, fontFamily: FB,
            fontWeight: 800, fontSize: 14, cursor: 'pointer',
            letterSpacing: '.01em',
          },
        }, 'Get a quote →'),
        React.createElement('button', {
          key: 'i',
          onClick: onSignIn,
          style: {
            background: 'transparent', color: T.navy || '#0A1B2E',
            border: '1.5px solid ' + (T.line2 || '#D7D2C6'),
            padding: '14px 22px', borderRadius: 12, fontFamily: FB,
            fontWeight: 700, fontSize: 14, cursor: 'pointer',
          },
        }, 'I have an account'),
      ]),
    ]);
  }

  // Empty state for authenticated customers with no shipments.
  function EmptyShipments(props) {
    const { onQuote, compact } = props;
    const T = window.T || {};
    const FD = window.FD || 'Archivo, sans-serif';
    const FB = window.FB || 'Archivo, sans-serif';
    const FM = window.FM || 'Space Mono, monospace';

    return React.createElement('div', {
      style: {
        background: '#fff',
        border: '1px dashed ' + (T.line2 || '#D7D2C6'),
        borderRadius: 16,
        padding: compact ? '28px 20px' : '40px 32px',
        textAlign: 'center',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: 12,
      },
    }, [
      React.createElement('div', {
        key: 'k',
        style: {
          fontFamily: FM, fontSize: 10.5, letterSpacing: '.12em',
          textTransform: 'uppercase', color: T.muted || '#5A6B7F', fontWeight: 700,
        },
      }, 'Nothing here yet'),
      React.createElement('div', {
        key: 'h',
        style: {
          fontFamily: FD, fontWeight: 900, fontSize: compact ? 18 : 22,
          color: T.ink || '#0A1B2E', maxWidth: 360,
        },
      }, "You haven't shipped with us yet."),
      React.createElement('div', {
        key: 's',
        style: {
          fontFamily: FB, fontSize: 14, color: T.muted || '#5A6B7F',
          maxWidth: 360, lineHeight: 1.5,
        },
      }, 'Get a quote in 60 seconds — our team will reply within one business hour.'),
      React.createElement('button', {
        key: 'b',
        onClick: onQuote,
        style: {
          marginTop: 8, background: T.red || '#DD1C24', color: '#fff', border: 0,
          padding: '13px 22px', borderRadius: 12, fontFamily: FB,
          fontWeight: 800, fontSize: 14, cursor: 'pointer',
        },
      }, 'Get my first quote →'),
    ]);
  }

  // Thin banner shown above logged-in surfaces when demo data is loaded.
  function DemoBanner(props) {
    const T = window.T || {};
    const FB = window.FB || 'Archivo, sans-serif';
    const FM = window.FM || 'Space Mono, monospace';
    return React.createElement('div', {
      style: {
        background: 'rgba(221,28,36,0.08)',
        border: '1px solid rgba(221,28,36,0.2)',
        borderRadius: 10,
        padding: '10px 14px',
        display: 'flex',
        alignItems: 'center',
        gap: 10,
        fontFamily: FM,
        fontSize: 11,
        letterSpacing: '.06em',
        textTransform: 'uppercase',
        fontWeight: 700,
        color: T.red || '#DD1C24',
      },
    }, [
      React.createElement('span', { key: 'd' }, props.label || 'Demo view'),
      React.createElement('span', {
        key: 't',
        style: { color: T.muted || '#5A6B7F', textTransform: 'none', fontWeight: 500, letterSpacing: '0', fontSize: 12 },
      }, props.note || ('Showing sample shipments. ' + (props.onExit ? '' : 'Add ?demo=0 to URL to exit.'))),
      props.onExit ? React.createElement('button', {
        key: 'x',
        onClick: props.onExit,
        style: {
          marginLeft: 'auto', background: 'transparent', border: 0,
          color: T.red || '#DD1C24', cursor: 'pointer', fontWeight: 700,
          fontSize: 11, letterSpacing: '.06em',
        },
      }, props.exitLabel || 'EXIT DEMO') : null,
    ].filter(Boolean));
  }

  function CustomerStateNotice(props) {
    props = props || {};
    if (props.status !== 'stale' && props.status !== 'error') return null;
    const T = window.T || {};
    const FB = window.FB || 'Archivo, sans-serif';
    const FM = window.FM || 'Space Mono, monospace';
    const stale = props.status === 'stale';
    const title = stale
      ? 'Showing your last saved update'
      : "We couldn't load your account updates";
    const detail = stale
      ? ("We couldn't refresh right now." +
          (props.updatedLabel ? ' Last updated ' + props.updatedLabel + '.' : ''))
      : 'Try again, or call 1-800-277-7570 if you need immediate help.';

    return React.createElement('div', {
      role: 'status',
      style: {
        background: stale ? 'rgba(237,164,31,0.10)' : 'rgba(221,28,36,0.08)',
        border: '1px solid ' + (stale ? 'rgba(237,164,31,0.34)' : 'rgba(221,28,36,0.24)'),
        borderRadius: 12,
        padding: props.compact ? '11px 12px' : '13px 15px',
        display: 'flex',
        alignItems: 'center',
        gap: 12,
      },
    }, [
      React.createElement('div', {
        key: 'copy',
        style: { flex: 1, minWidth: 0 },
      }, [
        React.createElement('div', {
          key: 'title',
          style: {
            fontFamily: FB,
            fontWeight: 800,
            fontSize: props.compact ? 12.5 : 13.5,
            color: T.ink || '#0A1B2E',
          },
        }, title),
        React.createElement('div', {
          key: 'detail',
          style: {
            fontFamily: FB,
            fontSize: props.compact ? 11.5 : 12.5,
            color: T.muted || '#5A6B7F',
            lineHeight: 1.45,
            marginTop: 3,
          },
        }, detail),
      ]),
      props.onRetry ? React.createElement('button', {
        key: 'retry',
        onClick: props.onRetry,
        style: {
          flexShrink: 0,
          background: T.navy || '#0A1B2E',
          color: '#fff',
          border: 0,
          borderRadius: 9,
          padding: props.compact ? '8px 10px' : '9px 12px',
          fontFamily: FM,
          fontSize: 10,
          fontWeight: 700,
          cursor: 'pointer',
        },
      }, 'Try again') : null,
    ].filter(Boolean));
  }

  window.ViamarAuth = {
    useAuth: useAuth,
    isDemoMode: isDemoMode,
    AnonymousWelcome: AnonymousWelcome,
    EmptyShipments: EmptyShipments,
    DemoBanner: DemoBanner,
    CustomerStateNotice: CustomerStateNotice,
  };
})();
