// Self-serve enrollment funnel: Registration → OTP → Payment → Done.
// Reads ?plan=monthly|upfront from the hash. Reuses AuthShell/Field from auth.jsx.

const PLAN_INFO = {
  monthly: { label: "Monthly plan", blurb: "$549 total · pay $261 now, then $144 in month 2 and month 3.", first: 261 },
  upfront: { label: "Pay-in-Full", blurb: "$499 one-time — best value, save $50.", first: 499 },
};

const EnrollScreen = ({ go }) => {
  const planKey = (() => {
    const qs = new URLSearchParams((window.location.hash.split("?")[1] || ""));
    return qs.get("plan") === "upfront" ? "upfront" : "monthly";
  })();
  const plan = PLAN_INFO[planKey];

  const [step, setStep] = React.useState("register"); // register | otp | pay | done
  const [form, setForm] = React.useState({ parent_name: "", email: "", phone: "", child_name: "", child_age: "" });
  const [hp, setHp] = React.useState(""); // honeypot
  const [enrollmentId, setEnrollmentId] = React.useState(null);
  const [amountDue, setAmountDue] = React.useState(plan.first);
  const [devCode, setDevCode] = React.useState("");
  const [code, setCode] = React.useState("");
  const [payMsg, setPayMsg] = React.useState("");
  const [error, setError] = React.useState("");
  const [loading, setLoading] = React.useState(false);

  const submitRegister = async (e) => {
    e.preventDefault(); setError("");
    if (!form.parent_name.trim() || !form.email.trim() || !form.child_name.trim()) { setError("Please fill in the required fields."); return; }
    setLoading(true);
    const res = await apiFetch("/enroll/start", { method: "POST", body: JSON.stringify({
      plan: planKey, parent_name: form.parent_name, email: form.email, phone: form.phone || undefined,
      child_name: form.child_name, child_age: form.child_age || undefined, hp,
    })});
    const d = await res.json().catch(() => ({}));
    setLoading(false);
    if (!res.ok) { setError(d.error || "Could not start enrollment."); return; }
    setEnrollmentId(d.enrollment_id);
    if (d.amount_due) setAmountDue(d.amount_due);
    if (d.dev_code) setDevCode(d.dev_code); // shown only while email delivery is off
    setStep("otp");
  };

  const submitOtp = async (e) => {
    e.preventDefault(); setError("");
    if (code.trim().length !== 6) { setError("Enter the 6-digit code."); return; }
    setLoading(true);
    const res = await apiFetch("/enroll/verify-otp", { method: "POST", body: JSON.stringify({ enrollment_id: enrollmentId, code: code.trim() })});
    const d = await res.json().catch(() => ({}));
    setLoading(false);
    if (!res.ok) { setError(d.error || "Invalid code."); return; }
    setStep("pay");
  };

  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 startPayment = async () => {
    setError(""); setLoading(true);
    const res = await apiFetch("/enroll/create-order", { method: "POST", body: JSON.stringify({ enrollment_id: enrollmentId })});
    const d = await res.json().catch(() => ({}));
    if (!res.ok) { setLoading(false); setError(d.error || "Could not start payment."); return; }

    if (!d.razorpay) {
      // Inactive gateway: enrollment captured; team follows up to collect payment.
      setLoading(false);
      setPayMsg(d.message || "Our team will reach out to complete your enrollment.");
      setStep("done");
      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); setPayMsg("Payment cancelled — you can try again."); } },
      handler: async (resp) => {
        setPayMsg("Confirming payment…");
        const c = await apiFetch("/enroll/confirm", { method: "POST", body: JSON.stringify({
          enrollment_id: enrollmentId,
          razorpay_order_id: resp.razorpay_order_id,
          razorpay_payment_id: resp.razorpay_payment_id,
          razorpay_signature: resp.razorpay_signature,
        })});
        setLoading(false);
        if (c.ok) { setPayMsg("Payment received! Check your email for your login."); setStep("done"); }
        else { const e = await c.json().catch(() => ({})); setError(e.error || "Payment verification failed. If you were charged, contact support."); }
      },
    });
    rzp.open();
  };

  return (
    <AuthShell tagline="Enroll your child.">
      {/* Plan banner */}
      <div style={{ background: "var(--paper-deep)", border: "var(--border-thin)", borderRadius: 12, padding: "14px 16px", marginBottom: 20 }}>
        <div className="mono" style={{ fontSize: 11, fontWeight: 700, color: "var(--coral)", letterSpacing: ".06em" }}>{plan.label.toUpperCase()}</div>
        <div style={{ fontSize: 13, color: "var(--ink-soft)", marginTop: 4 }}>{plan.blurb}</div>
      </div>

      {step === "register" && (
        <>
          <h1 className="display" style={{ fontSize: 30, margin: "0 0 6px", letterSpacing: "-0.03em" }}>Create your spot</h1>
          <p style={{ fontSize: 13.5, color: "var(--ink-soft)", marginBottom: 18 }}>We'll verify your email, then take payment. Your login is emailed right after.</p>
          <form onSubmit={submitRegister}>
            <Field label="Your name *" value={form.parent_name} onChange={e => setForm(f => ({ ...f, parent_name: e.target.value }))} placeholder="Parent / guardian name" required/>
            <Field label="Email *" type="email" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} placeholder="you@example.com" autoComplete="email" required/>
            <Field label="Phone / WhatsApp" type="tel" value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} placeholder="+1 555 123 4567"/>
            <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 12 }}>
              <Field label="Child's name *" value={form.child_name} onChange={e => setForm(f => ({ ...f, child_name: e.target.value }))} placeholder="e.g. Maya" required/>
              <Field label="Age" type="number" min="2" max="18" value={form.child_age} onChange={e => setForm(f => ({ ...f, child_age: e.target.value }))} placeholder="9"/>
            </div>
            {/* Honeypot — hidden from humans */}
            <input value={hp} onChange={e => setHp(e.target.value)} tabIndex={-1} autoComplete="off" style={{ position: "absolute", left: "-9999px", width: 1, height: 1 }} aria-hidden="true"/>
            {error && <div style={{ background: "#fee2e2", color: "#b91c1c", borderRadius: 10, padding: "10px 14px", fontSize: 13, margin: "8px 0 14px" }}>{error}</div>}
            <button type="submit" disabled={loading} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", padding: "14px 22px", fontSize: 15, marginTop: 8, opacity: loading ? .6 : 1 }}>
              {loading ? "Sending code…" : "Continue →"}
            </button>
          </form>
        </>
      )}

      {step === "otp" && (
        <>
          <h1 className="display" style={{ fontSize: 30, margin: "0 0 6px", letterSpacing: "-0.03em" }}>Verify your email</h1>
          <p style={{ fontSize: 13.5, color: "var(--ink-soft)", marginBottom: 18 }}>We sent a 6-digit code to <strong>{form.email}</strong>.</p>
          {devCode && <div style={{ background: "#fffbeb", border: "1px solid #fde68a", borderRadius: 10, padding: "8px 12px", fontSize: 12.5, marginBottom: 14, color: "#92400e" }}>Email delivery is off in this environment — your code is <strong>{devCode}</strong>.</div>}
          <form onSubmit={submitOtp}>
            <Field label="6-digit code" value={code} onChange={e => setCode(e.target.value.replace(/\D/g, "").slice(0, 6))} placeholder="123456" inputMode="numeric" style={{ letterSpacing: "0.3em", fontSize: 20, textAlign: "center" }} required/>
            {error && <div style={{ background: "#fee2e2", color: "#b91c1c", borderRadius: 10, padding: "10px 14px", fontSize: 13, margin: "8px 0 14px" }}>{error}</div>}
            <button type="submit" disabled={loading} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", padding: "14px 22px", fontSize: 15, opacity: loading ? .6 : 1 }}>
              {loading ? "Verifying…" : "Verify →"}
            </button>
          </form>
        </>
      )}

      {step === "pay" && (
        <>
          <h1 className="display" style={{ fontSize: 30, margin: "0 0 6px", letterSpacing: "-0.03em" }}>Payment</h1>
          <p style={{ fontSize: 13.5, color: "var(--ink-soft)", marginBottom: 18 }}>Amount due now: <strong>${amountDue}</strong>{planKey === "monthly" ? " (month 1 of 3)" : ""}.</p>
          {payMsg && <div style={{ fontSize: 13, color: "var(--ink-soft)", marginBottom: 14 }}>{payMsg}</div>}
          {error && <div style={{ background: "#fee2e2", color: "#b91c1c", borderRadius: 10, padding: "10px 14px", fontSize: 13, margin: "8px 0 14px" }}>{error}</div>}
          <button onClick={startPayment} disabled={loading} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", padding: "14px 22px", fontSize: 15, opacity: loading ? .6 : 1 }}>
            {loading ? "Please wait…" : `Pay $${amountDue} →`}
          </button>
        </>
      )}

      {step === "done" && (
        <>
          <h1 className="display" style={{ fontSize: 30, margin: "0 0 6px", letterSpacing: "-0.03em" }}>You're all set 🎉</h1>
          <p style={{ fontSize: 14, color: "var(--ink-soft)", marginBottom: 18 }}>{payMsg || "Check your email for your login details."}</p>
          <button onClick={() => go("/login")} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", padding: "14px 22px", fontSize: 15 }}>Go to sign in →</button>
        </>
      )}
    </AuthShell>
  );
};

window.EnrollScreen = EnrollScreen;
