// Pro Gate — wraps AI-feature UI behind Pro status.
//
// Usage (React.createElement style; works for both .jsx and inline JSX):
//   e(window.ProGate, { fallback: e(SomeUpgradePanel) }, ...children)
//
// Or imperative:
//   const status = await window.MR.pro.getMyStatus();
//   if (status !== 'approved') showUpgrade();
//
// Renders children when the user is Pro (approved or admin); otherwise
// renders the appropriate upgrade panel:
//   • signed-out      → "Sign in to request Pro access"
//   • none            → "Request Pro access" button
//   • requested       → "Request pending — admin will review"
//   • denied          → "Access denied" + contact note
//   • table-missing   → admin-facing: "Run the SQL in data-pro.js to enable"
//   • unknown         → generic "Couldn't check your status" with retry
//
// The status is cached in localStorage so the gate doesn't flicker on
// every mount. Re-checked on focus and after a request.

(function () {
  const e = React.createElement;
  const { useState, useEffect, useCallback } = React;

  function useProStatus() {
    const [status, setStatus] = useState(() => {
      // Optimistic: trust the cached value on first paint.
      try { return localStorage.getItem('mr-pro-status') || 'unknown'; }
      catch { return 'unknown'; }
    });
    const [checking, setChecking] = useState(false);

    const refresh = useCallback(async () => {
      if (!window.MR || !window.MR.pro) return;
      setChecking(true);
      try {
        const s = await window.MR.pro.getMyStatus();
        setStatus(s);
      } finally {
        setChecking(false);
      }
    }, []);

    useEffect(() => {
      refresh();
      const onFocus = () => refresh();
      window.addEventListener('focus', onFocus);

      // Subscribe to Supabase auth state changes — covers the case where
      // the user signs in via the auth modal (no window focus event
      // fires, and we'd otherwise keep showing 'signed-out' until they
      // blurred + refocused the window).
      let unsubAuth = null;
      const setupAuthSub = async () => {
        if (window.MR && window.MR.readyPromise && !window.MR.ready) {
          try { await window.MR.readyPromise; } catch {}
        }
        const sb = window.MR && window.MR.supabase;
        if (sb && sb.auth && typeof sb.auth.onAuthStateChange === 'function') {
          const { data } = sb.auth.onAuthStateChange((_event, _session) => {
            refresh();
          });
          unsubAuth = () => {
            try { data && data.subscription && data.subscription.unsubscribe(); }
            catch {}
          };
        }
      };
      setupAuthSub();

      return () => {
        window.removeEventListener('focus', onFocus);
        if (unsubAuth) unsubAuth();
      };
    }, [refresh]);

    return { status, checking, refresh };
  }

  // The upgrade panel — shown when the user isn't Pro. `compact` makes
  // it smaller (for inline use inside the AI sidebar's empty body).
  function ProUpgradePanel({ status, onRefresh, compact }) {
    const [submitting, setSubmitting] = useState(false);
    const [note, setNote] = useState('');
    const [showNote, setShowNote] = useState(false);

    const submit = async () => {
      setSubmitting(true);
      const res = await window.MR.pro.requestAccess(note);
      setSubmitting(false);
      if (res.ok) {
        await onRefresh();
      } else if (res.reason === 'signed-out') {
        // Defer to the gated() flow elsewhere; just surface message
        alert('You need to sign in first to request Pro access.');
      } else if (res.reason === 'table-missing') {
        alert('Pro system not initialized yet. The admin needs to run the setup SQL — see data-pro.js for the script.');
      } else {
        alert('Could not submit request: ' + (res.reason || 'unknown error'));
      }
    };

    let body;
    if (status === 'signed-out') {
      // Two-step gate when signed out: sign in first, THEN request Pro.
      // The previous copy ("Sign in to use AI") was misleading because
      // signing in alone doesn't grant access — Pro approval is the
      // actual gate. Spell out both steps clearly.
      body = e('div', { className: 'pro-gate-body' },
        e('div', { className: 'pro-gate-icon' }, '✦'),
        e('h3', null, 'Request Pro access to use AI'),
        e('p', null, "AI features are reserved for Pro members. It's free during alpha — sign in first, then request access here in a tap or two."),
        e('button', {
          type: 'button',
          className: 'ai-btn ai-btn--primary pro-gate-cta',
          onClick: () => {
            if (typeof window.__mr_openAuth === 'function') window.__mr_openAuth();
            else alert('Use the avatar icon in the top-right to sign in.');
          },
        }, 'Sign in to continue →')
      );
    } else if (status === 'requested') {
      body = e('div', { className: 'pro-gate-body pro-gate-body--pending' },
        e('div', { className: 'pro-gate-icon' }, '◷'),
        e('h3', null, 'Request pending'),
        e('p', null, "We've passed your request to the team. You'll get access as soon as an admin approves it — usually within a day."),
        e('button', { type: 'button', className: 'ai-btn', onClick: onRefresh, disabled: submitting }, 'Check again')
      );
    } else if (status === 'denied') {
      body = e('div', { className: 'pro-gate-body pro-gate-body--denied' },
        e('div', { className: 'pro-gate-icon' }, '×'),
        e('h3', null, 'Access not granted'),
        e('p', null, "Your Pro request wasn't approved. Reach out to the team if you think this is a mistake.")
      );
    } else if (status === 'table-missing') {
      body = e('div', { className: 'pro-gate-body pro-gate-body--setup' },
        e('div', { className: 'pro-gate-icon' }, '⚙'),
        e('h3', null, 'Pro system not initialized'),
        e('p', null, 'The admin needs to run the setup SQL once in Supabase. The script is in the top comment of '),
        e('code', null, 'data-pro.js'), '. Reload after running it.'
      );
    } else if (status === 'unknown') {
      body = e('div', { className: 'pro-gate-body' },
        e('h3', null, "Couldn't check your access status"),
        e('p', null, 'Try again in a moment.'),
        e('button', { type: 'button', className: 'ai-btn', onClick: onRefresh, disabled: submitting }, 'Retry')
      );
    } else {
      // 'none' — never requested
      body = e('div', { className: 'pro-gate-body' },
        e('div', { className: 'pro-gate-icon' }, '✦'),
        e('h3', null, 'Pro feature'),
        e('p', null, "AI tools — the assistant, 'What's missing?', smart placeholder fills, list import — are powered by a paid model. To keep costs in check, we approve users one at a time."),
        e('p', { className: 'pro-gate-sub' }, "It's free during alpha — just tell us a bit about how you'd use it."),
        showNote
          ? e('div', { className: 'pro-gate-form' },
              e('textarea', {
                value: note,
                onChange: (ev) => setNote(ev.target.value),
                placeholder: 'Briefly: what would you use AI features for? (optional)',
                rows: 3,
              }),
              e('div', { className: 'pro-gate-actions' },
                e('button', { type: 'button', className: 'ai-btn ai-btn--primary', onClick: submit, disabled: submitting },
                  submitting ? 'Submitting…' : 'Send request'
                ),
                e('button', { type: 'button', className: 'ai-btn', onClick: () => setShowNote(false), disabled: submitting }, 'Cancel')
              )
            )
          : e('button', { type: 'button', className: 'ai-btn ai-btn--primary pro-gate-cta', onClick: () => setShowNote(true) },
              '✦ Request Pro access'
            )
      );
    }

    return e('div', { className: 'pro-gate' + (compact ? ' pro-gate--compact' : '') }, body);
  }

  function ProGate({ children, fallback, compact }) {
    const { status, refresh } = useProStatus();
    if (status === 'approved') return children;
    if (fallback) return fallback;
    return e(ProUpgradePanel, { status, onRefresh: refresh, compact });
  }

  // Hook export for callers that need to react to status without wrapping.
  ProGate.useStatus = useProStatus;
  ProGate.UpgradePanel = ProUpgradePanel;

  window.ProGate = ProGate;
})();
