// screens-public.jsx — Landing + Signup

const API_BASE = "";

// ── LANDING — single page, hero + how-it-works + pricing ──────────────
const Landing = ({ goto, selectPath }) => {
  const [stats, setStats] = React.useState({ total_claims: null });

  React.useEffect(() => {
    fetch("/api/public/stats").then(r => r.ok ? r.json() : null)
      .then(d => { if (d) setStats(d); }).catch(() => {});
    document.documentElement.classList.add("pattern-loud");
    return () => document.documentElement.classList.remove("pattern-loud");
  }, []);

  const tiers = [
    { id: "house_cut",   name: "House Cut",   price: 10, blurb: "Regular drops" },
    { id: "prime_cut",   name: "Prime Cut",   price: 15, blurb: "+ highroller", featured: true },
    { id: "grand_feast", name: "Grand Feast", price: 30, blurb: "Every code" },
  ];

  const steps = [
    { icon: "tg",    label: "Link Telegram" },
    { icon: "key",   label: "Add API key" },
    { icon: "bolt",  label: "We claim" },
  ];

  const go = () => { selectPath("api"); goto("signup"); };

  return (
    <div className="container fade-in" style={{ position: "relative" }}>
      <div className="landing-bg" aria-hidden="true">
        <div className="glow" />
        {Array.from({ length: 10 }).map((_, i) => (
          <span key={i} className="ember" style={{
            left: `${(i * 9.3 + 6) % 100}%`,
            bottom: `${8 + (i % 5) * 5}%`,
            animationDuration: `${5 + (i % 5) * 0.7}s`,
            animationDelay: `${(i * 0.4) % 5}s`,
          }} />
        ))}
      </div>

      {/* HERO */}
      <section className="landing-hero">
        <span className="eyebrow">🔥 stake sauce</span>
        <h1 className="h1">
          Bonus codes. <span className="accent">Served hot.</span>
        </h1>
        <p className="lead">Auto-claim Stake.com & Stake.us. Pay per slot.</p>
        <div className="row" style={{ marginTop: 28, gap: 10, justifyContent: "center", flexWrap: "wrap" }}>
          <Btn kind="primary" lg onClick={go}>Get started <Icon name="arrow" /></Btn>
          <Btn lg onClick={() => goto("signup")}>Sign in</Btn>
        </div>
        {stats.total_claims != null && (
          <p className="muted mono" style={{ fontSize: 11, marginTop: 18, letterSpacing: ".08em" }}>
            {stats.total_claims.toLocaleString()} cuts claimed
          </p>
        )}
      </section>

      {/* HOW IT WORKS */}
      <section className="landing-steps">
        {steps.map((s, i) => (
          <div key={s.icon} className="landing-step">
            <div className="landing-step-num">{i + 1}</div>
            <Icon name={s.icon} size={22} />
            <span>{s.label}</span>
          </div>
        ))}
      </section>

      {/* PRICING */}
      <section className="landing-pricing">
        <div style={{ textAlign: "center", marginBottom: 18 }}>
          <span className="eyebrow">menu</span>
          <h2 style={{ fontSize: 24, marginTop: 6, marginBottom: 0 }}>Pick a cut</h2>
        </div>
        <div className="grid-3" style={{ gap: 12, maxWidth: 760, margin: "0 auto" }}>
          {tiers.map(p => (
            <div key={p.id}
              className={"tier-card " + (p.featured ? "featured" : "")}
              onClick={go}
              style={{ cursor: "pointer" }}>
              {p.featured && <span className="ribbon">popular</span>}
              <strong style={{ fontSize: 15 }}>{p.name}</strong>
              <div style={{ marginTop: 6, display: "flex", alignItems: "baseline", gap: 3 }}>
                <span style={{ fontFamily: "var(--font-num)", fontSize: 36, fontWeight: 800 }}>${p.price}</span>
                <span className="muted" style={{ fontSize: 11 }}>/slot/mo</span>
              </div>
              <p className="muted" style={{ fontSize: 12, marginTop: 8, margin: 0 }}>{p.blurb}</p>
            </div>
          ))}
        </div>
        <p className="muted" style={{ fontSize: 11, textAlign: "center", marginTop: 14 }}>
          Reloads & daily dollar bundled. Free tier = daily dollar only.
        </p>
      </section>
    </div>
  );
};

