// =============================================================
// PROJECT LAZARUS — STORE BOOTSTRAP
// Shared mount logic. Every page HTML sets window.__LAZ_PAGE__
// (and optionally window.__LAZ_MODE__ for storefront pages),
// then loads this file to render the right React component.
// =============================================================

(() => {
  // Pick desktop vs mobile based on viewport width.
  // Fallback (innerWidth=0 in sandboxed iframes etc): default to desktop.
  const safeWidth = () => {
    const w = window.innerWidth || document.documentElement.clientWidth || 0;
    return w > 0 ? w : 1440;
  };

  const useViewport = () => {
    const [w, setW] = React.useState(safeWidth());
    React.useEffect(() => {
      const onResize = () => setW(safeWidth());
      window.addEventListener('resize', onResize);
      return () => window.removeEventListener('resize', onResize);
    }, []);
    return w;
  };

  // Map page identifier -> { Desktop, Mobile } component pair.
  const COMPONENTS = {
    home:       { D: () => window.HomeDesktop,       M: () => window.HomeMobile       },
    storefront: { D: () => window.StorefrontDesktop, M: () => window.StorefrontMobile },
    signin:     { D: () => window.SigninDesktop,     M: () => window.SigninMobile     },
    pdp:        { D: () => window.PDPDesktop,        M: () => window.PDPMobile        },
    cart:       { D: () => window.CartDesktop,       M: () => window.CartMobile       },
    account:    { D: () => window.AccountDesktop,    M: () => window.AccountMobile    },
    success:    { D: () => window.SuccessDesktop,    M: () => window.SuccessMobile    },
    cancel:     { D: () => window.CancelDesktop,     M: () => window.CancelMobile     },
    notfound:   { D: () => window.NotFoundDesktop,   M: () => window.NotFoundMobile   },
    terms:      { D: () => window.TermsDesktop,      M: () => window.TermsMobile      },
    privacy:    { D: () => window.PrivacyDesktop,    M: () => window.PrivacyMobile    },
  };

  const Loading = () => (
    <div style={{
      minHeight: '100vh', display: 'grid', placeItems: 'center',
      fontFamily: 'monospace', color: '#bdb8a8', fontSize: 13
    }}>Loading…</div>
  );

  // Catalog tick: bumps state whenever catalog-sync.js patches CATALOG /
  // TIER_PRODUCTS in place. Listening here forces a re-render of the entire
  // App tree, so any component that reads CATALOG-derived prices (cart,
  // tier card, package card, etc.) picks up the live values without each
  // component having to subscribe individually.
  const useCatalogTick = () => {
    const [t, setT] = React.useState(0);
    React.useEffect(() => {
      const on = () => setT((x) => x + 1);
      window.addEventListener('laz:catalog-changed', on);
      return () => window.removeEventListener('laz:catalog-changed', on);
    }, []);
    return t;
  };

  const App = () => {
    const w = useViewport();
    useCatalogTick();
    const pageKey = window.__LAZ_PAGE__ || 'home';
    const mode = window.__LAZ_MODE__;
    const slot = COMPONENTS[pageKey] || COMPONENTS.home;

    const Desktop = slot.D();
    const Mobile = slot.M();

    if (!Desktop && !Mobile) return <Loading />;

    // Tablet handling: at <1024px the desktop 1440 layout (with 80px
    // section padding + 4-up grids) feels cramped. Drop to the narrow
    // mobile component on iPad-portrait and below; small laptops at
    // ≥1024 still get desktop with eased padding (see style.css).
    const Picked = (w < 1024 && Mobile) ? Mobile : (Desktop || Mobile);

    // Storefront components take a mode prop. Everything else takes none.
    if (pageKey === 'storefront' && mode) {
      return <Picked mode={mode} />;
    }
    return <Picked />;
  };

  ReactDOM.createRoot(document.getElementById('root')).render(<App />);

  // Fetch the current user once and stash it on window so Nav (and any
  // other component) can read it via window.__LAZ_USER__. We dispatch
  // 'laz:auth-changed' after the fetch completes so listeners can react.
  // Also: gate the Account page — if you hit /account/ logged out, we
  // redirect you to the Steam sign-in flow with return_to set.
  (async () => {
    try {
      if (!window.LAZ) return;
      const u = await window.LAZ.me();
      window.__LAZ_USER__ = u;
      window.dispatchEvent(new CustomEvent('laz:auth-changed', { detail: u }));

      const page = window.__LAZ_PAGE__;
      if (page === 'account' && (!u || !u.signed_in)) {
        window.LAZ.signIn('/account/');
      }
    } catch {/* ignore — fall back to logged-out state */}
  })();
})();

