// Join page — three membership tiers + optional referral code.
// Referral codes credit the REFERRER (Ambassador members earn $10 per signed
// referral); they do not change the new member's price. A valid code is logged
// via /api/redeem before redirecting to the chosen tier's Elation enrollment URL.
// Tier enrollment URLs come from content.json membership.tiers[].enrollUrl.
// UI strings run through t() (EN/ES); tier content localizes via content.es.

function JoinPage({ onBack, initialTier }) {
  const c = window.RECOVERY_CONTENT || {};
  const m = c.membership || {};
  const tiers = (Array.isArray(m.tiers) && m.tiers.length) ? m.tiers : null;
  const legacyUrl = m.enrollUrl || "";
  const isMobile = useIsMobile();

  const [selected, setSelected] = React.useState(
    tiers ? (initialTier && tiers.some((tr) => tr.id === initialTier) ? initialTier : null) : "legacy"
  );
  const [code, setCode] = React.useState("");
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [state, setState] = React.useState("idle"); // idle | checking | valid | invalid | error
  const [referrer, setReferrer] = React.useState("");

  const selectedTier = tiers ? tiers.find((tr) => tr.id === selected) : null;
  const enrollTarget = selectedTier ? (selectedTier.enrollUrl || "") : legacyUrl;

  const checkCode = async () => {
    const trimmed = code.trim();
    if (!trimmed) return;
    setState("checking");
    try {
      const r = await fetch(`/api/validate?code=${encodeURIComponent(trimmed)}`);
      const data = await r.json();
      if (data.valid) {
        setReferrer(data.referrerFirstName || "");
        setState("valid");
      } else {
        setState("invalid");
      }
    } catch (e) {
      setState("error");
    }
  };

  const goEnroll = async () => {
    if (!enrollTarget) return;
    if (state === "valid") {
      try {
        await fetch("/api/redeem", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            code: code.trim(),
            name: name.trim(),
            email: email.trim(),
            tier: selectedTier ? selectedTier.id : "legacy",
          }),
        });
      } catch (e) { /* logging failure shouldn't block enrollment */ }
    }
    window.location.href = enrollTarget;
  };

  return (
    <div style={{ minHeight: "100vh", background: "var(--paper)", display: "flex", flexDirection: "column" }}>
      <nav className="nav">
        <div className="nav-inner">
          <a href="#" onClick={(e) => { e.preventDefault(); onBack?.(); }}><Logo /></a>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <LangToggle />
            <a href="#" onClick={(e) => { e.preventDefault(); onBack?.(); }} style={{ fontSize: 13, fontWeight: 600, color: "var(--cream-300)" }}>{t("← Back to site")}</a>
          </div>
        </div>
      </nav>
      <div style={{ flex: 1, padding: "48px 20px 80px" }}>
        <div style={{ maxWidth: 1080, margin: "0 auto" }}>
          <div style={{ textAlign: "center", marginBottom: 36 }}>
            <div className="eyebrow" style={{ marginBottom: 12 }}>{t("Membership")}</div>
            <h1 className="display" style={{ fontSize: isMobile ? 28 : 36, margin: "0 0 12px" }}>{t("Choose your membership")}</h1>
            <p style={{ color: "var(--cream-300)", fontSize: 15, lineHeight: 1.65, maxWidth: 620, margin: "0 auto" }}>
              {m.blurb || ""}
            </p>
          </div>

          {tiers && (
            <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "repeat(3, 1fr)", gap: isMobile ? 14 : 22, marginBottom: 36 }}>
              {tiers.map((tr) => {
                const active = selected === tr.id;
                return (
                  <div
                    key={tr.id}
                    onClick={() => setSelected(tr.id)}
                    style={{
                      background: "#ffffff",
                      border: active ? "2px solid var(--gold-500)" : "1px solid var(--line)",
                      borderRadius: 14,
                      padding: "28px 24px",
                      cursor: "pointer",
                      position: "relative",
                      boxShadow: active ? "var(--shadow-card-hover)" : "var(--shadow-card)",
                      transition: "box-shadow 150ms, border-color 150ms",
                    }}
                  >
                    {tr.tag && (
                      <span style={{ position: "absolute", top: -11, left: 24, background: "var(--gold-500)", color: "#fff", fontSize: 10, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", padding: "3px 10px", borderRadius: 999 }}>{tr.tag}</span>
                    )}
                    <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
                      <span style={{
                        width: 20, height: 20, borderRadius: "50%", flexShrink: 0,
                        border: active ? "6px solid var(--gold-500)" : "2px solid var(--line-strong)",
                        background: "#fff", boxSizing: "border-box",
                      }}></span>
                      <h2 className="display" style={{ fontSize: 17, margin: 0 }}>{tr.name}</h2>
                    </div>
                    <div className="display" style={{ fontSize: 15, color: "var(--gold-600)", marginBottom: 14 }}>{tr.priceLine}</div>
                    <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 8 }}>
                      {(tr.perks || []).map((p) => (
                        <li key={p} style={{ display: "flex", alignItems: "flex-start", gap: 8, fontSize: 13, color: "var(--cream-200)", lineHeight: 1.5 }}>
                          <span style={{ color: "var(--gold-500)", marginTop: 2 }}><Check size={12} /></span>{p}
                        </li>
                      ))}
                    </ul>
                    {tr.note && <div style={{ marginTop: 12, fontSize: 12, color: "var(--cream-400)" }}>{tr.note}</div>}
                  </div>
                );
              })}
            </div>
          )}

          <div style={{ background: "#ffffff", border: "1px solid var(--line)", borderRadius: 16, boxShadow: "var(--shadow-card)", padding: isMobile ? "28px 20px" : "36px 40px", maxWidth: 640, margin: "0 auto" }}>
            <label className="label-sm" style={{ display: "block", marginBottom: 8 }}>{t("Referral code (optional)")}</label>
            <p style={{ fontSize: 13, color: "var(--cream-400)", margin: "0 0 12px", lineHeight: 1.6 }}>
              {t("Were you referred by a GTX member? Enter their code so they receive credit.")}
            </p>
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              <input
                className="input"
                style={{ flex: 1, minWidth: 180, textTransform: "uppercase" }}
                placeholder="GTX-XXXX"
                value={code}
                onChange={(e) => { setCode(e.target.value); setState("idle"); }}
                onKeyDown={(e) => { if (e.key === "Enter") checkCode(); }}
              />
              <button className="btn btn-ghost" onClick={checkCode} disabled={state === "checking"}>
                {state === "checking" ? t("Checking…") : t("Apply")}
              </button>
            </div>

            {state === "valid" && (
              <div style={{ marginTop: 14, padding: "12px 16px", borderRadius: 10, background: "rgba(46,158,107,0.09)", border: "1px solid rgba(46,158,107,0.35)", color: "var(--success)", fontSize: 14, fontWeight: 600 }}>
                {referrer
                  ? t("✓ Code accepted — {name} will receive referral credit.").replace("{name}", referrer)
                  : t("✓ Code accepted — your referrer will receive credit.")}
              </div>
            )}
            {state === "invalid" && (
              <div style={{ marginTop: 14, padding: "12px 16px", borderRadius: 10, background: "rgba(196,87,74,0.08)", border: "1px solid rgba(196,87,74,0.35)", color: "var(--danger)", fontSize: 14 }}>
                {t("That code was not recognized. Check the spelling, or continue without one.")}
              </div>
            )}
            {state === "error" && (
              <div style={{ marginTop: 14, padding: "12px 16px", borderRadius: 10, background: "var(--paper)", border: "1px solid var(--line-strong)", color: "var(--cream-300)", fontSize: 14 }}>
                {t("We couldn't verify the code right now. You can continue without it, or try again in a moment.")}
              </div>
            )}

            {state === "valid" && (
              <div style={{ marginTop: 18, display: "grid", gap: 12 }}>
                <div>
                  <label className="label-sm" style={{ display: "block", marginBottom: 6 }}>{t("Your name")}</label>
                  <input className="input" placeholder={t("First and last name")} value={name} onChange={(e) => setName(e.target.value)} />
                </div>
                <div>
                  <label className="label-sm" style={{ display: "block", marginBottom: 6 }}>{t("Email")}</label>
                  <input className="input" type="email" placeholder={window.SITE_LANG === "es" ? "usted@ejemplo.com" : "you@example.com"} value={email} onChange={(e) => setEmail(e.target.value)} />
                </div>
              </div>
            )}

            <div style={{ marginTop: 26, display: "flex", flexDirection: "column", gap: 12 }}>
              {tiers && !selectedTier && (
                <p style={{ fontSize: 13, color: "var(--cream-400)", textAlign: "center", margin: 0 }}>{t("Select a membership above to continue.")}</p>
              )}
              {selectedTier && !enrollTarget && (
                <p style={{ fontSize: 13, color: "var(--danger)", textAlign: "center", margin: 0 }}>
                  {t("Online enrollment for this plan is opening soon — call {phone} to join today.").replace("{phone}", (c.contact && c.contact.officePhone) || "the office")}
                </p>
              )}
              <button
                className="btn btn-primary btn-lg"
                style={{ width: "100%" }}
                onClick={goEnroll}
                disabled={!enrollTarget || (state === "valid" && !name.trim())}
              >
                {t("Continue to enrollment")} <ArrowRight />
              </button>
              <p style={{ fontSize: 12, color: "var(--cream-400)", textAlign: "center", margin: 0, lineHeight: 1.6 }}>
                {m.enrollDisclosure || t("Enrollment and payment are handled securely by Elation Health, our HIPAA-compliant patient platform.")}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { JoinPage });