// ── SIGNUP — Telegram first ────────────────────────────────────────
const Signup = ({ goto, signIn }) => {
  const [mode, setMode]   = React.useState("telegram"); // telegram | email
  const [isSignIn, setIsSignIn] = React.useState(false);
  const [busy, setBusy]   = React.useState(false);
  const [error, setError] = React.useState("");

  // Telegram state
  const [tgUser, setTgUser]   = React.useState("");
  const [tgCode, setTgCode]   = React.useState(null);
  const [tgPolling, setTgPolling] = React.useState(false);
  const [tgToken, setTgToken] = React.useState(null);
  const pollRef = React.useRef(null);

  // Email state
  const [email, setEmail] = React.useState("");
  const [pw, setPw]       = React.useState("");

  // Credentials-set step (after Telegram, if no email yet)
  const [settingCreds, setSettingCreds] = React.useState(false);
  const [credEmail, setCredEmail] = React.useState("");
  const [credPw, setCredPw]       = React.useState("");
  const [credError, setCredError] = React.useState("");
  const [credBusy, setCredBusy]   = React.useState(false);

  const tgValid    = tgUser.replace("@", "").length > 2;
  const emailValid = /\S+@\S+\.\S+/.test(email) && pw.length >= 6;

  const stopPoll = () => {
    if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null; }
  };

  const startPoll = (code) => {
    stopPoll();
    setTgPolling(true);
    pollRef.current = setInterval(async () => {
      try {
        const r = await fetch(`${API_BASE}/api/auth/telegram/poll`, {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ code }),
        });
        const d = await r.json();
        if (d.verified) {
          stopPoll();
          setTgPolling(false);
          if (d.needs_credentials) {
            setTgToken(d.token);
            setSettingCreds(true);
          } else {
            localStorage.setItem("cc_token", d.token);
            signIn(d.user);
            goto(d.user?.plan && d.user.plan !== "free" ? "dashboard" : "subscription");
          }
        }
      } catch (_) {}
    }, 2000);
  };

  const submitTg = async (e) => {
    e?.preventDefault();
    if (!tgValid) return;
    setError(""); setBusy(true);
    try {
      const r = await fetch(`${API_BASE}/api/auth/telegram/request`, {
        method: "POST", headers: { "content-type": "application/json" },
        body: JSON.stringify({ username: tgUser.replace("@", "") }),
      });
      const d = await r.json();
      if (d.error) { setError(d.error); setBusy(false); return; }
      setTgCode(d.code);
      setBusy(false);
      startPoll(d.code);
    } catch { setError("Network error"); setBusy(false); }
  };

  const submitEmail = async (e) => {
    e?.preventDefault();
    if (!emailValid) return;
    setError(""); setBusy(true);
    const endpoint = isSignIn ? "/api/signin" : "/api/signup";
    try {
      const r = await fetch(`${API_BASE}${endpoint}`, {
        method: "POST", headers: { "content-type": "application/json" },
        body: JSON.stringify({ email, password: pw }),
      });
      const d = await r.json();
      if (d.error) { setError(d.error); setBusy(false); return; }
      localStorage.setItem("cc_token", d.token);
      signIn(d.user);
      goto(d.user?.plan && d.user.plan !== "free" ? "dashboard" : "subscription");
    } catch { setError("Network error"); setBusy(false); }
  };

  const submitCreds = async (e) => {
    e?.preventDefault();
    if (!/\S+@\S+\.\S+/.test(credEmail) || credPw.length < 6) return;
    setCredError(""); setCredBusy(true);
    try {
      const r = await fetch(`${API_BASE}/api/me/set-credentials`, {
        method: "POST",
        headers: { "content-type": "application/json", "Authorization": `Bearer ${tgToken}` },
        body: JSON.stringify({ email: credEmail, password: credPw }),
      });
      const d = await r.json();
      if (d.error) { setCredError(d.error); setCredBusy(false); return; }
      localStorage.setItem("cc_token", d.token);
      signIn(d.user);
      goto(d.user?.plan && d.user.plan !== "free" ? "dashboard" : "subscription");
    } catch { setCredError("Network error"); setCredBusy(false); }
  };

  // Credential-set screen (after Telegram verify, no email yet)
  if (settingCreds) {
    const credValid = /\S+@\S+\.\S+/.test(credEmail) && credPw.length >= 6;
    return (
      <div className="container fade-in auth-card">
        <span className="eyebrow">one more thing</span>
        <h2 style={{ fontSize: 26, marginTop: 6, marginBottom: 14 }}>Set a password</h2>
        <Card lift>
          <form onSubmit={submitCreds} className="stack">
            <Field label="Email">
              <Input type="email" placeholder="you@example.com" value={credEmail} onChange={e => setCredEmail(e.target.value)} />
            </Field>
            <Field label="Password" hint="6+ characters">
              <Input type="password" placeholder="••••••••" value={credPw} onChange={e => setCredPw(e.target.value)} />
            </Field>
            {credError && <p className="err-text">{credError}</p>}
            <Btn type="submit" kind="primary" block lg disabled={!credValid || credBusy}>
              {credBusy ? "Saving…" : <>Continue <Icon name="arrow" /></>}
            </Btn>
          </form>
        </Card>
      </div>
    );
  }

  // Telegram code screen
  if (tgCode) {
    return (
      <div className="container fade-in auth-card">
        <Btn kind="ghost" sm onClick={() => { stopPoll(); setTgCode(null); }}><Icon name="left" /> Back</Btn>
        <h2 style={{ fontSize: 24, marginTop: 18, marginBottom: 6 }}>Send to @CCUclaimerbot</h2>
        <p className="muted" style={{ marginBottom: 18, fontSize: 13 }}>
          Open Telegram. Paste this code to the bot.
        </p>
        <Card lift>
          <div className="tg-code">{tgCode}</div>
          <p className="muted" style={{ textAlign: "center", marginTop: 8, fontSize: 12 }}>
            {tgPolling ? "⏳ waiting…" : ""}
          </p>
        </Card>
      </div>
    );
  }

  // Main signup screen — Telegram primary, email collapsed
  return (
    <div className="container fade-in auth-card">
      <Btn kind="ghost" sm onClick={() => goto("landing")}><Icon name="left" /> Back</Btn>
      <h2 style={{ fontSize: 28, marginTop: 18, marginBottom: 18 }}>
        {isSignIn ? "Sign in" : "Sign up"}
      </h2>
      <Card lift>
        {mode === "telegram" ? (
          <form onSubmit={submitTg} className="stack">
            <Field label="Telegram username">
              <Input placeholder="@alice" value={tgUser} onChange={e => setTgUser(e.target.value)} />
            </Field>
            {error && <p className="err-text">{error}</p>}
            <Btn type="submit" kind="primary" block lg disabled={!tgValid || busy}>
              {busy ? "…" : <><Icon name="tg" /> Continue with Telegram</>}
            </Btn>
            <button type="button" className="auth-switch" onClick={() => { setMode("email"); setError(""); }}>
              Use email instead
            </button>
          </form>
        ) : (
          <form onSubmit={submitEmail} className="stack">
            <Field label="Email">
              <Input type="email" placeholder="you@example.com" value={email} onChange={e => setEmail(e.target.value)} />
            </Field>
            <Field label="Password" hint={isSignIn ? "" : "6+ characters"}>
              <Input type="password" placeholder="••••••••" value={pw} onChange={e => setPw(e.target.value)} />
            </Field>
            {error && <p className="err-text">{error}</p>}
            <Btn type="submit" kind="primary" block lg disabled={!emailValid || busy}>
              {busy ? "…" : isSignIn ? <>Sign in <Icon name="arrow" /></> : <>Create account <Icon name="arrow" /></>}
            </Btn>
            <button type="button" className="auth-switch" onClick={() => { setMode("telegram"); setError(""); }}>
              Use Telegram instead
            </button>
          </form>
        )}
      </Card>
      <p className="muted" style={{ textAlign: "center", marginTop: 14, fontSize: 12 }}>
        {isSignIn ? "New here?" : "Already have an account?"}
        {" "}
        <button className="auth-switch inline" onClick={() => { setIsSignIn(!isSignIn); setError(""); }}>
          {isSignIn ? "Sign up" : "Sign in"}
        </button>
      </p>
    </div>
  );
};

Object.assign(window, { Landing, Signup });
