// Installment pay page (Month 2/3) — opened from a reminder link /#/pay/<token>.
const PayScreen = ({ go }) => {
  const token = window.location.hash.replace(/^#?\/pay\//, "").split("?")[0];
  const [info, setInfo] = React.useState(null);
  const [error, setError] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const [msg, setMsg] = React.useState("");

  React.useEffect(() => {
    apiFetch(`/pay/${encodeURIComponent(token)}`)
      .then((r) => r.json().then((d) => ({ ok: r.ok, d })))
      .then(({ ok, d }) => {
        if (!ok) { setError(d.error || "Invalid payment link."); return; }
        setInfo(d);
        if (d.status === "paid") setDone(true);
      })
      .catch(() => setError("Could not load this payment link."));
  }, []);

  const loadRazorpay = () => new Promise((resolve, reject) => {
    if (window.Razorpay) return resolve();
    const s = document.createElement("script");
    s.src = "https://checkout.razorpay.com/v1/checkout.js";
    s.onload = () => resolve();
    s.onerror = () => reject(new Error("Could not load the payment library."));
    document.body.appendChild(s);
  });

  const pay = async () => {
    setError(""); setMsg(""); setLoading(true);
    const res = await apiFetch(`/pay/${encodeURIComponent(token)}/order`, { method: "POST" });
    const d = await res.json().catch(() => ({}));
    if (!res.ok) { setLoading(false); setError(d.error || "Could not start payment."); return; }
    if (d.paid) { setLoading(false); setDone(true); return; }
    if (!d.razorpay) { setLoading(false); setMsg(d.message || "Please contact us to pay."); return; }
    try { await loadRazorpay(); } catch (e) { setLoading(false); setError(e.message); return; }
    const rzp = new window.Razorpay({
      key: d.key_id, order_id: d.order_id, amount: d.amount, currency: d.currency,
      name: d.name || "EpiqMinds", description: d.description || "", prefill: d.prefill || {},
      theme: { color: "#ff5a3c" },
      modal: { ondismiss: () => { setLoading(false); setMsg("Payment cancelled — you can try again."); } },
      handler: async (resp) => {
        setMsg("Confirming payment…");
        const c = await apiFetch(`/pay/${encodeURIComponent(token)}/confirm`, { method: "POST", body: JSON.stringify({
          razorpay_order_id: resp.razorpay_order_id, razorpay_payment_id: resp.razorpay_payment_id, razorpay_signature: resp.razorpay_signature,
        })});
        setLoading(false);
        if (c.ok) setDone(true);
        else { const e = await c.json().catch(() => ({})); setError(e.error || "Verification failed. If you were charged, contact support."); }
      },
    });
    rzp.open();
  };

  return (
    <AuthShell tagline="Complete your payment.">
      {error && <div style={{ background: "#fee2e2", color: "#b91c1c", borderRadius: 10, padding: "12px 16px", fontSize: 14 }}>{error}</div>}
      {!error && !info && <div style={{ padding: 20, color: "var(--ink-mute)" }}>Loading…</div>}
      {!error && done && (
        <>
          <h1 className="display" style={{ fontSize: 30, margin: "0 0 6px", letterSpacing: "-0.03em" }}>Payment received 🎉</h1>
          <p style={{ fontSize: 14, color: "var(--ink-soft)", marginBottom: 18 }}>Thank you! Your child's classes stay active.</p>
          <button onClick={() => go("/login")} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", padding: "14px 22px", fontSize: 15 }}>Go to sign in →</button>
        </>
      )}
      {!error && info && !done && (
        <>
          <h1 className="display" style={{ fontSize: 30, margin: "0 0 6px", letterSpacing: "-0.03em" }}>Payment {info.seq} of 3</h1>
          <p style={{ fontSize: 14, color: "var(--ink-soft)", marginBottom: 18 }}>
            {info.child_name ? `${info.child_name} — ` : ""}amount due: <strong>${info.amount}</strong>.
          </p>
          {msg && <div style={{ fontSize: 13, color: "var(--ink-soft)", marginBottom: 14 }}>{msg}</div>}
          <button onClick={pay} disabled={loading} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", padding: "14px 22px", fontSize: 15, opacity: loading ? .6 : 1 }}>
            {loading ? "Please wait…" : `Pay $${info.amount} →`}
          </button>
        </>
      )}
    </AuthShell>
  );
};

window.PayScreen = PayScreen;
