const Section = ({ title, children }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
    <div style={{ font: "400 20px/1 var(--font-display)", color: "var(--fg-1)", letterSpacing: "-0.02em", paddingBottom: 10, borderBottom: "1px solid var(--border-1)" }}>{title}</div>
    {children}
  </div>
);

function Settings({ user, jobContext, onJobChange, onLogout, darkMode = false, subscriptionPlan = "free", sessionUsage = { used: 0, limit: 1 }, onUpgrade }) {
  const isPaid = subscriptionPlan === "pro" || subscriptionPlan === "premium";
  // Selected repos persist on jobContext.selectedRepos (array of repo names).
  // Default selection (first session after connecting): all repos selected.
  const [selectedRepos, setSelectedRepos] = React.useState(() => {
    const saved = jobContext?.selectedRepos;
    if (Array.isArray(saved)) return saved;
    return (jobContext?.githubTopRepos || []).map(r => r.name);
  });

  function toggleRepo(name) {
    setSelectedRepos(prev => {
      const next = prev.includes(name) ? prev.filter(n => n !== name) : [...prev, name];
      onJobChange({ ...jobContext, selectedRepos: next });
      return next;
    });
  }
  function selectAllRepos() {
    const all = (jobContext?.githubTopRepos || []).map(r => r.name);
    setSelectedRepos(all);
    onJobChange({ ...jobContext, selectedRepos: all });
  }
  const [role, setRole]       = React.useState(jobContext?.role || "");
  const [company, setCompany] = React.useState(jobContext?.company || "");
  const ghConnected = !!(jobContext?.githubName);
  const [voice, setVoice]       = React.useState(localStorage.getItem("gr.voice") || "female");
  const [saved, setSaved]       = React.useState(false);

  function save() {
    const ctx = {
      ...jobContext,
      role, company,
    };
    onJobChange(ctx);
    localStorage.setItem("gr.voice", voice);
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  }

  return (
    <div data-screen-label="Settings" style={{ minHeight: "100vh" }}>
      <header style={{
        padding: "20px clamp(16px, 5vw, 32px)", borderBottom: "1px solid var(--border-1)",
        background: darkMode
          ? "linear-gradient(180deg, rgba(44,47,53,.86) 0%, rgba(28,30,35,.92) 100%)"
          : "linear-gradient(180deg, rgba(255,255,255,.88) 0%, rgba(242,245,248,.94) 100%)",
        backdropFilter: "blur(12px)",
        display: "flex", alignItems: "center", justifyContent: "space-between",
        flexWrap: "wrap", gap: 12,
      }}>
        <div style={{ minWidth: 0 }}>
          <h1 style={{ font: "400 28px/1 var(--font-display)", letterSpacing: "-0.02em", margin: 0 }}>Settings</h1>
          <div style={{ font: "var(--text-body-sm)", color: "var(--fg-3)", marginTop: 3 }}>Manage your profile, interview setup, and connections</div>
        </div>
        <Button variant="primary" onClick={save} style={{ flexShrink: 0 }} icon={saved ? <Icon name="check" size={14} color="#fff" /> : null}>
          {saved ? "Saved" : "Save changes"}
        </Button>
      </header>

      <main style={{ maxWidth: 680, margin: "0 auto", padding: "clamp(20px, 5vw, 40px)", display: "flex", flexDirection: "column", gap: "clamp(24px, 5vw, 36px)" }}>

        {/* Profile */}
        <Section title="Profile">
          <Card padding={20}>
            <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
              {user.picture
                ? <img src={user.picture} width="56" height="56" style={{ borderRadius: 999, flexShrink: 0 }} alt="" />
                : <Avatar initials={user.initials} size={56} brand />}
              <div style={{ flex: "1 1 180px", minWidth: 0 }}>
                <div style={{ font: "400 20px/1 var(--font-display)", letterSpacing: "-0.02em", color: "var(--fg-1)", overflowWrap: "anywhere" }}>{user.name}</div>
                <div style={{ font: "var(--text-body-sm)", color: "var(--fg-3)", marginTop: 2, overflowWrap: "anywhere" }}>{user.email}</div>
                <Pill tone="success" style={{ marginTop: 8, whiteSpace: "nowrap" }}>
                  <Icon name="shield-check" size={11} /> Google connected
                </Pill>
              </div>
              <Button variant="secondary" onClick={onLogout} style={{ flexShrink: 0 }} icon={<Icon name="log-out" size={14} />}>Sign out</Button>
            </div>
          </Card>
        </Section>

        {/* Interview setup */}
        <Section title="Interview setup">
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <TextField label="Target role" placeholder="e.g. Software Engineer" value={role} onChange={e => setRole(e.target.value)} />
            <TextField label="Target company" placeholder="e.g. Google" value={company} onChange={e => setCompany(e.target.value)} />
          </div>
        </Section>

        {/* Voice preference */}
        <Section title="Interviewer voice">
          <Card padding={16}>
            <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
              {[
                { id: "female", label: "Female", desc: "HFC · Natural", icon: "user-round" },
                { id: "male",   label: "Male",   desc: "Lessac · Clear", icon: "user" },
              ].map(v => (
                <button key={v.id} onClick={() => setVoice(v.id)} style={{
                  flex: "1 1 150px", minWidth: 0, padding: "12px 16px", borderRadius: 8, cursor: "pointer", textAlign: "left",
                  border: `2px solid ${voice === v.id ? "var(--gr-green-500)" : "var(--border-1)"}`,
                  background: voice === v.id ? "var(--bg-brand-soft)" : "var(--bg-subtle)",
                  display: "flex", alignItems: "center", gap: 12,
                }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: 999, flexShrink: 0,
                    background: voice === v.id ? "var(--gr-green-500)" : "var(--bg-subtle)",
                    display: "flex", alignItems: "center", justifyContent: "center",
                  }}>
                    <Icon name={v.icon} size={16} color={voice === v.id ? "#fff" : "var(--fg-3)"} />
                  </div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ font: "500 14px var(--font-sans)", color: voice === v.id ? "var(--gr-green-700)" : "var(--fg-1)", whiteSpace: "nowrap" }}>{v.label}</div>
                    <div style={{ font: "var(--text-body-sm)", color: "var(--fg-3)", whiteSpace: "nowrap" }}>{v.desc}</div>
                  </div>
                  {voice === v.id && <Icon name="check-circle-2" size={16} color="var(--gr-green-500)" style={{ marginLeft: "auto" }} />}
                </button>
              ))}
            </div>
          </Card>
        </Section>

        {/* Connections */}
        <Section title="Connections">

          {/* GitHub */}
          <Card padding={20}>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 14 }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: "#24292e", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="#fff"><path d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"/></svg>
              </div>
              <div style={{ flex: "1 1 140px", minWidth: 0 }}>
                <div style={{ font: "500 14px var(--font-sans)" }}>GitHub</div>
                <div style={{ font: "var(--text-body-sm)", color: "var(--fg-3)" }}>Ari references your repos during technical questions</div>
              </div>
              {ghConnected && <Pill tone="success" dot style={{ flexShrink: 0, whiteSpace: "nowrap" }}>Connected</Pill>}
            </div>

            {ghConnected ? (
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px", borderRadius: 8, background: "var(--bg-subtle)", border: "1px solid var(--border-1)" }}>
                  <img src={jobContext.githubAvatar} width="40" height="40" style={{ borderRadius: 999 }} alt="" onError={e => { e.currentTarget.src = "../../assets/logo.svg"; }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ font: "500 14px var(--font-sans)" }}>{jobContext.githubName}</div>
                    <div style={{ font: "var(--text-body-sm)", color: "var(--fg-3)" }}>@{jobContext.github} · {jobContext.githubRepos} repos</div>
                    {jobContext.githubBio && <div style={{ font: "var(--text-body-sm)", color: "var(--fg-2)", marginTop: 2 }}>{jobContext.githubBio}</div>}
                    <div style={{ display: "flex", gap: 12, marginTop: 4, flexWrap: "wrap" }}>
                      {jobContext.githubCompany  && <span style={{ font: "var(--text-body-sm)", color: "var(--fg-3)" }}>🏢 {jobContext.githubCompany}</span>}
                      {jobContext.githubLocation && <span style={{ font: "var(--text-body-sm)", color: "var(--fg-3)" }}>📍 {jobContext.githubLocation}</span>}
                    </div>
                  </div>
                </div>
                {jobContext.githubLanguages?.length > 0 && (
                  <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                    {jobContext.githubLanguages.map(l => (
                      <Pill key={l} tone="outline">{l}</Pill>
                    ))}
                  </div>
                )}
                {jobContext.githubTopRepos?.length > 0 && (
                  <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                      <div>
                        <div style={{ font: "500 13px var(--font-sans)", color: "var(--fg-1)" }}>
                          Repos Ari draws questions from
                        </div>
                        <div style={{ font: "12px var(--font-sans)", color: "var(--fg-3)", marginTop: 2 }}>
                          {isPaid
                            ? `Pick the projects you want to be quizzed on — ${selectedRepos.length} selected.`
                            : "Pro and Premium can pick specific repos. Free uses all your top repos."}
                        </div>
                      </div>
                      {isPaid && (
                        <button
                          type="button"
                          onClick={selectAllRepos}
                          style={{
                            background: "transparent", border: "1px solid var(--border-1)",
                            borderRadius: 7, padding: "5px 12px", cursor: "pointer",
                            font: "500 12px var(--font-sans)", color: "var(--fg-2)",
                            whiteSpace: "nowrap", flexShrink: 0,
                          }}
                        >
                          Select all
                        </button>
                      )}
                      {!isPaid && onUpgrade && (
                        <button
                          type="button"
                          onClick={() => onUpgrade?.("pro")}
                          style={{
                            background: "var(--gr-green-500, #1F7A4F)", border: "none",
                            borderRadius: 7, padding: "6px 12px", cursor: "pointer",
                            font: "600 12px var(--font-sans)", color: "#fff",
                            whiteSpace: "nowrap", flexShrink: 0,
                          }}
                        >
                          Upgrade
                        </button>
                      )}
                    </div>
                    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                      {jobContext.githubTopRepos.map(r => {
                        const checked = selectedRepos.includes(r.name);
                        const interactive = isPaid;
                        return (
                          <label
                            key={r.name}
                            style={{
                              display: "flex", alignItems: "center", gap: 12,
                              padding: "10px 12px", borderRadius: 8,
                              background: interactive && checked ? "rgba(31,122,79,.06)" : "var(--bg-subtle)",
                              border: `1px solid ${interactive && checked ? "rgba(31,122,79,.28)" : "var(--border-1)"}`,
                              cursor: interactive ? "pointer" : "default",
                              opacity: interactive ? 1 : 0.65,
                              transition: "background 120ms, border-color 120ms",
                            }}
                          >
                            <input
                              type="checkbox"
                              checked={interactive ? checked : true}
                              disabled={!interactive}
                              onChange={() => interactive && toggleRepo(r.name)}
                              style={{ flexShrink: 0, width: 16, height: 16, cursor: interactive ? "pointer" : "default", accentColor: "var(--gr-green-500, #1F7A4F)" }}
                            />
                            <div style={{ flex: 1, minWidth: 0 }}>
                              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                                <span style={{ font: "500 13px var(--font-sans)", color: "var(--fg-1)" }}>{r.name}</span>
                                {/^https?:\/\//i.test(r.url || "") && (
                                  <a href={r.url} target="_blank" rel="noopener noreferrer" onClick={e => e.stopPropagation()} style={{ font: "12px var(--font-sans)", color: "var(--fg-3)", textDecoration: "none" }}>
                                    ↗
                                  </a>
                                )}
                              </div>
                              {r.description && <div style={{ font: "var(--text-body-sm)", color: "var(--fg-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.description}</div>}
                            </div>
                            <div style={{ display: "flex", alignItems: "center", gap: 8, flexShrink: 0 }}>
                              {r.language && <Pill tone="neutral">{r.language}</Pill>}
                              <span style={{ font: "var(--text-body-sm)", color: "var(--fg-3)" }}>★ {r.stars}</span>
                            </div>
                          </label>
                        );
                      })}
                    </div>
                    {isPaid && selectedRepos.length === 0 && (
                      <div style={{ font: "12px var(--font-sans)", color: "#b91c1c", padding: "8px 12px", background: "rgba(180,35,24,.05)", border: "1px solid rgba(180,35,24,.2)", borderRadius: 7 }}>
                        No repos selected — Ari will fall back to all your top repos.
                      </div>
                    )}
                  </div>
                )}
              </div>
            ) : (
              <a href={`https://api.usegreenroom.app/auth/github?token=${encodeURIComponent(localStorage.getItem("gr.token") || "")}`} style={{
                display: "inline-flex", alignItems: "center", gap: 8,
                padding: "8px 16px", borderRadius: 6, textDecoration: "none",
                background: "#24292e", color: "#fff",
                font: "500 13px var(--font-sans)",
              }}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="#fff"><path d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"/></svg>
                Connect GitHub
              </a>
            )}
          </Card>

          {/* LinkedIn */}
          <Card padding={20}>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 14 }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: "#0077b5", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="#fff"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>
              </div>
              <div style={{ flex: "1 1 140px", minWidth: 0 }}>
                <div style={{ font: "500 14px var(--font-sans)" }}>LinkedIn</div>
                <div style={{ font: "var(--text-body-sm)", color: "var(--fg-3)" }}>Your background and experience for personalised questions</div>
              </div>
              {jobContext?.linkedinName && <Pill tone="success" dot style={{ flexShrink: 0, whiteSpace: "nowrap" }}>Connected</Pill>}
            </div>

            {jobContext?.linkedinName ? (
              <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: 8, background: "var(--bg-subtle)", border: "1px solid var(--border-1)" }}>
                {jobContext.linkedinPicture
                  ? <img src={jobContext.linkedinPicture} width="32" height="32" style={{ borderRadius: 999 }} alt="" />
                  : <div style={{ width: 32, height: 32, borderRadius: 999, background: "#0077b5", display: "flex", alignItems: "center", justifyContent: "center", color: "#fff", font: "600 13px var(--font-sans)" }}>in</div>}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ font: "500 13px var(--font-sans)", overflowWrap: "anywhere" }}>{jobContext.linkedinName}</div>
                  <div style={{ font: "var(--text-body-sm)", color: "var(--fg-3)", overflowWrap: "anywhere" }}>{jobContext.linkedinEmail}</div>
                </div>
              </div>
            ) : (
              <a href="https://api.usegreenroom.app/auth/linkedin" style={{
                display: "inline-flex", alignItems: "center", gap: 8,
                padding: "8px 16px", borderRadius: 6, textDecoration: "none",
                background: "#0077b5", color: "#fff",
                font: "500 13px var(--font-sans)",
              }}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="#fff"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>
                Connect LinkedIn
              </a>
            )}
          </Card>
        </Section>

        {/* Subscription management — paid users only */}
        {subscriptionPlan !== "free" && (
          <SubscriptionPanel
            subscriptionPlan={subscriptionPlan}
            user={user}
            darkMode={darkMode}
            sessionUsage={sessionUsage}
          />
        )}

        {/* Plan usage — pro only */}
        {subscriptionPlan !== "free" && (() => {
          const remaining = sessionUsage.limit - sessionUsage.used;
          const pct = Math.min((sessionUsage.used / sessionUsage.limit) * 100, 100);
          const color = remaining <= 5 ? "#dc2626" : remaining <= 10 ? "#d97706" : "var(--gr-green-500)";
          return (
            <Section title="Plan usage">
              <Card padding={20}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
                  <div>
                    <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                      <span style={{ font: "700 36px var(--font-mono)", color, letterSpacing: "-0.03em", lineHeight: 1 }}>{remaining}</span>
                      <span style={{ font: "500 14px var(--font-sans)", color: "var(--fg-3)" }}>of {sessionUsage.limit} sessions left this month</span>
                    </div>
                    <div style={{ font: "var(--text-body-sm)", color: "var(--fg-3)", marginTop: 4 }}>
                      {sessionUsage.used} session{sessionUsage.used !== 1 ? "s" : ""} used · resets on your next billing date
                    </div>
                  </div>
                  <Pill tone={remaining <= 5 ? "danger" : remaining <= 10 ? "warning" : "success"}>{subscriptionPlan}</Pill>
                </div>
                <div style={{ height: 6, background: "var(--bg-subtle)", borderRadius: 999, overflow: "hidden" }}>
                  <div style={{ height: "100%", width: `${pct}%`, background: color, borderRadius: 999, transition: "width 600ms ease" }} />
                </div>
              </Card>
            </Section>
          );
        })()}

      </main>
    </div>
  );
}
// ── Subscription cancel + refund-request panel ────────────────────
function SubscriptionPanel({ subscriptionPlan, user, darkMode, sessionUsage = { used: 0, limit: 1 } }) {
  const token = localStorage.getItem("gr.token") || "";
  // Refund policy: only available before first session on the current plan.
  // sessionUsage.used is sessions used this period — if it's > 0, they've used the service.
  const refundEligible = (sessionUsage?.used || 0) === 0;
  const [cancelling, setCancelling]   = React.useState(false);
  const [cancelMsg,  setCancelMsg]    = React.useState("");
  const [cancelErr,  setCancelErr]    = React.useState("");
  const [showRefund, setShowRefund]   = React.useState(false);
  const [reason,     setReason]       = React.useState("");
  const [sending,    setSending]      = React.useState(false);
  const [refundMsg,  setRefundMsg]    = React.useState("");
  const [refundErr,  setRefundErr]    = React.useState("");

  async function cancel() {
    if (!confirm("Cancel your subscription? You'll keep access until the end of the paid period.")) return;
    setCancelling(true); setCancelErr(""); setCancelMsg("");
    try {
      const res = await fetch("https://api.usegreenroom.app/api/subscription/cancel", {
        method: "POST",
        headers: { Authorization: `Bearer ${token}` },
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Couldn't cancel");
      setCancelMsg(data.message || "Cancelled.");
      window.posthog?.capture('subscription_cancelled');
    } catch (e) {
      setCancelErr(e.message);
    }
    setCancelling(false);
  }

  async function submitRefund(e) {
    e.preventDefault();
    if (reason.trim().length < 5) { setRefundErr("Please tell us a bit more so we can help."); return; }
    setSending(true); setRefundErr(""); setRefundMsg("");
    try {
      const res = await fetch("https://api.usegreenroom.app/api/refund/request", {
        method: "POST",
        headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
        body: JSON.stringify({ reason: reason.trim() }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Couldn't submit request");
      setRefundMsg(data.message || "Request received.");
      setReason("");
      window.posthog?.capture('refund_requested');
      setTimeout(() => setShowRefund(false), 2400);
    } catch (e) {
      setRefundErr(e.message);
    }
    setSending(false);
  }

  return (
    <Section title="Subscription">
      <Card padding={20}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 12 }}>
          <div>
            <div style={{ font: "500 14px var(--font-sans)", color: "var(--fg-1)" }}>
              You're on the <strong style={{ textTransform: "capitalize" }}>{subscriptionPlan}</strong> plan
            </div>
            <div style={{ font: "12px var(--font-sans)", color: "var(--fg-3)", marginTop: 3 }}>
              Manage your subscription. Cancellations keep access until the end of your paid period.
            </div>
            {!refundEligible && (
              <div style={{ font: "12px var(--font-sans)", color: "var(--fg-4)", marginTop: 6 }}>
                Refunds are only available before your first mock session on this plan.
              </div>
            )}
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button
              onClick={() => refundEligible && setShowRefund(v => !v)}
              disabled={!refundEligible}
              title={refundEligible ? "" : "Refunds are only available before your first mock session on this plan."}
              style={{
                padding: "8px 14px", borderRadius: 8, border: "1px solid var(--border-1)",
                background: "transparent",
                color: refundEligible ? "var(--fg-2)" : "var(--fg-4)",
                font: "500 13px var(--font-sans)",
                cursor: refundEligible ? "pointer" : "not-allowed",
                opacity: refundEligible ? 1 : 0.6,
              }}
            >
              Request refund
            </button>
            <button onClick={cancel} disabled={cancelling || !!cancelMsg} style={{
              padding: "8px 14px", borderRadius: 8, border: "1px solid rgba(180,35,24,.3)",
              background: cancelMsg ? "var(--bg-subtle)" : "rgba(180,35,24,.04)",
              color: cancelMsg ? "var(--fg-3)" : "#B42318",
              font: "600 13px var(--font-sans)",
              cursor: cancelling || cancelMsg ? "not-allowed" : "pointer",
            }}>
              {cancelling ? "Cancelling…" : (cancelMsg ? "Cancelled" : "Cancel subscription")}
            </button>
          </div>
        </div>

        {cancelMsg && (
          <div style={{ marginTop: 12, padding: "10px 12px", borderRadius: 8, background: "rgba(31,122,79,.06)", border: "1px solid rgba(31,122,79,.22)", font: "13px/1.5 var(--font-sans)", color: "var(--fg-1)" }}>
            ✓ {cancelMsg}
          </div>
        )}
        {cancelErr && (
          <div style={{ marginTop: 12, padding: "10px 12px", borderRadius: 8, background: "rgba(180,35,24,.05)", border: "1px solid rgba(180,35,24,.22)", font: "13px var(--font-sans)", color: "#B42318" }}>
            {cancelErr}
          </div>
        )}

        {showRefund && (
          <form onSubmit={submitRefund} style={{ marginTop: 16, paddingTop: 16, borderTop: "1px solid var(--border-1)", display: "flex", flexDirection: "column", gap: 10 }}>
            <div style={{ font: "500 13px var(--font-sans)", color: "var(--fg-1)" }}>Request a refund</div>
            <div style={{ font: "12px var(--font-sans)", color: "var(--fg-3)" }}>
              We process refund requests manually within 24 hours. Briefly tell us why.
            </div>
            <textarea
              value={reason}
              onChange={e => setReason(e.target.value)}
              placeholder="e.g. The questions weren't relevant to my role / I was double-charged / Service wasn't what I expected"
              rows={4}
              style={{
                width: "100%", padding: "10px 12px", boxSizing: "border-box",
                border: "1px solid var(--border-1)", borderRadius: 8,
                font: "13px/1.5 var(--font-sans)", color: "var(--fg-1)",
                outline: "none", resize: "vertical", background: "var(--bg-subtle)",
              }}
            />
            {refundErr && (
              <div style={{ font: "12px var(--font-sans)", color: "#B42318", padding: "8px 10px", background: "rgba(180,35,24,.05)", borderRadius: 7 }}>{refundErr}</div>
            )}
            {refundMsg && (
              <div style={{ font: "13px var(--font-sans)", color: "var(--gr-green-600, #1F7A4F)", padding: "8px 10px", background: "rgba(31,122,79,.06)", borderRadius: 7 }}>✓ {refundMsg}</div>
            )}
            <div style={{ display: "flex", gap: 8 }}>
              <button type="button" onClick={() => { setShowRefund(false); setReason(""); setRefundErr(""); }} style={{
                padding: "8px 14px", borderRadius: 8, border: "1px solid var(--border-1)",
                background: "transparent", color: "var(--fg-2)", font: "500 13px var(--font-sans)", cursor: "pointer",
              }}>Cancel</button>
              <button type="submit" disabled={sending} style={{
                padding: "8px 16px", borderRadius: 8, border: "none",
                background: sending ? "var(--fg-4)" : "#14140F", color: "#fff",
                font: "600 13px var(--font-sans)", cursor: sending ? "not-allowed" : "pointer",
              }}>
                {sending ? "Sending…" : "Send refund request"}
              </button>
            </div>
          </form>
        )}
      </Card>
    </Section>
  );
}

window.Settings = Settings;
