/* App shell: router, register modal, mount */
const { useState: useStateApp, useEffect: useEffectApp } = React;

const ROUTES = {
  home: HomePage, events: EventsPage, about: AboutPage, community: CommunityPage,
  poets: PoetsPage, journal: JournalPage, library: LibraryPage,
  perform: PerformPage, membership: MembershipPage, partners: PartnersPage, contact: ContactPage,
};

function RegisterModal({ payload, onClose }) {
  const isMember = !!payload.membership;
  const [step, setStep] = useStateApp(1);
  const [guests, setGuests] = useStateApp(1);
  useEffectApp(() => { document.body.style.overflow = "hidden"; return () => { document.body.style.overflow = ""; }; }, []);
  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-x" onClick={onClose}>✕</button>
        {step === 1 ? (
          <div style={{ padding: "clamp(34px,5vw,46px)" }}>
            <Eyebrow style={{ marginBottom: 14 }}>{isMember ? "Become a member" : payload.status === "wait" ? "Join the waitlist" : "Reserve your seat"}</Eyebrow>
            <h2 className="h-md" style={{ marginBottom: 8 }}>{isMember ? payload.membership : payload.title}</h2>
            <p className="muted" style={{ marginBottom: 26, fontSize: "0.95rem" }}>
              {isMember ? `${payload.price} / ${payload.per} · cancel anytime` : `${payload.date} · ${payload.time} · ${payload.venue}`}
            </p>
            <form onSubmit={(e) => { e.preventDefault(); setStep(2); }} style={{ display: "grid", gap: 18 }}>
              <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <div className="field"><label>Name</label><input required placeholder="Your name" /></div>
                <div className="field"><label>Email</label><input type="email" required placeholder="you@email.com" /></div>
              </div>
              <div className="field"><label>Mobile</label><input required placeholder="+91" /></div>
              {!isMember && payload.status !== "wait" && (
                <div className="field">
                  <label>Seats</label>
                  <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
                    <div style={{ display: "flex", alignItems: "center", border: "1px solid var(--line)", borderRadius: 100 }}>
                      <button type="button" onClick={() => setGuests(Math.max(1, guests - 1))} style={{ padding: "10px 16px", fontSize: "1.2rem" }}>–</button>
                      <span style={{ minWidth: 28, textAlign: "center", fontWeight: 600 }}>{guests}</span>
                      <button type="button" onClick={() => setGuests(Math.min(4, guests + 1))} style={{ padding: "10px 16px", fontSize: "1.2rem" }}>+</button>
                    </div>
                    <span className="muted" style={{ fontSize: "0.9rem" }}>{payload.price} each · <strong style={{ color: "var(--ink)" }}>{payload.price.replace(/[^0-9]/g, "") * guests ? "₹" + (parseInt(payload.price.replace(/[^0-9]/g, "")) * guests).toLocaleString("en-IN") : payload.price}</strong></span>
                  </div>
                </div>
              )}
              <button className="btn btn-primary" type="submit" style={{ justifyContent: "center", marginTop: 4 }}>
                {isMember ? "Continue to confirm" : payload.status === "wait" ? "Join waitlist" : "Continue"} <Icon.arrow className="arr" />
              </button>
              <p className="muted center" style={{ fontSize: "0.78rem" }}>This is a demo — no payment is taken.</p>
            </form>
          </div>
        ) : (
          <div style={{ padding: "clamp(40px,6vw,56px)" }}>
            <ThankYou
              title={isMember ? "Welcome to the circle." : payload.status === "wait" ? "You're on the list." : "Your seat is held."}
              text={isMember
                ? `You're now a ${payload.membership}. Your first reserved seats are waiting at the next volume.`
                : payload.status === "wait"
                ? "We'll email you the moment a seat opens up for this volume."
                : `We've held ${guests} seat${guests > 1 ? "s" : ""} for ${payload.title}. A confirmation is on its way to your inbox.`}
            />
            <button className="btn btn-ghost" style={{ justifyContent: "center", width: "100%", marginTop: 8 }} onClick={onClose}>Done</button>
          </div>
        )}
      </div>
    </div>
  );
}

function App() {
  const [route, setRoute] = useStateApp(() => (location.hash.replace("#/", "") || "home"));
  const [reg, setReg] = useStateApp(null);

  const go = (to) => {
    if (to === route) { window.scrollTo({ top: 0, behavior: "smooth" }); return; }
    location.hash = "#/" + to;
  };
  useEffectApp(() => {
    const onHash = () => {
      const r = location.hash.replace("#/", "") || "home";
      setRoute(ROUTES[r] ? r : "home");
      window.scrollTo({ top: 0, behavior: "instant" in window ? "instant" : "auto" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  useEffectApp(() => {
    const playVids = () => { document.querySelectorAll("video").forEach((v) => v.play().catch(() => {})); };
    playVids();
    const evs = ["pointerdown", "touchstart", "scroll", "keydown"];
    const once = () => { playVids(); evs.forEach((e) => window.removeEventListener(e, once)); };
    evs.forEach((e) => window.addEventListener(e, once, { passive: true }));
    return () => evs.forEach((e) => window.removeEventListener(e, once));
  }, [route]);

  const Page = ROUTES[route] || HomePage;
  const onRegister = (payload) => setReg(payload);

  return (
    <React.Fragment>
      <Nav route={route} go={go} />
      <div key={route} className="page-enter">
        <Page go={go} onRegister={onRegister} />
      </div>
      <Footer go={go} />
      {reg && <RegisterModal payload={reg} onClose={() => setReg(null)} />}
    </React.Fragment>
  );
}

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