/* screens-auth.jsx — Landing + SignUp Wizard + SignIn + ForgotPassword */
const { useState: useStateAuth, useEffect: useAuthFX } = React;

/* ─────────────────────────────────────────────────────────────
   LANDING
───────────────────────────────────────────────────────────── */
function Landing({ nav, lang, setLang }) {
  const headParts = t("landing.headline").split(",");
  const catalog = window.CATALOG ? window.CATALOG.GAMES : [];
  const [carouselIdx, setCarouselIdx] = useStateAuth(0);
  const [isMobile, setIsMobile] = useStateAuth(window.matchMedia("(max-width: 640px)").matches);
  useAuthFX(() => {
    const mq = window.matchMedia("(max-width: 640px)");
    const fn = (e) => setIsMobile(e.matches);
    mq.addEventListener("change", fn);
    return () => mq.removeEventListener("change", fn);
  }, []);
  const VISIBLE = isMobile ? 2 : 4;
  const maxIdx = Math.max(0, catalog.length - VISIBLE);
  const clampedIdx = Math.min(carouselIdx, maxIdx);
  function prev() { setCarouselIdx(i => Math.max(0, i - 1)); }
  function next() { setCarouselIdx(i => Math.min(maxIdx, i + 1)); }

  return (
    <div className="app" style={{ background: "var(--bg)" }}>
      <header className="topbar">
        <div className="wrap topbar-inner">
          <div className="brand"><Logo /> Scoby</div>
          <span className="spacer"></span>
          <LangToggle lang={lang} onChange={setLang} />
          <button className="btn ghost hide-mobile" onClick={() => nav("#/signin")}>{t("nav.signin")}</button>
          <button className="btn primary" onClick={() => nav("#/signup")}>{t("nav.getstarted")}</button>
        </div>
      </header>

      <section className="lp-hero">
        <div className="lp-orb"></div>
        <span className="lp-eyebrow"><Icon name="dice" size={14} />{t("landing.eyebrow")}</span>
        <h1 className="lp-h1">
          {headParts[0]},<br /><em>{headParts[1] ? headParts[1].trim() : ""}</em>
        </h1>
        <p className="lp-sub">{t("landing.sub")}</p>
        <div className="lp-ctas">
          <button className="btn primary lg" onClick={() => nav("#/signup")}>{t("landing.cta1")}<Icon name="arrow" /></button>
          <button className="btn lg" onClick={() => nav("#/signin")}>{t("nav.signin")}</button>
        </div>
      </section>

      {/* Carousel */}
      <section className="lp-games">
        <h2 style={{ textAlign: "center", marginBottom: 18, fontSize: 20 }}>{t("landing.games")}</h2>
        <div style={{ position: "relative", maxWidth: "var(--maxw)", margin: "0 auto", padding: isMobile ? "0 40px" : "0 56px" }}>
          <button className="iconbtn carousel-btn" onClick={prev} disabled={clampedIdx === 0}
            style={{ position: "absolute", left: 8, top: "50%", transform: "translateY(-50%)", zIndex: 2 }}>
            <Icon name="back" size={18} />
          </button>
          <div style={{ overflow: "hidden" }}>
            <div style={{ display: "flex", gap: 14, transition: "transform .35s cubic-bezier(.4,0,.2,1)",
              transform: `translateX(calc(-${clampedIdx} * (100% / ${VISIBLE} + 14px / ${VISIBLE})))` }}>
              {catalog.map((g) => {
                const ready = g.status === "ready";
                return (
                  <div key={g.id} style={{ flex: `0 0 calc((100% - ${(VISIBLE-1)*14}px) / ${VISIBLE})`, minWidth: 0 }}
                    className={"lp-game-chip" + (ready ? " active" : "")}>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <div className="game-icon" style={{ width: 38, height: 38, color: ready ? "var(--accent)" : "var(--faint)", background: ready ? "var(--accent-50)" : "var(--bg-2)", borderColor: ready ? "var(--accent-100)" : "var(--line)" }}>
                        <Icon name={g.icon} size={18} />
                      </div>
                      <span style={{ fontWeight: 700, fontSize: 13, color: ready ? "var(--ink)" : "var(--ink-2)" }}>{t("game." + g.id + ".name")}</span>
                    </div>
                    <p className="muted" style={{ fontSize: 12, margin: 0, lineHeight: 1.4 }}>{t("game." + g.id + ".desc")}</p>
                    <span className={"tag " + (ready ? "live" : "soon")} style={{ alignSelf: "flex-start", fontSize: 11 }}>
                      {ready && <span style={{ width: 5, height: 5, borderRadius: 99, background: "var(--good)", display: "inline-block", marginRight: 5 }}></span>}
                      {t(ready ? "tag.ready" : "tag.soon")}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>
          <button className="iconbtn carousel-btn" onClick={next} disabled={clampedIdx >= maxIdx}
            style={{ position: "absolute", right: 8, top: "50%", transform: "translateY(-50%)", zIndex: 2 }}>
            <Icon name="arrow" size={18} />
          </button>
          <div style={{ display: "flex", justifyContent: "center", gap: 6, marginTop: 14 }}>
            {Array.from({ length: maxIdx + 1 }, (_, i) => (
              <button key={i} onClick={() => setCarouselIdx(i)}
                style={{ width: i === clampedIdx ? 20 : 8, height: 8, borderRadius: 4, border: "none",
                  background: i === clampedIdx ? "var(--accent)" : "var(--line-2)", padding: 0,
                  cursor: "pointer", transition: "all .2s" }} />
            ))}
          </div>
        </div>
      </section>

      {/* Features */}
      <div className="lp-features">
        {[{ icon: "book", tk: "f1" }, { icon: "users", tk: "f2" }, { icon: "grid", tk: "f3" }].map(({ icon, tk }) => (
          <div className="lp-feat" key={tk}>
            <div className="lp-feat-icon"><Icon name={icon} size={22} /></div>
            <h3>{t("landing." + tk)}</h3>
            <p>{t("landing." + tk + "sub")}</p>
          </div>
        ))}
      </div>

      <section className="lp-cta-banner">
        <h2>{lang === "de" ? "Bereit zum Spielen?" : "Ready to play?"}</h2>
        <p>{t("landing.sub")}</p>
        <button className="btn lg" style={{ background: "var(--accent)", color: "#fff", border: "none" }} onClick={() => nav("#/signup")}>
          {t("landing.cta1")}<Icon name="arrow" />
        </button>
      </section>

      <footer className="wrap" style={{ paddingTop: 24, paddingBottom: 32, borderTop: "1px solid var(--line)", marginTop: 40 }}>
        <div style={{ display: "flex", flexWrap: "wrap", gap: "12px 28px", alignItems: "center" }}>
          <span style={{ color: "var(--faint)", fontSize: 13 }}>{t("landing.footer")}</span>
          <span style={{ flex: 1 }}></span>
          <a href="legal/impressum.html" style={{ color: "var(--faint)", fontSize: 13, textDecoration: "none" }}>Impressum</a>
          <a href="legal/privacy.html"   style={{ color: "var(--faint)", fontSize: 13, textDecoration: "none" }}>Datenschutz</a>
          <a href="legal/terms.html"     style={{ color: "var(--faint)", fontSize: 13, textDecoration: "none" }}>AGB</a>
        </div>
      </footer>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────
   SIGN-UP WIZARD  (3 steps)
   Step 0 — Account details
   Step 1 — Plan selection (Free / Pro)
   Step 2 — Success / payment result
───────────────────────────────────────────────────────────── */
const PLANS = [
  {
    id: "pro_monthly",
    icon: "trophy",
    labelKey: "plan.pro",
    priceKey: "plan.proPrice",
    intervalKey: "plan.monthly",
    features: ["plan.pro.f1", "plan.pro.f2", "plan.pro.f3", "plan.pro.f4"],
    cta: "plan.pro.cta",
    accent: true,
  },
  {
    id: "pro_yearly",
    icon: "trophy",
    labelKey: "plan.pro",
    priceKey: "plan.proYearlyPrice",
    intervalKey: "plan.yearly",
    savingKey: "plan.yearlySaving",
    features: ["plan.pro.f1", "plan.pro.f2", "plan.pro.f3", "plan.pro.f4"],
    cta: "plan.pro.cta",
    accent: true,
  },
];

function SignUp({ nav, onCreate, onFinish, lang, setLang }) {
  const [step, setStep]       = useStateAuth(0);
  const [display, setDisplay] = useStateAuth("");
  const [email, setEmail]     = useStateAuth("");
  const [password, setPassword] = useStateAuth("");
  const [plan, setPlan]       = useStateAuth("pro_monthly");
  const [result, setResult]   = useStateAuth(null);
  const [createdAcc, setCreatedAcc] = useStateAuth(null);
  const [busy, setBusy]       = useStateAuth(false);
  const [error, setError]     = useStateAuth("");

  const emailOk   = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email.trim());
  const passwordOk = password.length >= 8;
  const step0ok   = display.trim().length >= 2 && emailOk && passwordOk;

  async function handleStep0(e) {
    e && e.preventDefault();
    if (!step0ok) return;
    setBusy(true);
    setError("");
    try {
      let acc;
      if (window.sb) {
        const user = await Store.signUpWithSupabase({ displayName: display, email: email.trim(), password });
        acc = { id: user.id, displayName: display, email: email.trim() };
      } else {
        acc = onCreate({ displayName: display, email: email.trim() });
      }
      setCreatedAcc(acc);
      setStep(1);
    } catch (err) {
      setError(err.message || (lang === "de" ? "Fehler beim Erstellen des Kontos." : "Error creating account."));
    } finally {
      setBusy(false);
    }
  }

  async function handlePlanChoice(chosenPlan) {
    setPlan(chosenPlan);
    setBusy(true);
    const interval = chosenPlan === "pro_yearly" ? "year" : "month";
    const priceId  = chosenPlan === "pro_yearly"
      ? window.__ENV?.STRIPE_PRO_YEARLY_PRICE_ID
      : window.__ENV?.STRIPE_PRO_MONTHLY_PRICE_ID;
    try {
      if (priceId && createdAcc?.id) {
        await Store.createCheckoutSession({
          priceId, interval,
          profileId: createdAcc.id,
          email:     createdAcc.email,
        });
        setResult("failed"); // only reached if Stripe redirects back (cancel)
      } else {
        await new Promise(r => setTimeout(r, 1200));
        setResult("success");
      }
    } catch {
      setResult("failed");
    } finally {
      setBusy(false);
      setStep(2);
    }
  }

  const STEPS = [
    lang === "de" ? "Konto" : "Account",
    lang === "de" ? "Tarif" : "Plan",
    lang === "de" ? "Fertig" : "Done",
  ];

  return (
    <div className="app" style={{ background: "var(--bg)" }}>
      <header className="topbar">
        <div className="wrap topbar-inner">
          <div className="brand" onClick={() => nav("#/")}><Logo /> Scoby</div>
          <span className="spacer"></span>
          <LangToggle lang={lang} onChange={setLang} />
          {step < 2 && (
            <button className="btn ghost sm" onClick={() => nav("#/signin")}>{t("nav.signin")}</button>
          )}
        </div>
      </header>

      <main className="wrap" style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center",
        padding: "36px 24px 60px", gap: 28 }}>

        {/* Step indicator */}
        <div style={{ display: "flex", alignItems: "center", gap: 0, marginBottom: 4 }}>
          {STEPS.map((label, i) => (
            <React.Fragment key={i}>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
                <div style={{ width: 32, height: 32, borderRadius: "50%", display: "flex",
                  alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 13,
                  background: i < step ? "var(--accent)" : i === step ? "var(--accent)" : "var(--bg-2)",
                  color: i <= step ? "#fff" : "var(--ink-2)",
                  border: i > step ? "1.5px solid var(--line)" : "none",
                  transition: "all .3s" }}>
                  {i < step ? "✓" : i + 1}
                </div>
                <span style={{ fontSize: 12, fontWeight: i === step ? 700 : 400,
                  color: i === step ? "var(--ink)" : "var(--ink-2)", whiteSpace: "nowrap" }}>{label}</span>
              </div>
              {i < STEPS.length - 1 && (
                <div style={{ width: 60, height: 2, background: i < step ? "var(--accent)" : "var(--line-2)",
                  margin: "0 8px", marginBottom: 22, transition: "background .3s" }} />
              )}
            </React.Fragment>
          ))}
        </div>

        {/* ── Step 0: Account ─────────────────────────────── */}
        {step === 0 && (
          <div className="card" style={{ width: "100%", maxWidth: 460, padding: 30 }}>
            <span className="eyebrow">{t("signup.eyebrow")}</span>
            <h2 style={{ fontSize: 24, marginTop: 8, marginBottom: 6 }}>{t("signup.title")}</h2>
            <p className="muted" style={{ fontSize: 14, marginBottom: 22 }}>{t("signup.sub")}</p>
            <form onSubmit={handleStep0} style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <div className="field">
                <label>{t("signup.name")}</label>
                <input className="input" placeholder={t("signup.namePh")} value={display} autoFocus
                  onChange={e => { setDisplay(e.target.value); setError(""); }} />
              </div>
              <div className="field">
                <label>{t("signup.email")}</label>
                <input className="input" type="email" placeholder="you@example.com" value={email}
                  onChange={e => { setEmail(e.target.value); setError(""); }} />
              </div>
              <div className="field">
                <label>{t("signup.password")}</label>
                <input className="input" type="password" placeholder={t("signup.passwordPh")} value={password}
                  onChange={e => { setPassword(e.target.value); setError(""); }} />
              </div>
              {error && (
                <div style={{ color: "var(--strike)", fontSize: 14, padding: "10px 14px",
                  background: "oklch(0.97 0.04 25)", borderRadius: "var(--r)", border: "1px solid oklch(0.88 0.07 25)" }}>
                  {error}
                </div>
              )}
              <button className="btn primary lg block" type="submit" disabled={!step0ok || busy} style={{ marginTop: 8 }}>
                {busy ? (lang === "de" ? "Konto wird erstellt…" : "Creating account…") : (lang === "de" ? "Weiter" : "Continue")}
                {!busy && <Icon name="arrow" />}
              </button>
            </form>
          </div>
        )}

        {/* ── Step 1: Plan ─────────────────────────────────── */}
        {step === 1 && (
          <div style={{ width: "100%", maxWidth: 680 }}>
            <h2 style={{ textAlign: "center", fontSize: 24, marginBottom: 6 }}>
              {lang === "de" ? "Wähle deinen Tarif" : "Choose your plan"}
            </h2>
            <p className="muted" style={{ textAlign: "center", marginBottom: 28, fontSize: 14 }}>
              {lang === "de" ? "Jederzeit wechselbar. Keine versteckten Kosten." : "Switch anytime. No hidden fees."}
            </p>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 14 }}>
              {PLANS.map(p => (
                <div key={p.id} className="card"
                  style={{ padding: 28, display: "flex", flexDirection: "column", gap: 14,
                    border: p.accent ? "2px solid var(--accent)" : "1.5px solid var(--line)",
                    position: "relative", overflow: "hidden" }}>
                  {(p.accent || p.badgeKey || p.savingKey) && (
                    <div style={{ position: "absolute", top: 12, right: 12, display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 4 }}>
                      {p.savingKey && (
                        <div style={{ background: "oklch(0.55 0.18 145)", color: "#fff", fontSize: 11, fontWeight: 700,
                          padding: "3px 9px", borderRadius: 99 }}>{t(p.savingKey)}</div>
                      )}
                      {p.badgeKey && (
                        <div style={{ background: "oklch(0.5 0.15 280)", color: "#fff", fontSize: 11, fontWeight: 700,
                          padding: "3px 9px", borderRadius: 99 }}>{t(p.badgeKey)}</div>
                      )}
                    </div>
                  )}
                  <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <div className="game-icon" style={{ width: 44, height: 44, color: p.accent ? "var(--accent)" : "var(--ink-2)",
                      background: p.accent ? "var(--accent-50)" : "var(--bg-2)", borderColor: p.accent ? "var(--accent-100)" : "var(--line)" }}>
                      <Icon name={p.icon} size={22} />
                    </div>
                    <div>
                      <div style={{ fontWeight: 800, fontSize: 16 }}>{t(p.labelKey)}
                        {p.intervalKey && <span className="muted" style={{ fontWeight: 400, fontSize: 13 }}> · {t(p.intervalKey)}</span>}
                      </div>
                      <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20,
                        color: p.accent ? "var(--accent)" : "var(--ink)" }}>{t(p.priceKey)}</div>
                    </div>
                  </div>
                  <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 8 }}>
                    {p.features.map(f => (
                      <li key={f} style={{ display: "flex", gap: 9, alignItems: "flex-start", fontSize: 14 }}>
                        <span style={{ color: p.accent ? "var(--accent)" : "var(--good)", marginTop: 1, flexShrink: 0 }}>✓</span>
                        <span>{t(f)}</span>
                      </li>
                    ))}
                  </ul>
                  <button className={"btn lg block" + (p.accent ? " primary" : "")}
                    disabled={busy}
                    onClick={() => handlePlanChoice(p.id)}
                    style={{ marginTop: "auto" }}>
                    {busy && plan === p.id
                      ? (lang === "de" ? "Weiterleitung…" : "Redirecting…")
                      : t(p.cta)}
                    {!busy && <Icon name={p.accent ? "arrow" : "play"} size={16} />}
                  </button>
                </div>
              ))}
            </div>
            <p className="faint" style={{ textAlign: "center", fontSize: 12.5, marginTop: 18 }}>
              {lang === "de"
                ? "Pro-Zahlung wird von Stripe sicher verarbeitet. Jederzeit kündbar."
                : "Pro payment processed securely by Stripe. Cancel anytime."}
            </p>
          </div>
        )}

        {/* ── Step 2: Result ───────────────────────────────── */}
        {step === 2 && (
          <div className="card" style={{ width: "100%", maxWidth: 460, padding: 36, textAlign: "center" }}>
            {result === "success" ? (
              <React.Fragment>
                <div style={{ fontSize: 52, marginBottom: 12 }}>🎉</div>
                <h2 style={{ fontSize: 24, marginBottom: 8 }}>
                  {lang === "de" ? `Willkommen, ${display}!` : `Welcome, ${display}!`}
                </h2>
                <p className="muted" style={{ fontSize: 15, marginBottom: 10 }}>
                  {lang === "de" ? "Du bist jetzt Scoby Pro. Genieße alle Features!" : "You're now on Scoby Pro. Enjoy all features!"}
                </p>
                <div style={{ display: "inline-flex", alignItems: "center", gap: 8,
                  background: "var(--accent-50)", border: "1px solid var(--accent-100)", borderRadius: "var(--r)",
                  padding: "10px 16px", marginBottom: 20, fontSize: 13, color: "var(--accent)", fontWeight: 600 }}>
                  <Icon name="trophy" size={16} />
                  <span>{lang === "de" ? "Pro · Unbegrenzte Spiele" : "Pro · Unlimited games"}</span>
                </div>
                <button className="btn primary lg block" onClick={() => onFinish ? onFinish(createdAcc) : nav("#/")}>
                  {lang === "de" ? "Zum Dashboard" : "Go to Dashboard"}<Icon name="arrow" />
                </button>
              </React.Fragment>
            ) : (
              <React.Fragment>
                <div style={{ fontSize: 52, marginBottom: 12 }}>😕</div>
                <h2 style={{ fontSize: 22, marginBottom: 8 }}>
                  {lang === "de" ? "Zahlung nicht abgeschlossen" : "Payment not completed"}
                </h2>
                <p className="muted" style={{ fontSize: 14, marginBottom: 24 }}>
                  {lang === "de"
                    ? "Keine Sorge — dein Konto ist erstellt. Du kannst jederzeit auf Pro upgraden."
                    : "No worries — your account is created. You can upgrade to Pro anytime."}
                </p>
                <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                  <button className="btn primary lg block" onClick={() => onFinish ? onFinish(createdAcc) : nav("#/")}>
                    {lang === "de" ? "Zum Dashboard" : "Go to Dashboard"}<Icon name="arrow" />
                  </button>
                  <button className="btn lg block" onClick={() => { setResult(null); setStep(1); }}>
                    {lang === "de" ? "Nochmal versuchen" : "Try again"}
                  </button>
                </div>
              </React.Fragment>
            )}
          </div>
        )}
      </main>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────
   SIGN-IN
