// Spellstash login / signup page.
// Email + password via Supabase Auth. After auth, redirects to ?next= or
// /collection.html. Auto-switches to signup if URL has ?signup=1.

const { useState, useEffect } = React;

// Only allow same-origin relative redirects from ?next. Blocks open-redirect
// payloads like //evil.com, https://evil.com, and javascript: URLs. Must start
// with a single "/" and not "//" or "/\".
function safeNext(raw, fallback) {
  if (typeof raw !== "string" || raw.length === 0) return fallback;
  if (raw[0] !== "/" || raw[1] === "/" || raw[1] === "\\") return fallback;
  return raw;
}

function LoginPage() {
  const [mode, setMode] = useState("login");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState(null);
  const [info, setInfo] = useState(null);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    if (params.get("signup") === "1") setMode("signup");

    // Already logged in? Skip the form and go.
    window.ssAuth.client.auth.getSession().then(({ data }) => {
      if (data.session) {
        window.location.href = safeNext(params.get("next"), "/collection");
      }
    });
  }, []);

  const goNext = () => {
    const params = new URLSearchParams(window.location.search);
    window.location.href = safeNext(params.get("next"), "/collection");
  };

  const submit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError(null);
    setInfo(null);
    try {
      if (mode === "login") {
        const { error: err } = await window.ssAuth.client.auth.signInWithPassword({ email, password });
        if (err) throw err;
        goNext();
      } else {
        const { data, error: err } = await window.ssAuth.client.auth.signUp({ email, password });
        if (err) throw err;
        if (data.session) {
          // Email confirmation disabled in Supabase project, session is live.
          // Brand-new accounts with no explicit destination land on the
          // collection with ?welcome=1, which surfaces the founding-member
          // lifetime offer once. An explicit ?next (e.g. from a Pro CTA) wins.
          const params = new URLSearchParams(window.location.search);
          window.location.href = safeNext(params.get("next"), "/collection?welcome=1");
        } else {
          setInfo("Check your email for a confirmation link, then come back and sign in.");
          setSubmitting(false);
        }
      }
    } catch (err) {
      setError(err.message || "Something went wrong. Try again.");
      setSubmitting(false);
    }
  };

  const signInWithGoogle = async () => {
    setSubmitting(true);
    setError(null);
    try {
      const params = new URLSearchParams(window.location.search);
      const next = safeNext(params.get("next"), "/collection");
      const { error: err } = await window.ssAuth.client.auth.signInWithOAuth({
        provider: "google",
        options: {
          redirectTo: window.location.origin + next,
        },
      });
      if (err) throw err;
      // signInWithOAuth navigates the page; nothing to do post-call.
    } catch (err) {
      setError(err.message || "Could not start Google sign-in.");
      setSubmitting(false);
    }
  };

  return (
    <div className="cm-root">
      <main className="ss-login-main">
        <div className="ss-login-card">
          <div className="ss-login-logo">
            <a href="/" style={{ textDecoration: "none", color: "inherit" }}>
              <span style={{ fontFamily: "var(--cm-serif)", fontSize: 28, letterSpacing: "0.005em" }}>Spellstash</span>
            </a>
          </div>
          <h1 className="ss-login-title">
            {mode === "login" ? "Sign in" : "Create your stash"}
          </h1>
          <p className="ss-login-sub">
            {mode === "login"
              ? "Welcome back. Email and password to continue."
              : "Free to start. 3 containers and 300 cards. No credit card."}
          </p>
          <button
            type="button"
            className="ss-oauth-btn ss-oauth-btn--google"
            onClick={signInWithGoogle}
            disabled={submitting}
          >
            <svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true">
              <path fill="#4285F4" d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844a4.14 4.14 0 0 1-1.796 2.716v2.255h2.908c1.702-1.567 2.684-3.875 2.684-6.612z" />
              <path fill="#34A853" d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z" />
              <path fill="#FBBC05" d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332z" />
              <path fill="#EA4335" d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z" />
            </svg>
            <span>Continue with Google</span>
          </button>

          <div className="ss-login-divider">
            <span>or</span>
          </div>

          <form className="ss-login-form" onSubmit={submit}>
            <label>
              <span className="cm-label">Email</span>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                autoFocus
                autoComplete="email"
                placeholder="you@example.com"
              />
            </label>
            <label>
              <span className="cm-label">Password</span>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                minLength={8}
                autoComplete={mode === "login" ? "current-password" : "new-password"}
                placeholder={mode === "signup" ? "at least 8 characters" : ""}
              />
            </label>
            {error && <div className="cm-form-error">{error}</div>}
            {info && <div className="ss-login-info">{info}</div>}
            <button type="submit" className="cm-btn cm-btn--primary cm-btn--block" disabled={submitting}>
              {submitting ? "Working…" : (mode === "login" ? "Sign in" : "Create account")}
            </button>
          </form>
          <div className="ss-login-toggle">
            {mode === "login" ? (
              <>New here? <a href="#" onClick={(e) => { e.preventDefault(); setMode("signup"); setError(null); setInfo(null); }}>Create an account</a></>
            ) : (
              <>Already have an account? <a href="#" onClick={(e) => { e.preventDefault(); setMode("login"); setError(null); setInfo(null); }}>Sign in</a></>
            )}
          </div>
          <div className="ss-login-fine">
            <span className="cm-mono cm-dim">$4.99/month when you upgrade. Less than a booster pack.</span>
          </div>
        </div>
      </main>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<LoginPage />);
