/* global React, useRoute, useToast, I */
const { useState: useMemState } = React;

/* ─────────────────────────────────────────────────────────────────
   Membership — three tiers, billed monthly via Stripe.
   Tier keys map server-side to STRIPE_PRICE_ATELIER /
   STRIPE_PRICE_SIGNATURE.  Founders is invite-only; submits a
   booking-style inquiry through /api/booking instead of Stripe.
   ───────────────────────────────────────────────────────────────── */
const TIERS = [
  {
    key: "atelier",
    name: "Atelier",
    price: 49,
    cadence: "month",
    tagline: "The studio's working tier.",
    blurb: "Member rates on the panel · loyalty credits on every order · saved profiles · one-tap reorder.",
    benefits: [
      "Member pricing on every panel service",
      "5% loyalty credit per order, redeemable any time",
      "Up to 3 saved profiles for one-tap apply",
      "Priority support — under 1 working day",
    ],
    cta: "Join Atelier",
  },
  {
    key: "signature",
    name: "Signature",
    price: 199,
    cadence: "month",
    tagline: "For artists running a campaign.",
    blurb: "Atelier plus monthly concierge call · campaign planning · industry-tier credit · 10% loyalty.",
    benefits: [
      "Everything in Atelier",
      "10% loyalty credit per order",
      "Up to 10 saved profiles",
      "Monthly 30-min concierge call",
      "$200 / mo industry-tier credit (playlist · press · sync)",
      "Priority queue on growth deliveries",
    ],
    cta: "Join Signature",
    popular: true,
  },
  {
    key: "founders",
    name: "Founders",
    price: 0,
    cadence: "invite",
    tagline: "Closed circle.",
    blurb: "Invite-only. Reserved for the studio's earliest clients and partners.",
    benefits: [
      "All Signature benefits",
      "20% loyalty credit per order",
      "Unlimited saved profiles",
      "Direct Slack channel with the studio",
      "Concierge campaign design at no charge",
    ],
    cta: "Request invite",
    invite: true,
  },
];

