/* Girişimci Yatırımcı Okulu — Ön Kayıt · app */
function useRegForm() {
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [error, setError] = React.useState("");
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  // Seed with the floor so the UI renders instantly, then replace with the
  // live count from beehiiv (via /api/count) on mount. After that it only
  // changes on signup, using the fresh count the subscribe call returns.
  const [count, setCount] = React.useState(31);
  React.useEffect(() => {
    setSubmitted(localStorage.getItem("gy_okul_done") === "1");
    fetch("/api/count")
      .then((r) => r.json())
      .then((d) => { if (typeof d.count === "number") setCount(d.count); })
      .catch(() => {});
  }, []);
  async function submit() {
    if (submitting) return;
    const ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
    if (!ok) { setError("Geçerli bir e-posta adresi gir."); return; }
    setError("");
    setSubmitting(true);
    try {
      const res = await fetch("/api/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: name.trim(), email: email.trim() }),
      });
      if (!res.ok) {
        setError("Bir şeyler ters gitti. Lütfen tekrar dene.");
        return;
      }
      // The server re-queries beehiiv on signup and returns the fresh total.
      const data = await res.json().catch(() => ({}));
      if (typeof data.count === "number") setCount(data.count);
      localStorage.setItem("gy_okul_done", "1");
      setSubmitted(true);
    } catch (e) {
      setError("Bağlantı hatası. Lütfen tekrar dene.");
    } finally {
      setSubmitting(false);
    }
  }
  return { name, setName, email, setEmail, error, submitted, submitting, count, submit };
}

function App() {
  const form = useRegForm();
  const scrollTop = () => window.scrollTo({ top: 0, behavior: "smooth" });
  return (
    <div style={{ background: "#fff" }}>
      <Nav onCTA={scrollTop} />
      <Hero form={form} />
      <GiftBand />
      <Curriculum />
      <Benefits />
      <Community />
      <FAQ />
      <FinalCTA form={form} onScrollTop={scrollTop} />
      <Footer />
    </div>
  );
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
