/* Supabase Auth gate restricted to @megaeth.com.

   How it works:
     1. User clicks "Sign in with Google" → supabase.auth.signInWithOAuth
        redirects to Google with hd=megaeth.com hint.
     2. Google → Supabase callback URL → Supabase verifies and redirects
        back to our app with the session in the URL fragment.
     3. Supabase client picks up the session via detectSessionInUrl, strips
        the fragment, and persists the JWT in localStorage.
     4. We check the verified email ends with @megaeth.com (belt-and-suspenders
        on top of the Postgres RLS policies, which are the real gate).

   If Supabase isn't configured yet, we show a setup-required screen with
   exact instructions instead of failing silently.
*/

const { useState: useStateAuth, useEffect: useEffectAuth, useCallback: useCallbackAuth } = React;

const ALLOWED_DOMAIN = 'megaeth.com';

function isAllowedEmail(email) {
  return !!email && email.toLowerCase().endsWith('@' + ALLOWED_DOMAIN);
}

/* Add the signed-in user to the shared owner roster (kv key
   `signed_in_users`). Deduped by email; updates lastSeenAt on every
   sign-in so the Owners list stays sorted by recency.  */
async function registerOwnerFromSignIn(email, picture) {
  if (!email || !window.mcalStore) return;
  const owner = window.mcalUtils.ownerFromEmail(email);
  if (!owner) return;
  const existing = (await window.mcalStore.get('signed_in_users')) || [];
  const idx = existing.findIndex(u => u.email === owner.email);
  const next = existing.slice();
  const record = {
    id: owner.id,
    email: owner.email,
    name: owner.name,
    color: idx >= 0 ? (existing[idx].color || owner.color) : owner.color,
    picture: picture || (idx >= 0 ? existing[idx].picture : ''),
    lastSeenAt: Date.now(),
  };
  if (idx >= 0) next[idx] = { ...existing[idx], ...record };
  else next.push(record);
  await window.mcalStore.set('signed_in_users', next);
}

function useAuth() {
  const sb = window.mcalSb;
  const [user, setUser] = useStateAuth(null);
  const [error, setError] = useStateAuth(null);
  const [ready, setReady] = useStateAuth(false);

  useEffectAuth(() => {
    if (!sb) { setReady(true); return; }
    let cancelled = false;

    // Initial session
    (async () => {
      const { data } = await sb.auth.getSession();
      if (cancelled) return;
      applySession(data.session);
      setReady(true);
    })();

    // React to login / logout / refresh
    const { data: { subscription } } = sb.auth.onAuthStateChange((_event, session) => {
      applySession(session);
    });

    function applySession(session) {
      const u = session && session.user;
      if (!u) { setUser(null); return; }
      const meta = u.user_metadata || {};
      const email = (u.email || '').toLowerCase();
      if (!isAllowedEmail(email)) {
        setError(`Access is restricted to @${ALLOWED_DOMAIN} accounts. You signed in as ${email || 'an unknown email'}.`);
        sb.auth.signOut(); // immediately revoke so the gate stays closed
        setUser(null);
        return;
      }
      setError(null);
      setUser({
        email,
        name: meta.full_name || meta.name || email,
        picture: meta.avatar_url || meta.picture || '',
        sub: u.id,
      });
      // Persist this sign-in to the shared roster so every collaborator
      // sees them in the Owner picker without anybody managing it manually.
      registerOwnerFromSignIn(email, meta.avatar_url || meta.picture || '');
    }

    return () => { cancelled = true; subscription && subscription.unsubscribe(); };
  }, [sb]);

  const signIn = useCallbackAuth(async () => {
    if (!sb) return;
    setError(null);
    const { error: e } = await sb.auth.signInWithOAuth({
      provider: 'google',
      options: {
        redirectTo: window.location.origin + window.location.pathname,
        queryParams: { hd: ALLOWED_DOMAIN, prompt: 'select_account' },
      },
    });
    if (e) setError(e.message || 'Sign-in failed.');
  }, [sb]);

  const signOut = useCallbackAuth(async () => {
    if (!sb) return;
    await sb.auth.signOut();
    setUser(null);
  }, [sb]);

  return { user, error, ready, signIn, signOut };
}

function LoginScreen({ onSignIn, error }) {
  const status = window.mcalSbStatus;
  const configured = status === 'ready';

  return (
    <div className="auth-screen">
      <div className="auth-card">
        <img src="assets/logo.svg" className="auth-logo" alt="MegaETH" />
        <h1 className="auth-title">Marketing Calendar</h1>
        <p className="auth-sub">
          Sign in with your <code>@{ALLOWED_DOMAIN}</code> account to continue.
        </p>

        {!configured ? (
          <div className="auth-setup">
            <div className="auth-setup-title">Setup required</div>
            <p>Set your Supabase project URL and anon key in <code>index.html</code>:</p>
            <pre>{`<script>
  window.MCAL_SUPABASE_URL =
    'https://YOUR-PROJECT.supabase.co';
  window.MCAL_SUPABASE_ANON_KEY =
    'eyJhbGciOi...';   // public anon key from API settings
</script>`}</pre>
            <p className="auth-setup-hint">
              Create a free Supabase project at <a href="https://supabase.com/dashboard" target="_blank" rel="noopener noreferrer">supabase.com/dashboard</a>.
              Run the SQL schema (in <code>SETUP.md</code>) and configure the
              Google provider in <em>Authentication → Providers</em>.
            </p>
          </div>
        ) : (
          <button className="auth-google-btn" onClick={onSignIn}>
            <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
              <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
              <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.99.66-2.25 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
              <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
              <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
            </svg>
            Sign in with Google
          </button>
        )}

        {error && <div className="auth-error">{error}</div>}

        <div className="auth-foot">Internal · MegaETH Marketing</div>
      </div>
    </div>
  );
}

window.mcalAuth = { useAuth, LoginScreen, ALLOWED_DOMAIN };
