/* global React, Star, Icon */
const { useState: useStateAuth, useEffect: useEffectAuth } = React;

// ── Config ────────────────────────────────────────────────────────────────────
const GOOGLE_CLIENT_ID = "552583746074-udqkotu82jncstvh4usforu985sgipbp.apps.googleusercontent.com";
const MAGIC_LINK_WORKER = "https://ftw-magic-link.brigham-freeth.workers.dev";

// ── Main login gate ────────────────────────────────────────────────────────────
function LoginGate({ onLogin, navigate }) {
  const [step, setStep] = useStateAuth("choose"); // choose | email | sent | error
  const [email, setEmail] = useStateAuth("");
  const [googleLoading, setGoogleLoading] = useStateAuth(false);
  const [errorMsg, setErrorMsg] = useStateAuth("");

  // Load Google Identity Services script once
  useEffectAuth(() => {
    if (document.getElementById("gsi-script")) return;
    const s = document.createElement("script");
    s.id = "gsi-script";
    s.src = "https://accounts.google.com/gsi/client";
    s.async = true;
    s.defer = true;
    // Initialize Google after script loads
    s.onload = () => {
      window.google.accounts.id.initialize({
        client_id: GOOGLE_CLIENT_ID,
        callback: (res) => handleGoogleCredential(res.credential),
        auto_select: false,
      });
      window.google.accounts.id.renderButton(
        document.getElementById("google-signin-btn"),
        { theme: "outline", size: "large", width: 320, text: "signin_with" }
      );
    };
    document.head.appendChild(s);
  }, []);

  // Re-render Google button when step changes back to choose
  useEffectAuth(() => {
    if (step === "choose" && window.google) {
      setTimeout(() => {
        const el = document.getElementById("google-signin-btn");
        if (el && !el.querySelector("iframe")) {
          window.google.accounts.id.renderButton(el,
            { theme: "outline", size: "large", width: 320, text: "signin_with" }
          );
        }
      }, 50);
    }
  }, [step]);

  // ── Google SSO handler ─────────────────────────────────────────────────────
  async function handleGoogleCredential(credential) {
    setGoogleLoading(true);
    setErrorMsg("");
    try {
      const res = await fetch(`${MAGIC_LINK_WORKER}/google-auth`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ credential }),
      });
      const data = await res.json();
      if (data.ok) {
        onLogin(data);
      } else {
        setErrorMsg(data.error || "Your Google account email isn't in our system yet. Contact us at hello@foothilltheatreworkshop.com.");
        setStep("error");
      }
    } catch {
      setErrorMsg("Connection error — please try again.");
      setStep("error");
    } finally {
      setGoogleLoading(false);
    }
  }

  // ── Magic link email handler ───────────────────────────────────────────────
  async function handleSendMagicLink(e) {
    e.preventDefault();
    if (!email.trim()) return;
    try {
      await fetch(`${MAGIC_LINK_WORKER}/send?email=${encodeURIComponent(email.trim())}`);
      setStep("sent");
    } catch {
      setErrorMsg("Couldn't send email — please try again.");
      setStep("error");
    }
  }

  return (
    <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center",
      background: "var(--paper)", padding: "24px 16px" }}>
      <div style={{ width: "100%", maxWidth: 400, background: "var(--white)",
        border: "var(--bd-ink)", borderRadius: "var(--r-card)", padding: "36px 32px",
        boxShadow: "4px 4px 0 var(--ink)" }}>

        {/* Logo */}
        <div style={{ textAlign: "center", marginBottom: 28 }}>
          <img src="assets/logo.png" alt="Foothill Theatre Workshop" style={{ height: 32 }} />
          <div style={{ marginTop: 12, fontSize: 13, color: "var(--ink-muted)", fontWeight: 600,
            letterSpacing: "0.06em", textTransform: "uppercase" }}>Family Hub</div>
        </div>

        {/* ── CHOOSE ── */}
        {step === "choose" && (
          <>
            <h2 style={{ fontSize: 20, textAlign: "center", marginBottom: 6 }}>Welcome back</h2>
            <p style={{ fontSize: 14, color: "var(--ink-muted)", textAlign: "center", marginBottom: 24, lineHeight: 1.5 }}>
              Sign in to see your schedule, call times, and tuition balance.
            </p>

            {/* Google button */}
            <div id="google-signin-btn"
              style={{ minHeight: 44, display: "flex", alignItems: "center",
                justifyContent: "center", marginBottom: 20 }}>
              {googleLoading && (
                <span style={{ fontSize: 14, color: "var(--ink-muted)" }}>Signing in…</span>
              )}
            </div>

            {/* Divider */}
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 20 }}>
              <div style={{ flex: 1, height: 1, background: "var(--ink)", opacity: 0.15 }} />
              <span style={{ fontSize: 12, color: "var(--ink-muted)", fontWeight: 600 }}>OR</span>
              <div style={{ flex: 1, height: 1, background: "var(--ink)", opacity: 0.15 }} />
            </div>

            {/* Email magic link */}
            <button onClick={() => setStep("email")}
              style={{ width: "100%", background: "var(--paper)", border: "2px solid var(--ink)",
                borderRadius: "var(--r-pill)", padding: "11px 16px", fontSize: 15,
                fontFamily: "var(--sans)", cursor: "pointer", fontWeight: 500 }}>
              ✉️ Email me a magic link
            </button>

            <p style={{ fontSize: 12, color: "var(--ink-muted)", textAlign: "center", marginTop: 20, lineHeight: 1.6 }}>
              Your Google account email must match your FTW registration email.<br />
              Questions? <a href="mailto:hello@foothilltheatreworkshop.com"
                style={{ color: "var(--teal)" }}>hello@foothilltheatreworkshop.com</a>
            </p>
          </>
        )}

        {/* ── EMAIL ── */}
        {step === "email" && (
          <>
            <button onClick={() => setStep("choose")}
              style={{ background: "none", border: "none", cursor: "pointer", fontSize: 13,
                color: "var(--ink-muted)", marginBottom: 16, padding: 0 }}>← Back</button>
            <h2 style={{ fontSize: 20, marginBottom: 8 }}>Email me a link</h2>
            <p style={{ fontSize: 14, color: "var(--ink-muted)", marginBottom: 20, lineHeight: 1.5 }}>
              Enter the email on your FTW account. We'll send a one-click login link — no password needed.
            </p>
            <form onSubmit={handleSendMagicLink}>
              <input type="email" required placeholder="your@email.com" value={email}
                onChange={e => setEmail(e.target.value)}
                style={{ width: "100%", boxSizing: "border-box", padding: "11px 14px",
                  border: "2px solid var(--ink)", borderRadius: "var(--r-md)", fontSize: 15,
                  fontFamily: "var(--sans)", marginBottom: 12, outline: "none" }} />
              <button type="submit"
                style={{ width: "100%", background: "var(--gold)", border: "2px solid var(--ink)",
                  borderRadius: "var(--r-pill)", padding: "12px", fontSize: 15,
                  fontFamily: "var(--display)", fontWeight: 600, cursor: "pointer" }}>
                Send magic link →
              </button>
            </form>
          </>
        )}

        {/* ── SENT ── */}
        {step === "sent" && (
          <div style={{ textAlign: "center" }}>
            <div style={{ fontSize: 48, marginBottom: 16 }}>📬</div>
            <h2 style={{ fontSize: 20, marginBottom: 8 }}>Check your inbox</h2>
            <p style={{ fontSize: 14, color: "var(--ink-muted)", lineHeight: 1.6 }}>
              We sent a login link to <strong>{email}</strong>.<br />
              Click it to open your Family Hub — no password needed.
            </p>
            <p style={{ fontSize: 12, color: "var(--ink-muted)", marginTop: 16 }}>
              Didn't get it? Check spam, or{" "}
              <button onClick={() => setStep("email")}
                style={{ background: "none", border: "none", cursor: "pointer",
                  color: "var(--teal)", fontSize: 12, padding: 0, textDecoration: "underline" }}>
                try again
              </button>.
            </p>
          </div>
        )}

        {/* ── ERROR ── */}
        {step === "error" && (
          <div style={{ textAlign: "center" }}>
            <div style={{ fontSize: 48, marginBottom: 16 }}>🤔</div>
            <h2 style={{ fontSize: 20, marginBottom: 8 }}>Email not found</h2>
            <p style={{ fontSize: 14, color: "var(--ink-muted)", lineHeight: 1.6, marginBottom: 20 }}>
              {errorMsg}
            </p>
            <button onClick={() => { setStep("choose"); setErrorMsg(""); }}
              style={{ background: "var(--gold)", border: "2px solid var(--ink)",
                borderRadius: "var(--r-pill)", padding: "10px 24px",
                fontFamily: "var(--display)", fontWeight: 600, fontSize: 15, cursor: "pointer" }}>
              Try again
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