───────────────────────────────────────────────────────────── */
function SignIn({ nav, onSignIn, lang, setLang }) {
  const [email, setEmail]       = useStateAuth("");
  const [password, setPassword] = useStateAuth("");
  const [error, setError]       = useStateAuth("");
  const [busy, setBusy]         = useStateAuth(false);

  async function submit(e) {
    e && e.preventDefault();
    if (!email.trim() || !password) return;
    setBusy(true);
    setError("");
    try {
      if (window.sb) {
        await Store.signInWithSupabase({ email: email.trim(), password });
        onSignIn(Store.getAccount());
      } else {
        const acc = Store.getAccount();
        if (acc && acc.email && acc.email.toLowerCase() === email.trim().toLowerCase()) {
          onSignIn(acc);
        } else {
          setError(t("signin.notfound"));
        }
      }
    } catch (err) {
      setError(t("signin.error") || err.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="app">
      <header className="topbar">
        <div className="wrap topbar-inner">
          <div className="brand" onClick={() => nav("#/")}><Logo /> Scoby</div>
          <span className="spacer"></span>
          <LangToggle lang={lang} onChange={setLang} />
        </div>
      </header>
      <main className="wrap" style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: "40px 24px" }}>
        <div className="card" style={{ width: "100%", maxWidth: 440, padding: 30 }}>
          <span className="eyebrow">{t("signin.eyebrow")}</span>
          <h2 style={{ fontSize: 26, marginTop: 10 }}>{t("signin.title")}</h2>
          <p className="muted" style={{ marginTop: 6, marginBottom: 22, fontSize: 14.5 }}>{t("signin.sub")}</p>
          <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div className="field">
              <label>{t("signup.email")}</label>
              <input className="input" type="email" placeholder="you@example.com" value={email} autoFocus
                onChange={e => { setEmail(e.target.value); setError(""); }} />
            </div>
            <div className="field">
              <label>{t("signin.password")}</label>
              <input className="input" type="password" placeholder="••••••••" value={password}
                onChange={e => { setPassword(e.target.value); setError(""); }} />
            </div>
            {error && (
              <div style={{ color: "var(--strike)", fontSize: 14, padding: "10px 14px",
                background: "oklch(0.97 0.04 25)", borderRadius: "var(--r)", border: "1px solid oklch(0.88 0.07 25)" }}>
                {error}
              </div>
            )}
            <button className="btn primary lg block" type="submit" disabled={busy}>
              {busy ? (lang === "de" ? "Anmelden…" : "Signing in…") : t("signin.submit")}
              {!busy && <Icon name="arrow" />}
            </button>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8, justifyContent: "space-between", marginTop: 4 }}>
              <button className="btn ghost block" type="button" onClick={() => nav("#/signup")} style={{ flex: 1 }}>{t("signin.create")}</button>
              <button className="btn ghost block" type="button" onClick={() => nav("#/forgot")} style={{ flex: 1 }}>{t("signin.forgot")}</button>
            </div>
          </form>
        </div>
      </main>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────
   FORGOT PASSWORD
