// 100dayslearning — sign in / create account

const { useState, useEffect } = React;

// ── Supabase ── replace these with your project values from supabase.com/dashboard → Settings → API
const SUPABASE_URL      = 'https://xrqtxadptqyfnhmslhhe.supabase.co';
const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhycXR4YWRwdHF5Zm5obXNsaGhlIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzkyODkyOTAsImV4cCI6MjA5NDg2NTI5MH0.-FQSgWWrFgx38FxlQlsZ25fp180OkPr_IoI1cvFN9Q0';
const supabase = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "editorial",
  "mode": "signin"
}/*EDITMODE-END*/;

const THEMES = [
  { value: "editorial", label: "Editorial" },
  { value: "terminal",  label: "Terminal"  },
  { value: "sketch",    label: "Sketch"    },
];

function GoogleLogo() {
  return (
    <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-.98.66-2.23 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>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError]     = useState(null);

  useEffect(() => { document.body.dataset.theme = t.theme; }, [t.theme]);

  // Redirect if already signed in
  useEffect(() => {
    supabase.auth.getSession().then(({ data: { session } }) => {
      if (session) window.location.href = "Python.html";
    });
  }, []);

  const isSignup = t.mode === "signup";

  const submit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const { error: err } = isSignup
        ? await supabase.auth.signUp({ email, password })
        : await supabase.auth.signInWithPassword({ email, password });
      if (err) throw err;
      window.location.href = "Python.html";
    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  };

  const signInWithGoogle = async () => {
    setError(null);
    const { error: err } = await supabase.auth.signInWithOAuth({
      provider: 'google',
      options: { redirectTo: window.location.origin + '/Python.html' },
    });
    if (err) setError(err.message);
  };

  return (
    <div className="auth-page" data-screen-label="Sign in">
      <a href="index.html" className="auth-home" aria-label="100dayslearning home">
        100dayslearning
      </a>

      <main className="auth-shell">
        <div className="auth-card">
          <div className="auth-mode">
            <button
              type="button"
              className={`mode-tab ${!isSignup ? "on" : ""}`}
              onClick={() => setTweak('mode', 'signin')}
            >Sign in</button>
            <button
              type="button"
              className={`mode-tab ${isSignup ? "on" : ""}`}
              onClick={() => setTweak('mode', 'signup')}
            >Create account</button>
          </div>

          <h1 className="auth-title">
            {isSignup ? "Start your 100 days." : "Welcome back."}
          </h1>
          <p className="auth-sub">
            {isSignup
              ? "First 10 days are free. No card, no trial timer."
              : "Sign in to keep your streak going."}
          </p>

          <div className="auth-oauth">
            <button type="button" className="oauth-btn" onClick={signInWithGoogle}>
              <GoogleLogo /> Continue with Google
            </button>
          </div>

          <div className="auth-divider">
            <span>or with email</span>
          </div>

          <form className="auth-form" onSubmit={submit}>
            {isSignup && (
              <label className="auth-field">
                <span>Your name</span>
                <input
                  type="text"
                  required
                  autoComplete="name"
                  placeholder="what should we call you?"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                />
              </label>
            )}

            <label className="auth-field">
              <span>Email</span>
              <input
                type="email"
                required
                autoComplete="email"
                placeholder="you@somewhere.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
            </label>

            <label className="auth-field">
              <span>
                Password
                {!isSignup && <a href="/forgot" className="field-link">Forgot?</a>}
              </span>
              <input
                type="password"
                required
                minLength={isSignup ? 8 : undefined}
                autoComplete={isSignup ? "new-password" : "current-password"}
                placeholder={isSignup ? "at least 8 characters" : "••••••••"}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
            </label>

            {error && (
              <p style={{margin: '0', fontSize: 13, color: '#c14a4a', fontFamily: 'var(--font-ui)'}}>{error}</p>
            )}

            <button type="submit" className="auth-submit" disabled={loading}>
              {loading ? "One sec…" : (isSignup ? "Create account" : "Sign in")}
              <svg className="arrow" width="14" height="14" viewBox="0 0 16 16" fill="none">
                <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </button>

            {isSignup && (
              <p className="auth-hint">
                By creating an account you agree to our <a href="/terms">terms</a> and <a href="/privacy">privacy policy</a>.
              </p>
            )}
          </form>
        </div>

        <p className="auth-foot">
          {isSignup ? (
            <>
              Already have an account?{" "}
              <a href="#" onClick={(e) => { e.preventDefault(); setTweak('mode', 'signin'); }}>Sign in</a>
            </>
          ) : (
            <>
              New here?{" "}
              <a href="#" onClick={(e) => { e.preventDefault(); setTweak('mode', 'signup'); }}>Create an account</a>
              {" "}— first 10 days free.
            </>
          )}
        </p>
      </main>

      <TweaksPanel>
        <TweakSection label="Aesthetic" />
        <TweakRadio
          label="Direction"
          value={t.theme}
          options={THEMES.map(x => x.value)}
          onChange={(v) => setTweak('theme', v)}
        />
        <TweakSection label="Default view" />
        <TweakRadio
          label="Open as"
          value={t.mode}
          options={["signin", "signup"]}
          onChange={(v) => setTweak('mode', v)}
        />
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
