// Waitlist.jsx — Countdown, WaitlistForm (email → Resend), StoreBadges.

/* ---------- Countdown ---------- */
function pad2(n) { return String(n).padStart(2, "0"); }

function Countdown({ dateStr, light = false }) {
  const target = React.useMemo(() => {
    const d = new Date(dateStr + "T00:00:00+05:30");
    return isNaN(d.getTime()) ? null : d.getTime();
  }, [dateStr]);

  const calc = React.useCallback(() => {
    if (!target) return null;
    const diff = Math.max(0, target - Date.now());
    return {
      d: Math.floor(diff / 86400000),
      h: Math.floor(diff / 3600000) % 24,
      m: Math.floor(diff / 60000) % 60,
      s: Math.floor(diff / 1000) % 60,
      over: diff === 0,
    };
  }, [target]);

  const [t, setT] = React.useState(calc);
  React.useEffect(() => {
    setT(calc());
    const id = setInterval(() => setT(calc()), 1000);
    return () => clearInterval(id);
  }, [calc]);

  if (!t) return null;
  if (t.over) {
    return <div lang="hi" style={{ fontFamily: "var(--font-display)", fontSize: 30, color: "var(--accent)" }}>आज का दिन आ गया।</div>;
  }

  const cells = [
    { v: String(t.d), l: "दिन" },
    { v: pad2(t.h), l: "घंटे" },
    { v: pad2(t.m), l: "मिनट" },
    { v: pad2(t.s), l: "सेकंड" },
  ];

  return (
    <div className="countdown" role="timer" aria-label={`${t.d} days ${t.h} hours ${t.m} minutes to launch`}
         style={{ display: "flex", alignItems: "flex-start", justifyContent: "center", gap: "clamp(14px, 3.5vw, 34px)" }}>
      {cells.map((c, i) => (
        <React.Fragment key={c.l}>
          {i > 0 && (
            <span aria-hidden="true" style={{
              fontFamily: "var(--font-display)", fontSize: "clamp(26px, 4vw, 44px)", lineHeight: 1.1,
              color: light ? "rgba(207,150,71,0.45)" : "rgba(161,108,36,0.35)", paddingTop: 2,
            }}>·</span>
          )}
          <div style={{ textAlign: "center", minWidth: 56 }}>
            <div style={{
              fontFamily: "var(--font-display)", fontWeight: 400, fontVariantNumeric: "tabular-nums",
              fontSize: "clamp(34px, 5.5vw, 58px)", lineHeight: 1.1, color: "var(--accent-strong)",
              ...(light ? { color: "var(--accent)" } : null),
            }}>{c.v}</div>
            <div lang="hi" style={{
              fontFamily: "var(--font-hi-body)", fontSize: 12.5, fontWeight: 500, letterSpacing: "0.04em",
              marginTop: 8,
              color: light ? "rgba(255,250,240,0.6)" : "var(--aohp-ink-grey)",
            }}>{c.l}</div>
          </div>
        </React.Fragment>
      ))}
    </div>
  );
}

/* ---------- Waitlist form ---------- */
function WaitlistForm({ dark = false, id }) {
  const [email, setEmail] = React.useState("");
  const [state, setState] = React.useState("idle"); // idle | submitting | done | error

  const submit = async (e) => {
    e.preventDefault();
    const ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
    if (!ok) { setState("error"); return; }
    setState("submitting");
    try {
      const res = await fetch("/api/waitlist", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: email.trim() }),
      });
      if (!res.ok) throw new Error("server");
      setState("done");
    } catch (_) {
      setState("error");
    }
  };

  const border = dark ? "1px solid rgba(207,150,71,0.32)" : "1px solid var(--aohp-border-gold)";

  return (
    <div id={id} style={{ maxWidth: 540, marginInline: "auto" }}>
      <form onSubmit={submit} className="waitlist-form" style={{
        display: "flex", gap: 10, flexWrap: "wrap",
        background: dark ? "rgba(255,255,234,0.05)" : "var(--bg-surface)",
        border, borderRadius: 9999, padding: 8, paddingLeft: 22,
        boxShadow: dark ? "none" : "0 6px 28px rgba(65,32,15,0.08)",
      }}>
        <input
          type="email" value={email} aria-label="Email address"
          onChange={(ev) => { setEmail(ev.target.value); if (state !== "idle") setState("idle"); }}
          placeholder="अपनी ईमेल आईडी लिखिए"
          lang="hi"
          disabled={state === "submitting" || state === "done"}
          style={{
            flex: 1, minWidth: 180, background: "transparent", border: "none", outline: "none",
            fontFamily: "var(--font-body)", fontSize: 15,
            color: dark ? "#fffaf0" : "var(--fg1)", padding: "12px 0",
            opacity: state === "done" ? 0.5 : 1,
          }}
        />
        <button type="submit" className="btn btn--gold" style={{ borderRadius: 9999 }} lang="hi"
                disabled={state === "submitting" || state === "done"}>
          {state === "submitting" ? "जोड़ रहे हैं…" : state === "done" ? "हो गया ✓" : "जुड़िए"}
        </button>
      </form>
      <p aria-live="polite" lang="hi" style={{
        textAlign: "center", marginTop: 14, marginBottom: 0, minHeight: 22,
        fontFamily: "var(--font-hi-body)", fontSize: 14,
        color: state === "error" ? (dark ? "#e8a87c" : "var(--aohp-error, #a14224)")
             : dark ? "rgba(255,250,240,0.65)" : "var(--fg3)",
      }}>
        {state === "done" ? "आपका स्वागत है। आप सूची में जुड़ गए।"
          : state === "error" ? "ज़रा ईमेल दोबारा देख लीजिए।"
          : "तैयार होते ही, सबसे पहले आपको ख़बर भेजेंगे।"}
      </p>
    </div>
  );
}