function Membership() {
  const { goto } = useRoute();
  const toast = useToast();
  const [busy, setBusy] = useMemState(null);
  const [email, setEmail] = useMemState("");

  async function startSubscription(tierKey) {
    if (!email || !email.includes("@")) { toast("Enter your email first."); return; }
    if (busy) return;
    setBusy(tierKey);
    try {
      const r = await fetch("/api/membership", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ tier: tierKey, email }),
      });
      const data = await r.json();
      if (data.url) { window.location.assign(data.url); return; }
      throw new Error(data.error || "subscription_failed");
    } catch (err) {
      toast("Couldn't start subscription. Email studio@elevenviews.io.");
    } finally {
      setBusy(null);
    }
  }

  function requestInvite(tierKey) {
    if (!email || !email.includes("@")) { toast("Enter your email and we'll write back."); return; }
    fetch("/api/booking", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        service: "membership",
        tier: tierKey,
        contact: { first: "Membership inquiry", last: "", email, phone: "", company: "", source: "Founders tier request" },
        brief: { title: "Founders membership invite request", budget: "—", timeline: "—", brief: `Requesting invite to the Founders tier. Email: ${email}` },
      }),
    })
      .then(() => toast("Sent. We'll write back within a working day."))
      .catch(() => toast("Send failed — email studio@elevenviews.io."));
  }

  return (
    <main className="fade">
      <section className="container" style={{ paddingTop: 84, paddingBottom: 48 }}>
        <span className="eyebrow eyebrow-gold">§ Membership</span>
        <h1 className="serif balance" style={{ fontSize: "clamp(48px, 7vw, 96px)", lineHeight: 0.96, letterSpacing: "-0.02em", margin: "16px 0 22px", maxWidth: 1100 }}>
          Three doors.<br/><em style={{ fontStyle: "italic", color: "var(--gold-soft)" }}>One panel.</em>
        </h1>
        <p className="pretty" style={{ color: "var(--text-1)", fontSize: 16, lineHeight: 1.65, maxWidth: 640, margin: "0 0 32px" }}>
          Pick a tier. Billed monthly via Stripe — cancel anytime in your portal. Every paid order earns loyalty credits you can spend on any future order.
        </p>
        <div style={{ display: "flex", gap: 10, alignItems: "center", maxWidth: 480, flexWrap: "wrap" }}>
          <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@studio.example" className="input" style={{ flex: 1, minWidth: 240, fontSize: 14 }} />
          <span className="mono" style={{ fontSize: 11, color: "var(--text-3)", letterSpacing: "0.1em", textTransform: "uppercase" }}>then pick a tier ↓</span>
        </div>
      </section>

      <hr className="rule" />

      <section className="container" style={{ paddingTop: 64, paddingBottom: 96 }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 18 }}>
          {TIERS.map((t) => (
            <article key={t.key} style={{
              background: "#0c0c0c",
              border: `1px solid ${t.popular ? "var(--gold)" : "var(--border)"}`,
              borderRadius: 14, padding: 28,
              display: "flex", flexDirection: "column", gap: 16,
              boxShadow: t.popular ? "0 0 40px rgba(255,204,83,0.05)" : "none",
            }}>
              {t.popular && <span className="num" style={{ background: "var(--gold)", color: "#000", padding: "4px 8px", borderRadius: 3, fontWeight: 600, alignSelf: "start" }}>Most chosen</span>}
              {t.invite && <span className="num" style={{ background: "transparent", color: "var(--gold)", padding: "4px 8px", borderRadius: 3, border: "1px solid var(--gold)", alignSelf: "start" }}>Invite only</span>}
              <div>
                <div className="serif" style={{ fontSize: 36, lineHeight: 1, margin: 0 }}>{t.name}</div>
                <p className="serif-it" style={{ fontSize: 17, color: "var(--text-1)", lineHeight: 1.4, margin: "8px 0 0" }}>{t.tagline}</p>
              </div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                {t.price > 0 ? (
                  <>
                    <span className="serif" style={{ fontSize: 56, color: "var(--gold)", fontStyle: "italic", lineHeight: 1, fontWeight: 300 }}>${t.price}</span>
                    <span className="mono" style={{ fontSize: 11, color: "var(--text-3)", letterSpacing: "0.16em", textTransform: "uppercase" }}>/ {t.cadence}</span>
                  </>
                ) : (
                  <span className="mono" style={{ fontSize: 14, color: "var(--gold)", letterSpacing: "0.18em", textTransform: "uppercase" }}>By invite</span>
                )}
              </div>
              <p style={{ fontSize: 14, color: "var(--text-2)", lineHeight: 1.6, margin: 0 }}>{t.blurb}</p>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 10, paddingTop: 12, borderTop: "1px solid var(--border-1)" }}>
                {t.benefits.map((b) => (
                  <li key={b} style={{ fontSize: 13.5, color: "var(--text-1)", display: "flex", gap: 10, lineHeight: 1.5 }}>
                    <I name="check" size={14} stroke="var(--gold)" /> {b}
                  </li>
                ))}
              </ul>
              <button
                className="btn btn-gold btn-lg"
                style={{ marginTop: "auto", opacity: busy === t.key ? 0.5 : 1 }}
                disabled={busy === t.key}
                onClick={() => t.invite ? requestInvite(t.key) : startSubscription(t.key)}
              >
                {busy === t.key ? "Opening…" : t.cta} <I name="arrow" size={14} />
              </button>
            </article>
          ))}
        </div>
      </section>

      <hr className="rule" />

      <section className="container" style={{ paddingTop: 64, paddingBottom: 96, textAlign: "center", maxWidth: 760, margin: "0 auto" }}>
        <I name="spark" size={20} stroke="var(--gold)" style={{ marginBottom: 18 }} />
        <p className="serif balance" style={{ fontSize: "clamp(22px, 2.6vw, 32px)", lineHeight: 1.3, fontStyle: "italic", margin: 0 }}>
          Cancel anytime in the portal. Loyalty credits never expire. The studio reads every membership inquiry by hand.
        </p>
        <div style={{ marginTop: 28, display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap" }}>
          <button className="btn btn-line" onClick={() => goto("panel")}>Open the panel <I name="arrow" size={14} /></button>
          <button className="btn btn-ghost" onClick={() => goto("contact")}>Talk to the studio</button>
        </div>
      </section>
    </main>
  );
}

window.Membership = Membership;
window.MEMBERSHIP_TIERS = TIERS;
