const { useState: useStateSC, useEffect: useEffectSC } = React;

const INCLUDED = [
  { key: "Designer",   prompt: "We need a flyer for Saturday's gala — keep it warm and not too corporate." },
  { key: "Writer",     prompt: "Draft a thank-you letter to the donors who gave during our spring drive." },
  { key: "Builder",    prompt: "We need a one-page event registration site for our June fundraiser." },
  { key: "Social",     prompt: "Three Instagram posts announcing the new tutoring program." },
  { key: "Researcher", prompt: "Find five family foundations in our county that fund youth-arts programs." },
];

const MONTHLY = "$12";

function fmtDate(iso) {
  if (!iso) return null;
  const d = new Date(iso);
  if (isNaN(d.getTime())) return null;
  return d.toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" });
}

function SuccessPage({ setRoute, sessionId }) {
  const [info, setInfo] = useStateSC(null);
  const [loaded, setLoaded] = useStateSC(false);

  useEffectSC(() => {
    if (typeof window !== "undefined" && typeof window.clearSignupDraft === "function") {
      window.clearSignupDraft();
    }
    if (!sessionId) { setLoaded(true); return; }
    fetch(`/api/session/${encodeURIComponent(sessionId)}`)
      .then(r => r.ok ? r.json() : null)
      .then(d => { setInfo(d); setLoaded(true); })
      .catch(() => setLoaded(true));
  }, [sessionId]);

  const guaranteeDate = fmtDate(info?.guaranteeEnd) || fmtDate(new Date(Date.now() + 30 * 86400000).toISOString());

  return (
    <div style={{ background: "var(--cream)", minHeight: "100vh", display: "flex", flexDirection: "column" }}>
      <div style={{ borderBottom: "1px solid var(--rule)", padding: "18px 40px" }}>
        <button onClick={() => setRoute("home")} style={{ background: "none", border: "none", cursor: "pointer", padding: 0 }}>
          <Wordmark size={20} />
        </button>
      </div>

      <div style={{ flex: 1, display: "flex", alignItems: "flex-start" }}>
        <div style={{ maxWidth: 880, margin: "0 auto", padding: "80px 40px 100px", width: "100%" }}>
          <Reveal>
            <div className="mono" style={{ color: "var(--orchard)", marginBottom: 28, display: "inline-flex", alignItems: "center", gap: 14 }}>
              <BranchSprig size={48}/>
              <span>Welcome to the orchard</span>
            </div>
          </Reveal>
          <Reveal delay={80}>
            <h1 style={{ fontSize: "clamp(48px, 6.4vw, 92px)", lineHeight: 0.98, letterSpacing: "-0.025em", marginBottom: 28 }}>
              You're <span className="serif-italic" style={{ color: "var(--sun-deep)" }}>in.</span>
            </h1>
          </Reveal>
          <Reveal delay={160}>
            <p style={{ fontSize: 19, lineHeight: 1.55, color: "var(--ink-2)", maxWidth: 680, marginBottom: 24 }}>
              {info?.email
                ? <>We're provisioning your dedicated assistant inbox now. You'll receive setup details at <span style={{ color: "var(--ink)", fontWeight: 500 }}>{info.email}</span> within 24 hours.</>
                : <>We're provisioning your dedicated assistant inbox now. You'll receive setup details by email within 24 hours.</>}
            </p>
          </Reveal>

          {loaded && (
            <Reveal delay={220}>
              <div style={{ background: "var(--paper)", border: "1px solid var(--rule)", padding: "32px 32px 28px", marginBottom: 40, marginTop: 24, maxWidth: 720 }}>
                <div className="mono" style={{ color: "var(--sun-deep)", marginBottom: 14 }}>Subscription summary</div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24, marginBottom: 20 }}>
                  <div>
                    <div className="mono" style={{ color: "var(--ink-3)", marginBottom: 6 }}>Status</div>
                    <div style={{ fontSize: 16, color: "var(--ink)", fontFamily: "'Newsreader', serif", fontStyle: "italic" }}>Subscribed · active</div>
                  </div>
                  <div>
                    <div className="mono" style={{ color: "var(--ink-3)", marginBottom: 6 }}>Plan</div>
                    <div style={{ fontSize: 16, color: "var(--ink)" }}>{MONTHLY} / month, flat</div>
                  </div>
                  {guaranteeDate && (
                    <div>
                      <div className="mono" style={{ color: "var(--ink-3)", marginBottom: 6 }}>Money-back through</div>
                      <div style={{ fontSize: 16, color: "var(--ink)" }}>{guaranteeDate}</div>
                    </div>
                  )}
                  {info?.orgName && (
                    <div>
                      <div className="mono" style={{ color: "var(--ink-3)", marginBottom: 6 }}>Organization</div>
                      <div style={{ fontSize: 16, color: "var(--ink)" }}>{info.orgName}</div>
                    </div>
                  )}
                </div>
                <div style={{ paddingTop: 20, borderTop: "1px solid var(--rule)" }}>
                  <div className="mono" style={{ color: "var(--ink-3)", marginBottom: 14 }}>What's included</div>
                  <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 14 }}>
                    {INCLUDED.map(a => (
                      <li key={a.key} style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 14, alignItems: "start" }}>
                        <svg width="18" height="22" viewBox="0 0 36 44" style={{ marginTop: 2 }}>
                          <path d="M18 4 Q 14 8 16 12" stroke="var(--bark)" strokeWidth="1.5" fill="none"/>
                          <circle cx="18" cy="26" r="13" fill="var(--sun)"/>
                          <circle cx="18" cy="26" r="13" fill="none" stroke="var(--bark)" strokeWidth="0.5" strokeDasharray="1 2.5" opacity="0.5"/>
                        </svg>
                        <div>
                          <div style={{ fontFamily: "'Newsreader', serif", fontSize: 18, color: "var(--ink)" }}>{a.key}</div>
                          <div style={{ fontSize: 13, color: "var(--ink-3)", fontFamily: "'Newsreader', serif", fontStyle: "italic", marginTop: 4 }}>
                            e.g., "{a.prompt}"
                          </div>
                        </div>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            </Reveal>
          )}

          <Reveal delay={300}>
            <h2 style={{ fontSize: 26, letterSpacing: "-0.015em", marginBottom: 12 }}>What happens next</h2>
            <ol style={{ paddingLeft: 18, margin: 0, display: "grid", gap: 12, color: "var(--ink-2)", fontSize: 15.5, lineHeight: 1.6, maxWidth: 680 }}>
              <li>Within 24 hours we'll email your dedicated assistant inbox address.</li>
              <li>Send any request to that address — a flyer, a draft, a research question. Reply with revisions until it's right.</li>
              <li>If we're not a fit, ask for your money back any time in the first 30 days — full refund, no questions asked. Cancel any month after that with a single email.</li>
            </ol>
          </Reveal>

          <Reveal delay={400}>
            <div style={{ marginTop: 48, display: "flex", gap: 18, alignItems: "center", flexWrap: "wrap" }}>
              <Button variant="ghost" onClick={() => setRoute("home")}>← Back to home</Button>
              <a href="mailto:hello@serviceorchard.com" style={{ fontSize: 14, color: "var(--ink-2)", textDecoration: "none", borderBottom: "1px solid var(--rule-2)", paddingBottom: 2 }}>
                hello@serviceorchard.com
              </a>
            </div>
          </Reveal>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SuccessPage });