/* ---------- Store badges (coming-soon state) ---------- */
function StoreBadges({ dark = false }) {
  const fg = dark ? "rgba(255,250,240,0.75)" : "var(--fg2)";
  const sub = dark ? "rgba(255,250,240,0.45)" : "var(--aohp-ink-grey)";
  const badge = {
    display: "inline-flex", alignItems: "center", gap: 12, padding: "12px 22px",
    border: dark ? "1px solid rgba(207,150,71,0.3)" : "1px solid var(--border)",
    borderRadius: 14, cursor: "default", userSelect: "none",
  };
  return (
    <div style={{ display: "flex", gap: 14, justifyContent: "center", flexWrap: "wrap" }}>
      <div style={badge} aria-label="App Store — coming soon">
        <svg width="22" height="22" viewBox="0 0 24 24" fill={fg} aria-hidden="true">
          <path d="M17.05 12.54c-.03-2.5 2.04-3.7 2.13-3.76-1.16-1.7-2.97-1.93-3.61-1.96-1.54-.16-3 .9-3.78.9-.78 0-1.98-.88-3.26-.85-1.68.02-3.22.97-4.08 2.47-1.74 3.02-.44 7.5 1.25 9.95.83 1.2 1.82 2.55 3.12 2.5 1.25-.05 1.72-.81 3.23-.81 1.51 0 1.93.81 3.25.79 1.35-.02 2.2-1.22 3.02-2.43.95-1.39 1.34-2.74 1.36-2.81-.03-.01-2.6-1-2.63-3.99z"/>
          <path d="M14.54 5.2c.69-.83 1.15-1.99 1.02-3.14-.99.04-2.18.66-2.89 1.49-.63.73-1.19 1.91-1.04 3.04 1.1.09 2.23-.56 2.91-1.39z"/>
        </svg>
        <span style={{ display: "flex", flexDirection: "column", gap: 1, textAlign: "left" }}>
          <span style={{ font: "600 9.5px/1 var(--font-body)", letterSpacing: "0.14em", textTransform: "uppercase", color: sub }}>Coming Soon On</span>
          <span style={{ font: "600 15px/1.2 var(--font-body)", color: fg }}>App Store</span>
        </span>
      </div>
      <div style={badge} aria-label="Google Play — coming soon">
        <svg width="20" height="22" viewBox="0 0 24 24" fill="none" stroke={fg} strokeWidth="1.6" strokeLinejoin="round" aria-hidden="true">
          <path d="M5 3.5v17c0 .6.65 1 1.17.68l14.06-8.5a.8.8 0 0 0 0-1.36L6.17 2.82A.78.78 0 0 0 5 3.5z"/>
        </svg>
        <span style={{ display: "flex", flexDirection: "column", gap: 1, textAlign: "left" }}>
          <span style={{ font: "600 9.5px/1 var(--font-body)", letterSpacing: "0.14em", textTransform: "uppercase", color: sub }}>Coming Soon On</span>
          <span style={{ font: "600 15px/1.2 var(--font-body)", color: fg }}>Google Play</span>
        </span>
      </div>
    </div>
  );
}

Object.assign(window, { Countdown, WaitlistForm, StoreBadges });
