const AUTH_PROVIDERS = (window.FPH_AUTH_CONFIG?.providers || []).filter(Boolean);

const getSupabaseClient = () => {
  const cfg = window.FPH_AUTH_CONFIG || {};
  if (!window.supabase?.createClient || !cfg.supabaseUrl || !cfg.supabaseKey) return null;
  if (!window.__FPH_SUPABASE__) {
    window.__FPH_SUPABASE__ = window.supabase.createClient(cfg.supabaseUrl, cfg.supabaseKey, {
      auth: {
        persistSession: true,
        autoRefreshToken: true,
        detectSessionInUrl: true,
      },
    });
  }
  return window.__FPH_SUPABASE__;
};

const useAuthSession = () => {
  const client = React.useMemo(() => getSupabaseClient(), []);
  const [session, setSession] = React.useState(null);
  const [user, setUser] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState("");

  React.useEffect(() => {
    let mounted = true;
    if (!client) {
      setError("Authentication is not configured.");
      setLoading(false);
      return undefined;
    }

    client.auth.getSession().then(({ data, error }) => {
      if (!mounted) return;
      if (error) setError(error.message);
      setSession(data?.session || null);
      setUser(data?.session?.user || null);
      setLoading(false);
    });

    const { data: listener } = client.auth.onAuthStateChange((_event, nextSession) => {
      if (!mounted) return;
      setSession(nextSession || null);
      setUser(nextSession?.user || null);
      setError("");
      setLoading(false);
    });

    return () => {
      mounted = false;
      listener?.subscription?.unsubscribe?.();
    };
  }, [client]);

  const signIn = React.useCallback(async ({ email, password }) => {
    if (!client) throw new Error("Authentication is not configured.");
    setError("");
    const { error } = await client.auth.signInWithPassword({ email, password });
    if (error) {
      setError(error.message);
      throw error;
    }
  }, [client]);

  const signInWithProvider = React.useCallback(async (providerId) => {
    if (!client) throw new Error("Authentication is not configured.");
    setError("");
    const options = {
      redirectTo: `${window.location.origin}/auth/callback`,
    };
    if (providerId === "azure") options.scopes = "email profile User.Read";
    const { error } = await client.auth.signInWithOAuth({ provider: providerId, options });
    if (error) {
      setError(error.message);
      throw error;
    }
  }, [client]);

  const signOut = React.useCallback(async () => {
    if (!client) return;
    await client.auth.signOut();
  }, [client]);

  return { client, session, user, loading, error, signIn, signInWithProvider, signOut };
};

const AuthScreen = ({ status = "ready", onSignIn, onProviderSignIn, authError }) => {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [localError, setLocalError] = React.useState("");
  const enabledProviders = AUTH_PROVIDERS.filter(p => p.enabled);

  const submit = async (event) => {
    event.preventDefault();
    if (!onSignIn || busy) return;
    setBusy(true);
    setLocalError("");
    try {
      await onSignIn({ email: email.trim(), password });
    } catch (err) {
      setLocalError(err.message || "Unable to sign in.");
    } finally {
      setBusy(false);
    }
  };

  const submitProvider = async (providerId) => {
    if (!onProviderSignIn || busy) return;
    setBusy(true);
    setLocalError("");
    try {
      await onProviderSignIn(providerId);
    } catch (err) {
      setLocalError(err.message || "Unable to start provider sign-in.");
      setBusy(false);
    }
  };

  return (
    <React.Fragment>
      <div className="auth-shell">
        <div className="auth-card card">
          <div className="brand auth-brand">
            <div className="brand-mark"><Icon name="ghost" size={18}/></div>
            <div>
              <div className="brand-name">wiki.ctab.tech</div>
              <div className="brand-sub mono">Multi-project private workspace</div>
            </div>
          </div>

          <div className="auth-copy">
            <div className="auth-kicker mono">Access required</div>
            <h1>Sign in to open wiki.ctab.tech.</h1>
            <p>Use your Supabase email/password account, or continue with Microsoft when your workspace uses Azure sign-in.</p>
          </div>

          {status === "loading" ? (
            <div className="auth-loading">Checking session…</div>
          ) : (
            <form className="auth-form" onSubmit={submit}>
              <label>
                <span>Email</span>
                <input type="email" autoComplete="email" value={email} onChange={e => setEmail(e.target.value)} required />
              </label>
              <label>
                <span>Password</span>
                <input type="password" autoComplete="current-password" value={password} onChange={e => setPassword(e.target.value)} required />
              </label>
              {(localError || authError) && <div className="auth-error">{localError || authError}</div>}
              <button className="btn primary auth-submit" type="submit" disabled={busy}>{busy ? "Signing in…" : "Sign in"}</button>
            </form>
          )}

          {!!enabledProviders.length && (
            <div className="auth-providers">
              <div className="auth-divider"><span>or</span></div>
              {enabledProviders.map(provider => (
                <button
                  key={provider.id}
                  className={`btn auth-provider ${provider.id === "azure" ? "microsoft" : ""}`.trim()}
                  type="button"
                  onClick={() => submitProvider(provider.id)}
                  disabled={busy}
                >
                  {provider.id === "azure" ? (
                    <span className="microsoft-mark" aria-hidden="true"><span></span><span></span><span></span><span></span></span>
                  ) : null}
                  {provider.label}
                </button>
              ))}
            </div>
          )}
        </div>
      </div>
      <div className="grain"/>
      <div className="vignette"/>
    </React.Fragment>
  );
};

window.useAuthSession = useAuthSession;
window.AuthScreen = AuthScreen;
