// Temporary registration page — opened from a lead's invite link /#/register/<token>.
// Collects a partial profile (student + parent), saves it onto the inquiry, then
// hands off to the Razorpay-hosted payment link. On payment, the server webhook
// provisions the account and emails credentials; this page polls until paid.
const RegisterScreen = ({ go }) => {
  const token = window.location.hash.replace(/^#?\/register\//, "").split("?")[0];
  const [info, setInfo] = React.useState(null);
  const [form, setForm] = React.useState(null);
  const [error, setError] = React.useState("");
  const [saving, setSaving] = React.useState(false);
  const [msg, setMsg] = React.useState("");
  const [paid, setPaid] = React.useState(false);
  const [awaiting, setAwaiting] = React.useState(false);
  const [showFeedback, setShowFeedback] = React.useState(false);
  const [feedback, setFeedback] = React.useState("");
  const [feedbackSent, setFeedbackSent] = React.useState(false);
  const pollRef = React.useRef(null);

  const sym = (c) => (c === "INR" ? "₹" : c === "USD" ? "$" : "");

  const apply = (d) => {
    setInfo(d);
    setForm({
      student_name: d.child_name || "",
      child_age: d.child_age || "",
      student_username: d.student_username || "",
      student_email: d.student_email || "",
      student_phone: d.student_phone || "",
      parent_name: d.parent_name || "",
      parent_email: d.parent_email || "",
      parent_phone: d.parent_phone || "",
    });
    if (d.paid) setPaid(true);
  };

  const fetchInfo = React.useCallback(() =>
    apiFetch(`/register/${encodeURIComponent(token)}`)
      .then((r) => r.json().then((d) => ({ ok: r.ok, d })))
  , [token]);

  React.useEffect(() => {
    fetchInfo()
      .then(({ ok, d }) => { if (!ok) { setError(d.error || "Invalid registration link."); return; } apply(d); })
      .catch(() => setError("Could not load this registration."));
    return () => pollRef.current && clearInterval(pollRef.current);
  }, [fetchInfo]);

  // While awaiting payment, poll for the webhook to mark the lead paid.
  React.useEffect(() => {
    if (!awaiting || paid) return;
    pollRef.current = setInterval(async () => {
      try {
        const { ok, d } = await fetchInfo();
        if (ok && d.paid) { setPaid(true); setAwaiting(false); clearInterval(pollRef.current); }
      } catch (_) {}
    }, 5000);
    return () => clearInterval(pollRef.current);
  }, [awaiting, paid, fetchInfo]);

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const saveAndPay = async () => {
    setError(""); setMsg(""); setSaving(true);
    if (!form.student_name.trim()) { setSaving(false); setError("Please enter the student's name."); return; }
    const res = await apiFetch(`/register/${encodeURIComponent(token)}`, {
      method: "POST",
      body: JSON.stringify({
        student_name: form.student_name,
        child_age: form.child_age === "" ? undefined : Number(form.child_age),
        student_username: form.student_username ? form.student_username.trim().toLowerCase() : undefined,
        student_email: form.student_email || undefined,
        student_phone: form.student_phone || undefined,
        parent_name: form.parent_name || undefined,
        parent_email: form.parent_email || undefined,
        parent_phone: form.parent_phone || undefined,
      }),
    });
    const d = await res.json().catch(() => ({}));
    setSaving(false);
    if (!res.ok) { setError(d.error || "Could not save your details."); return; }
    const url = d.payment_link_url || (info && info.payment_link_url);
    if (!url) { setMsg("Your details are saved. Our team will share the payment link shortly."); return; }
    window.open(url, "_blank", "noopener");
    setAwaiting(true);
    setMsg("Complete the payment in the new tab. This page updates automatically once it's confirmed.");
  };

  const sendFeedback = async () => {
    if (!feedback.trim()) return;
    await apiFetch(`/register/${encodeURIComponent(token)}/feedback`, { method: "POST", body: JSON.stringify({ feedback }) }).catch(() => {});
    setFeedbackSent(true);
  };

  const labelStyle = { fontSize: 11, fontWeight: 700, color: "var(--ink-mute)", letterSpacing: ".04em", margin: "0 0 4px" };
  const field = { width: "100%", padding: "10px 12px", borderRadius: 8, border: "1px solid var(--border-color,#e5e7eb)", fontSize: 14, boxSizing: "border-box" };

  return (
    <AuthShell tagline="Finish enrolling.">
      {error && <div style={{ background: "#fee2e2", color: "#b91c1c", borderRadius: 10, padding: "12px 16px", fontSize: 14, marginBottom: 14 }}>{error}</div>}
      {!error && !info && <div style={{ padding: 20, color: "var(--ink-mute)" }}>Loading…</div>}

      {!error && paid && (
        <>
          <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! Check your email for your login details — you'll set your own password on first sign-in.</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 && !paid && (
        <>
          <h1 className="display" style={{ fontSize: 28, margin: "0 0 4px", letterSpacing: "-0.03em" }}>Complete your registration</h1>
          {info.amount != null && (
            <p style={{ fontSize: 14, color: "var(--ink-soft)", marginBottom: 16 }}>
              {info.plan_label ? `${info.plan_label} — ` : ""}amount: <strong>{sym(info.currency)}{Number(info.amount).toLocaleString()}</strong>
            </p>
          )}

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 8 }}>
            <div style={{ gridColumn: "1 / -1" }}><div style={labelStyle}>STUDENT NAME *</div><input style={field} value={form.student_name} onChange={set("student_name")} placeholder="Student's full name" /></div>
            <div style={{ gridColumn: "1 / -1" }}><div style={labelStyle}>STUDENT USERNAME (for child login)</div><input style={field} value={form.student_username} onChange={set("student_username")} placeholder="e.g. arjun_codes — letters, numbers, . _ -" autoCapitalize="none" /><div style={{ fontSize: 11, color: "var(--ink-mute)", marginTop: 3 }}>Your child signs in with this username (or email). Leave blank and we'll create one.</div></div>
            <div><div style={labelStyle}>STUDENT AGE</div><input style={field} type="number" min="2" max="100" value={form.child_age} onChange={set("child_age")} placeholder="e.g. 10" /></div>
            <div><div style={labelStyle}>STUDENT PHONE</div><input style={field} value={form.student_phone} onChange={set("student_phone")} placeholder="Optional" /></div>
            <div style={{ gridColumn: "1 / -1" }}><div style={labelStyle}>STUDENT EMAIL</div><input style={field} type="email" value={form.student_email} onChange={set("student_email")} placeholder="Optional — we'll create one if blank" /></div>
            <div style={{ gridColumn: "1 / -1" }}><div style={labelStyle}>PARENT/GUARDIAN NAME</div><input style={field} value={form.parent_name} onChange={set("parent_name")} placeholder="Parent's full name" /></div>
            <div><div style={labelStyle}>PARENT EMAIL</div><input style={field} type="email" value={form.parent_email} onChange={set("parent_email")} placeholder="Login will be sent here" /></div>
            <div><div style={labelStyle}>PARENT PHONE</div><input style={field} value={form.parent_phone} onChange={set("parent_phone")} placeholder="Optional" /></div>
          </div>

          {msg && <div style={{ fontSize: 13, color: "var(--ink-soft)", margin: "10px 0", background: "var(--paper-deep,#f9fafb)", borderRadius: 8, padding: "10px 12px" }}>{msg}</div>}

          {!awaiting ? (
            <button onClick={saveAndPay} disabled={saving} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", padding: "14px 22px", fontSize: 15, marginTop: 8, opacity: saving ? .6 : 1 }}>
              {saving ? "Saving…" : info.amount != null ? `Save & pay ${sym(info.currency)}${Number(info.amount).toLocaleString()} →` : "Save & continue →"}
            </button>
          ) : (
            <>
              <button onClick={saveAndPay} disabled={saving} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", padding: "12px 20px", fontSize: 14, marginTop: 8 }}>
                Reopen payment ↗
              </button>
              <div style={{ textAlign: "center", marginTop: 12 }}>
                <button onClick={() => setShowFeedback((v) => !v)} style={{ background: "none", border: "none", color: "var(--ink-mute)", fontSize: 12, textDecoration: "underline", cursor: "pointer" }}>
                  Having trouble paying? Tell us
                </button>
              </div>
            </>
          )}

          {showFeedback && !feedbackSent && (
            <div style={{ marginTop: 12 }}>
              <textarea rows={3} style={{ ...field, resize: "vertical" }} value={feedback} onChange={(e) => setFeedback(e.target.value)} placeholder="What went wrong? We'll reach out to help." />
              <button onClick={sendFeedback} className="btn btn-ghost" style={{ marginTop: 8, padding: "8px 16px", fontSize: 13 }}>Send feedback</button>
            </div>
          )}
          {feedbackSent && <div style={{ marginTop: 12, fontSize: 13, color: "var(--moss,#16a34a)" }}>Thanks — our team will be in touch.</div>}
        </>
      )}
    </AuthShell>
  );
};

window.RegisterScreen = RegisterScreen;
