// Auth gate. Wraps the portal app and requires a Google sign-in whose email
// is in the server-side `admins` table (RLS only returns a row for the
// caller's own email). Failure to find that row → "not authorized" screen.

const AuthGate = ({ children }) => {
  // session: undefined = loading auth, null = signed out, object = signed in
  // adminOk: undefined = haven't checked yet, true/false = result
  const [session, setSession] = useState(undefined);
  const [adminOk, setAdminOk] = useState(undefined);

  useEffect(() => {
    if (!window.supa) { setSession(null); return; }
    let cancelled = false;
    window.supa.auth.getSession().then(({ data }) => {
      if (!cancelled) setSession(data.session || null);
    });
    const { data: sub } = window.supa.auth.onAuthStateChange((_event, sess) => {
      if (!cancelled) {
        setSession(sess || null);
        setAdminOk(undefined); // re-check on auth change
      }
    });
    return () => { cancelled = true; sub?.subscription?.unsubscribe(); };
  }, []);

  useEffect(() => {
    if (!session) { setAdminOk(undefined); return; }
    if (!window.supa) { setAdminOk(false); return; }
    let cancelled = false;
    const email = (session.user?.email || '').toLowerCase();
    window.supa
      .from('admins')
      .select('email,role')
      .eq('email', email)
      .maybeSingle()
      .then(({ data, error }) => {
        if (cancelled) return;
        setAdminOk(!error && !!data);
      });
    return () => { cancelled = true; };
  }, [session]);

  if (session === undefined) {
    return <AuthFrame><div style={{ color: 'var(--fg-3)', fontSize: 13 }}>Loading…</div></AuthFrame>;
  }
  if (!session) return <SignInScreen />;
  if (adminOk === undefined) {
    return <AuthFrame><div style={{ color: 'var(--fg-3)', fontSize: 13 }}>Checking access…</div></AuthFrame>;
  }
  if (!adminOk) {
    return <UnauthorizedScreen email={(session.user?.email || '').toLowerCase()} />;
  }
  return children;
};

const AuthFrame = ({ children }) => (
  <div style={{
    minHeight: '100vh',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    background: 'var(--bg-page)',
    fontFamily: 'var(--font-ui)',
    padding: 20,
  }}>{children}</div>
);

const SignInScreen = () => {
  const [error, setError] = useState('');
  const signIn = async () => {
    if (!window.supa) return;
    const { error } = await window.supa.auth.signInWithOAuth({
      provider: 'google',
      options: { redirectTo: window.location.origin + window.location.pathname },
    });
    if (error) setError(error.message);
  };
  return (
    <AuthFrame>
      <div style={{
        background: 'var(--bg-surface)',
        padding: '48px 48px 40px',
        borderRadius: 18,
        border: '1px solid var(--border-1)',
        boxShadow: 'var(--shadow-2)',
        maxWidth: 420, width: '100%',
        textAlign: 'center',
      }}>
        <div style={{
          fontSize: 11, fontWeight: 600, letterSpacing: '0.16em',
          textTransform: 'uppercase', color: 'var(--fg-3)', marginBottom: 18,
        }}>Snap Operation</div>
        <div style={{ fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em', marginBottom: 10 }}>
          Owner portal
        </div>
        <div style={{ fontSize: 13.5, color: 'var(--fg-2)', lineHeight: 1.55, marginBottom: 32 }}>
          Sign in to manage prep templates, broadcasts, devices, and staff.
        </div>
        <button onClick={signIn} style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          width: '100%', height: 44,
          background: 'var(--fg-1)', color: '#FFFFFF',
          border: 0, borderRadius: 10,
          fontSize: 14, fontWeight: 600, cursor: 'pointer',
        }}>
          <svg width="16" height="16" viewBox="0 0 48 48" aria-hidden="true">
            <path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3c-1.7 4.7-6.2 8-11.3 8-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34 6.1 29.3 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.4-.4-3.5z"/>
            <path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 16 19 13 24 13c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34 6.1 29.3 4 24 4 16.3 4 9.7 8.3 6.3 14.7z"/>
            <path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.4-5.2l-6.2-5.1c-2 1.4-4.5 2.3-7.2 2.3-5.1 0-9.5-3.3-11.2-8l-6.5 5C9.6 39.6 16.2 44 24 44z"/>
            <path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.3-2.4 4.3-4.4 5.7l6.2 5.1C42.6 35.8 44 30.3 44 24c0-1.3-.1-2.4-.4-3.5z"/>
          </svg>
          Sign in with Google
        </button>
        {error && (
          <div style={{ marginTop: 16, fontSize: 12.5, color: 'var(--danger)' }}>{error}</div>
        )}
      </div>
    </AuthFrame>
  );
};

const UnauthorizedScreen = ({ email }) => {
  const signOut = async () => { await window.supa?.auth.signOut(); };
  return (
    <AuthFrame>
      <div style={{
        background: 'var(--bg-surface)',
        padding: 48,
        borderRadius: 18,
        border: '1px solid var(--border-1)',
        boxShadow: 'var(--shadow-2)',
        maxWidth: 420, width: '100%',
        textAlign: 'center',
      }}>
        <div style={{ fontSize: 22, fontWeight: 600, marginBottom: 12 }}>Not authorized</div>
        <div style={{ fontSize: 13.5, color: 'var(--fg-2)', lineHeight: 1.55, marginBottom: 24 }}>
          <strong>{email}</strong> isn't on the allowlist for this portal. Sign in with a different account or ask the owner to add you.
        </div>
        <button onClick={signOut} style={{
          height: 38, padding: '0 18px',
          background: 'var(--bg-sunken)', color: 'var(--fg-1)',
          border: '1px solid var(--border-1)', borderRadius: 9,
          fontSize: 13, fontWeight: 600, cursor: 'pointer',
        }}>Sign out</button>
      </div>
    </AuthFrame>
  );
};

// Expose signOut so the Shell header can render a sign-out button.
window.portalSignOut = async () => { await window.supa?.auth.signOut(); };
