const { useState: useStateSU, useEffect: useEffectSU } = React;

const ASSISTANTS = [
  { key: "Designer",   tagline: "Flyers, brochures, postcards, menus." },
  { key: "Writer",     tagline: "Letters, blog posts, invitations." },
  { key: "Builder",    tagline: "Websites and landing pages." },
  { key: "Social",     tagline: "Multi-platform post sets." },
  { key: "Researcher", tagline: "Briefs, data summaries, donor research." },
];

const MONTHLY_CENTS = 1200;
const GUARANTEE_DAYS = 30;
const STORAGE_KEY = "so_signup_v2";

const dollars = (cents) => `$${(cents / 100).toFixed(0)}`;

function guaranteeEndLabel() {
  const d = new Date(Date.now() + GUARANTEE_DAYS * 86400000);
  return d.toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" });
}

function loadDraft() {
  try { return JSON.parse(sessionStorage.getItem(STORAGE_KEY) || "null"); } catch (_) { return null; }
}
function saveDraft(d) {
  try { sessionStorage.setItem(STORAGE_KEY, JSON.stringify(d)); } catch (_) {}
}
function clearDraft() {
  try { sessionStorage.removeItem(STORAGE_KEY); } catch (_) {}
}

function SignupPage({ setRoute, canceled }) {
  const draft = loadDraft();
  const [step, setStep] = useStateSU(draft?.step ?? 0);
  const [data, setData] = useStateSU(draft?.data ?? {
    orgName: "", userName: "", email: "", isNonprofit: false,
    agreeBilling: false, agreeTerms: false,
  });
  const [errors, setErrors] = useStateSU({});
  const [submitting, setSubmitting] = useStateSU(false);
  const [submitError, setSubmitError] = useStateSU(canceled ? "Payment canceled — your details are saved. Continue when ready." : "");

  useEffectSU(() => { window.scrollTo({ top: 0 }); }, [step]);
  useEffectSU(() => { saveDraft({ step, data }); }, [step, data]);

  const update = (k, v) => setData(d => ({ ...d, [k]: v }));

  const validate = (s) => {
    const e = {};
    if (s === 0) {
      if (!data.orgName.trim()) e.orgName = "Required";
      if (!data.userName.trim()) e.userName = "Required";
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) e.email = "Valid email required";
    }
    if (s === 1) {
      if (!data.agreeBilling) e.agreeBilling = "Required";
      if (!data.agreeTerms) e.agreeTerms = "Required";
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = () => { if (validate(step)) setStep(s => s + 1); };
  const back = () => setStep(s => Math.max(0, s - 1));

  const submit = async () => {
    if (!validate(1)) return;
    setSubmitting(true);
    setSubmitError("");
    try {
      const res = await fetch("/api/checkout-session", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          orgName: data.orgName.trim(),
          userName: data.userName.trim(),
          email: data.email.trim(),
          isNonprofit: !!data.isNonprofit,
        }),
      });
      const body = await res.json().catch(() => ({}));
      if (!res.ok || !body.url) {
        throw new Error(body.error || `Checkout failed (${res.status}).`);
      }
      window.location = body.url;
    } catch (err) {
      setSubmitting(false);
      setSubmitError(err.message || "Could not start checkout. Try again.");
    }
  };

  const sections = [
    { title: "About you",            n: "01" },
    { title: "Review & subscribe",   n: "02" },
  ];

  return (
    <div style={{ background: "var(--cream)", minHeight: "100vh" }}>
      <div style={{
        borderBottom: "1px solid var(--rule)",
        background: "rgba(244,239,230,0.92)",
        backdropFilter: "saturate(1.1) blur(8px)",
        WebkitBackdropFilter: "saturate(1.1) blur(8px)",
        position: "sticky", top: 0, zIndex: 50,
      }}>
        <div style={{ maxWidth: 1280, margin: "0 auto", padding: "18px 40px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 20, flexWrap: "wrap" }}>
          <button onClick={() => setRoute("home")} style={{ background: "none", border: "none", cursor: "pointer", padding: 0, fontFamily: "inherit" }}>
            <Wordmark size={20} />
          </button>
          <div className="mono" style={{ color: "var(--ink-3)" }}>
            Sign up · Step {step + 1} of 2
          </div>
        </div>
      </div>

      <div style={{ maxWidth: 1040, margin: "0 auto", padding: "80px 40px 120px" }}>
        <div className="apply-head" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 80, alignItems: "end", marginBottom: 64 }}>
          <div>
            <div className="mono" style={{ color: "var(--ink-3)", marginBottom: 28 }}>
              <span style={{ display: "inline-block", width: 28, height: 1, background: "currentColor", verticalAlign: "middle", marginRight: 10 }} />
              /signup
            </div>
            <h1 style={{ fontSize: "clamp(44px, 6vw, 76px)", lineHeight: 1.0, letterSpacing: "-0.025em", marginBottom: 0 }}>
              Subscribe <span className="serif-italic" style={{ color: "var(--sun-deep)" }}>today.</span>
            </h1>
          </div>
          <p style={{ color: "var(--ink-2)", fontSize: 17, lineHeight: 1.55, maxWidth: 380 }}>
            Two minutes to subscribe. $12 today, then $12 a month — full refund any time in the first 30 days, no questions asked.
          </p>
        </div>

        {submitError && (
          <div style={{
            background: "var(--paper)", borderLeft: "3px solid var(--sun-deep)",
            padding: "14px 18px", marginBottom: 32, fontSize: 15, color: "var(--ink-2)",
          }}>{submitError}</div>
        )}

        <div className="apply-body" style={{ display: "grid", gridTemplateColumns: "240px 1fr", gap: 64, alignItems: "start" }}>
          <aside className="apply-rail" style={{ position: "sticky", top: 120 }}>
            <div className="mono" style={{ color: "var(--ink-3)", marginBottom: 20 }}>Progress</div>
            <ol style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 2 }}>
              {sections.map((s, i) => {
                const done = i < step;
                const active = i === step;
                return (
                  <li key={s.n}>
                    <button
                      onClick={() => { if (i < step) setStep(i); }}
                      disabled={i > step}
                      style={{
                        display: "grid", gridTemplateColumns: "32px 1fr", gap: 10,
                        alignItems: "center", width: "100%",
                        padding: "14px 0", textAlign: "left",
                        background: "none", border: "none",
                        borderTop: "1px solid var(--rule)",
                        color: active ? "var(--ink)" : "var(--ink-3)",
                        cursor: i < step ? "pointer" : "default",
                        fontFamily: "inherit",
                      }}
                    >
                      <span style={{
                        width: 20, height: 20, borderRadius: "50%",
                        background: done ? "var(--orchard)" : active ? "var(--ink)" : "transparent",
                        border: done || active ? "none" : "1px solid var(--rule-2)",
                        color: "var(--cream)", fontSize: 10,
                        display: "flex", alignItems: "center", justifyContent: "center",
                        fontFamily: "'JetBrains Mono', monospace",
                      }}>
                        {done ? "✓" : active ? s.n.replace(/^0/,"") : ""}
                      </span>
                      <span style={{ fontSize: 14, letterSpacing: "-0.005em", fontWeight: active ? 500 : 400 }}>{s.title}</span>
                    </button>
                  </li>
                );
              })}
              <li style={{ borderTop: "1px solid var(--rule)", height: 0 }}/>
            </ol>

            <div style={{ marginTop: 32, padding: "18px 0", borderTop: "1px solid var(--rule)", borderBottom: "1px solid var(--rule)" }}>
              <div className="mono" style={{ color: "var(--ink-3)", marginBottom: 8 }}>Your plan</div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 4 }}>
                <span style={{ fontFamily: "'Newsreader', serif", fontSize: 36, color: "var(--bark)", letterSpacing: "-0.02em", lineHeight: 1 }}>
                  {dollars(MONTHLY_CENTS)}
                </span>
                <span className="serif-italic" style={{ color: "var(--ink-3)", fontSize: 14 }}>/ month</span>
              </div>
              <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4, fontFamily: "'Newsreader', serif", fontStyle: "italic" }}>
                All {ASSISTANTS.length} assistants · 30-day money-back
              </div>
            </div>
          </aside>

          <div style={{ maxWidth: 720 }}>
            {step === 0 && <StepDetails data={data} update={update} errors={errors} />}
            {step === 1 && <StepReview data={data} update={update} errors={errors} />}

            <div style={{ marginTop: 48, paddingTop: 32, borderTop: "1px solid var(--rule)", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
              {step > 0 ? (
                <button onClick={back} style={{ background: "none", border: "none", cursor: "pointer", fontSize: 14, color: "var(--ink-2)", padding: 0, fontFamily: "inherit" }}>← Back</button>
              ) : (
                <button onClick={() => { clearDraft(); setRoute("home"); }} style={{ background: "none", border: "none", cursor: "pointer", fontSize: 14, color: "var(--ink-3)", padding: 0, fontFamily: "inherit" }}>Cancel</button>
              )}
              {step < 1 ? (
                <Button onClick={next}>Continue →</Button>
              ) : (
                <Button onClick={submit} disabled={submitting}>
                  {submitting ? "Redirecting to Stripe…" : "Continue to secure checkout →"}
                </Button>
              )}
            </div>
            {step === 1 && (
              <p style={{ marginTop: 18, fontSize: 13, color: "var(--ink-3)", fontFamily: "'Newsreader', serif", fontStyle: "italic" }}>
                You'll finish on Stripe's secure checkout page. We never see your card details.
              </p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function StepDetails({ data, update, errors }) {
  return (
    <div>
      <StepHeading n="01" title="About you" />
      <p style={{ fontSize: 16, color: "var(--ink-2)", lineHeight: 1.6, marginBottom: 32, maxWidth: 580 }}>
        Three quick fields. Your billing address is collected by Stripe on the next page.
      </p>
      <Field label="Organization name" required error={errors.orgName}>
        <TextInput value={data.orgName} onChange={v => update("orgName", v)} placeholder="Westside Community Center" error={errors.orgName}/>
      </Field>
      <div className="apply-2col" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
        <Field label="Your name" required error={errors.userName}>
          <TextInput value={data.userName} onChange={v => update("userName", v)} error={errors.userName} placeholder="Maria Alvarez"/>
        </Field>
        <Field label="Email" required error={errors.email}>
          <TextInput type="email" value={data.email} onChange={v => update("email", v)} error={errors.email} placeholder="maria@westsidecc.org"/>
        </Field>
      </div>
      <label style={{
        display: "grid", gridTemplateColumns: "20px 1fr", gap: 12,
        padding: "16px 16px",
        background: data.isNonprofit ? "var(--paper)" : "transparent",
        border: "1px solid var(--rule)",
        cursor: "pointer",
        fontSize: 14, color: "var(--ink-2)", lineHeight: 1.5,
      }}>
        <input type="checkbox" checked={data.isNonprofit} onChange={e => update("isNonprofit", e.target.checked)}
          style={{ marginTop: 2, accentColor: "var(--orchard)", width: 16, height: 16 }}/>
        <div>
          <span style={{ color: "var(--ink)", fontWeight: 500 }}>We're a registered 501(c)(3) nonprofit.</span>
          {" "}Optional. If checked, we'll reach out about tax-exempt billing options.
        </div>
      </label>
    </div>
  );
}

function StepReview({ data, update, errors }) {
  const guaranteeEnds = guaranteeEndLabel();
  return (
    <div>
      <StepHeading n="02" title="Review & subscribe" />
      <p style={{ fontSize: 16, color: "var(--ink-2)", lineHeight: 1.6, marginBottom: 32, maxWidth: 580 }}>
        One last look before you head to Stripe.
      </p>

      <div style={{ background: "var(--paper)", border: "1px solid var(--rule)", padding: "28px 28px 24px", marginBottom: 32 }}>
        <div className="mono" style={{ color: "var(--sun-deep)", marginBottom: 16 }}>Your subscription</div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginBottom: 8, flexWrap: "wrap" }}>
          <span style={{ fontFamily: "'Newsreader', serif", fontSize: 18, color: "var(--ink-2)" }}>$</span>
          <span style={{ fontFamily: "'Newsreader', serif", fontSize: 56, lineHeight: 0.9, letterSpacing: "-0.04em", color: "var(--bark)" }}>{(MONTHLY_CENTS / 100).toFixed(0)}</span>
          <span className="serif-italic" style={{ color: "var(--ink-3)", fontSize: 16, marginLeft: 4 }}>/ month</span>
          <span style={{ marginLeft: 12, fontSize: 12, padding: "3px 9px", background: "var(--sun)", color: "var(--bark)", fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.06em", textTransform: "uppercase" }}>30-day money-back</span>
        </div>
        <div style={{ fontSize: 14, color: "var(--ink-3)", marginTop: 6, fontFamily: "'Newsreader', serif", fontStyle: "italic" }}>
          Charged today. Full refund any time through {guaranteeEnds} — no questions asked.
        </div>

        <div style={{ marginTop: 22, paddingTop: 18, borderTop: "1px solid var(--rule)" }}>
          <div className="mono" style={{ color: "var(--ink-3)", marginBottom: 10 }}>What's included</div>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 8 }}>
            {ASSISTANTS.map(a => (
              <li key={a.key} style={{ display: "grid", gridTemplateColumns: "16px 1fr", gap: 10, fontSize: 14, color: "var(--ink-2)" }}>
                <svg width="12" height="12" viewBox="0 0 12 12" style={{ marginTop: 5 }}>
                  <circle cx="6" cy="6" r="4.5" fill="var(--sun)"/>
                  <circle cx="6" cy="6" r="4.5" fill="none" stroke="var(--bark)" strokeWidth="0.4" strokeDasharray="1 1.5"/>
                </svg>
                <span><span style={{ color: "var(--ink)", fontWeight: 500 }}>{a.key}</span> — {a.tagline}</span>
              </li>
            ))}
            <li style={{ display: "grid", gridTemplateColumns: "16px 1fr", gap: 10, fontSize: 14, color: "var(--ink-2)" }}>
              <svg width="12" height="12" viewBox="0 0 12 12" style={{ marginTop: 5 }}>
                <circle cx="6" cy="6" r="4.5" fill="var(--sun)"/>
                <circle cx="6" cy="6" r="4.5" fill="none" stroke="var(--bark)" strokeWidth="0.4" strokeDasharray="1 1.5"/>
              </svg>
              <span>Unlimited requests across every assistant.</span>
            </li>
          </ul>
        </div>
        <div style={{ marginTop: 22, paddingTop: 18, borderTop: "1px solid var(--rule)", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, fontSize: 14 }}>
          <div>
            <div className="mono" style={{ color: "var(--ink-3)", marginBottom: 4 }}>Organization</div>
            <div style={{ color: "var(--ink)" }}>{data.orgName}</div>
          </div>
          <div>
            <div className="mono" style={{ color: "var(--ink-3)", marginBottom: 4 }}>Email</div>
            <div style={{ color: "var(--ink)" }}>{data.email}</div>
          </div>
        </div>
      </div>

      <div style={{ display: "grid", gap: 2, background: "var(--rule)", border: "1px solid var(--rule)" }}>
        <AgreeRow
          checked={data.agreeBilling}
          onChange={v => update("agreeBilling", v)}
          error={errors.agreeBilling}
          body={`I understand my card will be charged ${dollars(MONTHLY_CENTS)} today and monthly thereafter. I can cancel anytime, and request a full refund within 30 days for any reason.`}
        />
        <AgreeRow
          checked={data.agreeTerms}
          onChange={v => update("agreeTerms", v)}
          error={errors.agreeTerms}
          body={"I agree to Service Orchard's terms of service and privacy policy."}
        />
      </div>
    </div>
  );
}

function AgreeRow({ checked, onChange, body, error }) {
  return (
    <label style={{
      display: "grid", gridTemplateColumns: "28px 1fr", gap: 14,
      background: checked ? "var(--paper)" : "var(--cream)",
      padding: "20px 22px", cursor: "pointer",
      transition: "background .12s ease",
    }}>
      <input type="checkbox" checked={checked} onChange={e => onChange(e.target.checked)}
        style={{ marginTop: 2, accentColor: "var(--orchard)", width: 16, height: 16 }}/>
      <div>
        <div style={{ fontSize: 14.5, lineHeight: 1.55, color: "var(--ink)" }}>{body}</div>
        {error && <div className="mono" style={{ color: "#a04a2a", marginTop: 6 }}>✕ {error}</div>}
      </div>
    </label>
  );
}

function Field({ label, hint, error, children, required, optional }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
        <label style={{ fontSize: 14, fontWeight: 500, letterSpacing: "-0.005em" }}>
          {label}{required && <span style={{ color: "var(--orchard)", marginLeft: 4 }}>*</span>}
        </label>
        {optional && <span className="mono" style={{ color: "var(--ink-3)" }}>Optional</span>}
      </div>
      {hint && <div style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 10, fontFamily: "'Newsreader', serif", fontStyle: "italic" }}>{hint}</div>}
      {children}
      {error && <div className="mono" style={{ color: "#a04a2a", marginTop: 8 }}>✕ {error}</div>}
    </div>
  );
}

function TextInput({ value, onChange, placeholder, error, type = "text" }) {
  const style = {
    width: "100%",
    background: "var(--paper)",
    border: "1px solid var(--rule)",
    borderBottom: error ? "2px solid #a04a2a" : "2px solid var(--ink-2)",
    padding: "14px 16px",
    fontFamily: "inherit",
    fontSize: 15,
    color: "var(--ink)",
    outline: "none",
    transition: "border-color .15s ease, background .15s ease",
  };
  return (
    <input
      type={type}
      value={value}
      placeholder={placeholder}
      onChange={e => onChange(e.target.value)}
      style={style}
      onFocus={e => { e.currentTarget.style.borderBottomColor = error ? "#a04a2a" : "var(--orchard)"; e.currentTarget.style.background = "#fff"; }}
      onBlur={e => { e.currentTarget.style.borderBottomColor = error ? "#a04a2a" : "var(--ink-2)"; e.currentTarget.style.background = "var(--paper)"; }}
    />
  );
}

function StepHeading({ n, title }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <div className="mono" style={{ color: "var(--orchard)", marginBottom: 12 }}>§ {n}</div>
      <h2 style={{ fontSize: 34, letterSpacing: "-0.015em", lineHeight: 1.1 }}>{title}</h2>
    </div>
  );
}

Object.assign(window, { SignupPage, clearSignupDraft: clearDraft });
