// cache-bust: 1779468723-8d9735
// =========================================================
// members-route.jsx — hash-based gated route for the members area.
//
// /build/#dashboard mounts <MembersArea /> as a full-viewport overlay,
// gated by window.BL_AUTH (login + build_lab_access).
//
// Why hash routing: CF Pages serves /build/index.html regardless of #anchor,
// so we get free deep links without a SPA router or extra HTML files.
//
// Escape closes. 'back to landing' button closes.
// =========================================================

(function () {
  const ROOT_ID = 'bl-members-root';
  const HASH_TRIGGER = '#dashboard';

  const { useState: useStateMR, useEffect: useEffectMR } = React;

  let _root = null;

  // ─────────────────────────────────────────────
  // The gate component
  // ─────────────────────────────────────────────
  function MembersGate() {
    // Poll so we react to login / payment state changes from outside our tree.
    const [, setTick] = useStateMR(0);
    useEffectMR(() => {
      const id = setInterval(() => setTick(t => t + 1), 500);
      return () => clearInterval(id);
    }, []);

    const auth = window.BL_AUTH;
    const ready = !!auth;
    const isLoggedIn = ready && auth.isLoggedIn();
    const hasAccess = ready && auth.hasBuildLabAccess();

    const close = () => { if (window.location.hash === HASH_TRIGGER) window.location.hash = ''; };
    const goPricing = () => {
      close();
      setTimeout(() => {
        const el = document.getElementById('pricing');
        if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }, 80);
    };

    // Common card style for the two paywall/login states
    const card = {
      background: '#fff',
      padding: '32px 28px',
      borderRadius: 10,
      maxWidth: 440,
      width: 'calc(100% - 32px)',
      textAlign: 'center',
      boxShadow: '0 30px 80px rgba(0,0,0,0.35)',
      fontFamily: 'Geist, system-ui, sans-serif',
    };
    const veil = {
      position: 'fixed', inset: 0,
      background: 'rgba(22,17,13,0.78)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      zIndex: 9000,
      backdropFilter: 'blur(4px)',
    };
    const primaryBtn = {
      background: '#d96846', color: '#fff', border: 'none',
      padding: '11px 20px', borderRadius: 6, cursor: 'pointer',
      fontSize: 14, fontWeight: 600, letterSpacing: '.01em',
    };
    const ghostBtn = {
      background: 'transparent', color: '#666', border: '1px solid #d6d2c8',
      padding: '11px 20px', borderRadius: 6, cursor: 'pointer', fontSize: 14,
    };

    // State 1: BL_AUTH not loaded yet -> brief loading state
    if (!ready) {
      return (
        <div style={veil}>
          <div style={{ ...card, opacity: 0.7 }}>
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 12, color: '#999' }}>
              loading...
            </div>
          </div>
        </div>
      );
    }

    // State 2: Not logged in -> sign-in prompt
    if (!isLoggedIn) {
      return (
        <div style={veil}>
          <div style={card}>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
              color: '#d96846', letterSpacing: '.08em', marginBottom: 8,
            }}>
              MEMBERS ONLY
            </div>
            <div style={{ fontSize: 22, fontWeight: 700, color: '#16110d', marginBottom: 10 }}>
              Sign in to open the dashboard.
            </div>
            <p style={{ fontSize: 14, color: '#666', lineHeight: 1.55, margin: 0 }}>
              The members area has every episode, every patch script, and the
              live build log. Magic-link sign-in &mdash; no password.
            </p>
            <div style={{ marginTop: 22, display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
              <button style={primaryBtn} onClick={() => auth.openLogin()}>
                Sign in &rarr;
              </button>
              <button style={ghostBtn} onClick={close}>
                Back to landing
              </button>
            </div>
          </div>
        </div>
      );
    }

    // State 3: Logged in but no Build Lab access -> upsell
    if (!hasAccess) {
      return (
        <div style={veil}>
          <div style={card}>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
              color: '#d96846', letterSpacing: '.08em', marginBottom: 8,
            }}>
              YOU'RE SIGNED IN
            </div>
            <div style={{ fontSize: 22, fontWeight: 700, color: '#16110d', marginBottom: 10 }}>
              One step away.
            </div>
            <p style={{ fontSize: 14, color: '#666', lineHeight: 1.55, margin: 0 }}>
              Join the Build Lab to unlock every module, every patch script, and
              the live build log. Cancel any time.
            </p>
            <div style={{ marginTop: 22, display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
              <button style={primaryBtn} onClick={goPricing}>
                See pricing &rarr;
              </button>
              <button style={ghostBtn} onClick={close}>
                Maybe later
              </button>
            </div>
          </div>
        </div>
      );
    }

    // State 4: Logged in + access -> render MembersArea with a close button
    const MembersAreaComp = window.MembersArea;
    return (
      <div style={{
        position: 'fixed', inset: 0,
        background: 'var(--paper, #f4eee3)',
        zIndex: 8000, overflow: 'auto',
      }}>
        <button
          onClick={close}
          title="Close (Esc)"
          style={{
            position: 'fixed', top: 12, right: 16, zIndex: 8500,
            background: 'rgba(22,17,13,0.85)', color: '#f4eee3',
            border: 'none', borderRadius: 6,
            padding: '8px 14px', cursor: 'pointer',
            fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
            letterSpacing: '.04em',
          }}
        >
          &larr; back to landing
        </button>
        <div style={{ height: '100vh', width: '100%', overflow: 'auto' }}>
          {MembersAreaComp ? <MembersAreaComp /> : (
            <div style={{ padding: 60, textAlign: 'center', color: '#999' }}>
              Loading members area&hellip;
            </div>
          )}
        </div>
      </div>
    );
  }

  // ─────────────────────────────────────────────
  // Mount / unmount lifecycle
  // ─────────────────────────────────────────────
  function mount() {
    if (_root) return;
    let host = document.getElementById(ROOT_ID);
    if (!host) {
      host = document.createElement('div');
      host.id = ROOT_ID;
      document.body.appendChild(host);
    }
    _root = ReactDOM.createRoot(host);
    _root.render(<MembersGate />);
  }

  function unmount() {
    if (!_root) return;
    _root.unmount();
    _root = null;
    const host = document.getElementById(ROOT_ID);
    if (host) host.remove();
  }

  function syncFromHash() {
    if (window.location.hash === HASH_TRIGGER) {
      mount();
    } else {
      unmount();
    }
  }

  // Escape key closes
  window.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && window.location.hash === HASH_TRIGGER) {
      window.location.hash = '';
    }
  });

  // Listen for hash changes
  window.addEventListener('hashchange', syncFromHash);

  // Initial check: if user lands directly on /build/#dashboard
  // (e.g. bookmarked link, or post-checkout redirect), mount immediately.
  // Small delay so BL_AUTH has a chance to initialize.
  setTimeout(syncFromHash, 50);
})();