───────────────────────────────────────────────────────────── */
function ForgotPassword({ nav, lang, setLang }) {
  const [email, setEmail] = useStateAuth("");
  const [sent, setSent]   = useStateAuth(false);
  const [busy, setBusy]   = useStateAuth(false);
  const [error, setError] = useStateAuth("");

  async function submit(e) {
    e && e.preventDefault();
    if (!email.trim()) return;
    setBusy(true);
    setError("");
    try {
      await Store.resetPassword({ email: email.trim() });
      setSent(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="app">
      <header className="topbar">
        <div className="wrap topbar-inner">
          <div className="brand" onClick={() => nav("#/")}><Logo /> Scoby</div>
          <span className="spacer"></span>
          <LangToggle lang={lang} onChange={setLang} />
        </div>
      </header>
      <main className="wrap" style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: "40px 24px" }}>
        <div className="card" style={{ width: "100%", maxWidth: 440, padding: 30 }}>
          <span className="eyebrow">{t("reset.eyebrow")}</span>
          <h2 style={{ fontSize: 26, marginTop: 10 }}>{t("reset.title")}</h2>
          <p className="muted" style={{ marginTop: 6, marginBottom: 22, fontSize: 14.5 }}>{t("reset.sub")}</p>
          {sent ? (
            <React.Fragment>
              <div style={{ color: "var(--good)", fontSize: 15, marginBottom: 20 }}>✓ {t("reset.sent")}</div>
              <button className="btn ghost block" onClick={() => nav("#/signin")}>{t("reset.back")}</button>
            </React.Fragment>
          ) : (
            <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <div className="field">
                <label>{t("signup.email")}</label>
                <input className="input" type="email" placeholder="you@example.com" value={email} autoFocus
                  onChange={e => { setEmail(e.target.value); setError(""); }} />
              </div>
              {error && (
                <div style={{ color: "var(--strike)", fontSize: 14, padding: "10px 14px",
                  background: "oklch(0.97 0.04 25)", borderRadius: "var(--r)", border: "1px solid oklch(0.88 0.07 25)" }}>
                  {error}
                </div>
              )}
              <button className="btn primary lg block" type="submit" disabled={busy || !email.trim()}>
                {busy ? "…" : t("reset.submit")}<Icon name="arrow" />
              </button>
              <button className="btn ghost block" type="button" onClick={() => nav("#/signin")}>{t("reset.back")}</button>
            </form>
          )}
        </div>
      </main>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────
   RESET PASSWORD  (landed here via recovery email link)
───────────────────────────────────────────────────────────── */
function ResetPassword({ nav, lang, setLang }) {
  const [pw, setPw]       = useStateAuth("");
  const [pw2, setPw2]     = useStateAuth("");
  const [done, setDone]   = useStateAuth(false);
  const [busy, setBusy]   = useStateAuth(false);
  const [error, setError] = useStateAuth("");

  async function submit(e) {
    e && e.preventDefault();
    if (pw.length < 8) return;
    if (pw !== pw2) { setError(t("resetpw.mismatch")); return; }
    setBusy(true);
    setError("");
    try {
      const { error: err } = await window.sb.auth.updateUser({ password: pw });
      if (err) throw err;
      setDone(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="app">
      <header className="topbar">
        <div className="wrap topbar-inner">
          <div className="brand" onClick={() => nav("#/")}><Logo /> Scoby</div>
          <span className="spacer"></span>
          <LangToggle lang={lang} onChange={setLang} />
        </div>
      </header>
      <main className="wrap" style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: "40px 24px" }}>
        <div className="card" style={{ width: "100%", maxWidth: 440, padding: 30 }}>
          <span className="eyebrow">{t("reset.eyebrow")}</span>
          <h2 style={{ fontSize: 26, marginTop: 10 }}>{t("resetpw.title")}</h2>
          <p className="muted" style={{ marginTop: 6, marginBottom: 22, fontSize: 14.5 }}>{t("resetpw.sub")}</p>
          {done ? (
            <React.Fragment>
              <div style={{ color: "var(--good)", fontSize: 15, marginBottom: 20 }}>✓ {t("resetpw.done")}</div>
              <button className="btn primary lg block" onClick={() => nav("#/")}>{t("dash.eyebrow")}<Icon name="arrow" /></button>
            </React.Fragment>
          ) : (
            <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <div className="field">
                <label>{t("resetpw.new")}</label>
                <input className="input" type="password" placeholder="••••••••" value={pw} autoFocus
                  onChange={e => { setPw(e.target.value); setError(""); }} />
              </div>
              <div className="field">
                <label>{t("resetpw.confirm")}</label>
                <input className="input" type="password" placeholder="••••••••" value={pw2}
                  onChange={e => { setPw2(e.target.value); setError(""); }} />
              </div>
              {error && (
                <div style={{ color: "var(--strike)", fontSize: 14, padding: "10px 14px",
                  background: "oklch(0.97 0.04 25)", borderRadius: "var(--r)", border: "1px solid oklch(0.88 0.07 25)" }}>
                  {error}
                </div>
              )}
              <button className="btn primary lg block" type="submit" disabled={busy || pw.length < 8}>
                {busy ? "…" : t("resetpw.submit")}<Icon name="arrow" />
              </button>
              <button className="btn ghost block" type="button" onClick={() => nav("#/signin")}>{t("reset.back")}</button>
            </form>
          )}
        </div>
      </main>
    </div>
  );
}

Object.assign(window, { Landing, SignIn, SignUp, ForgotPassword, ResetPassword });
