// ════════════════════════════════════════════════════════════════
// Pricing page — v2 preview React components.
// Data + checkout come from landing/v2/pricing-data.js (window.PLANS,
// window.handleCheckout, etc., copied verbatim from production).
// Reuses the Phase 1/2 design system: Nav, Btn, Eyebrow, TrustBar.
// ════════════════════════════════════════════════════════════════

// Free plan / not-signed-in fallback routes to the app signup, matching the
// production flow where handleCheckout(plan, isAnnual, onSignup) calls onSignup
// for the free tier and for un-authed paid checkout. Paid plans (Starter/Team)
// carry their plan + interval into the signup URL so checkout can auto-resume
// once the account + org exist (see app/core.jsx resume effect).
function pricingSignup(plan, isAnnual) {
  let u = "/app?mode=signup";
  // Only paid plans (have a Price ID) carry a checkout intent; free/business don't.
  if (plan && plan.id && plan.id !== "free" && plan.id !== "business") {
    u += "&plan=" + encodeURIComponent(plan.id) + "&interval=" + (isAnnual ? "annual" : "monthly");
  }
  window.location.href = u;
}

// ===== Hero — eyebrow + display heading + sub + billing toggle =====
function PricingHero({ isAnnual, onToggle }) {
  return <section className="v2-section v2-pricing-hero hero-stage" style={{ paddingBottom: "clamp(28px,3.6vw,44px)" }}>
    <div className="wrap" style={{ textAlign: "center", maxWidth: 760, margin: "0 auto" }}>
      <div style={{ display: "flex", justifyContent: "center", marginBottom: 18 }}>
        <Eyebrow>PRICING</Eyebrow>
      </div>
      <h1 className="display" style={{ fontSize: "clamp(34px,5.6vw,60px)", lineHeight: 1.02 }}>
        Pricing that doesn't require a <span className="serif-i" style={{ color: "var(--accent)" }}>procurement form.</span>
      </h1>
      <p style={{ fontSize: 18, lineHeight: 1.55, color: "var(--ink-2)", margin: "20px auto 0", maxWidth: 540 }}>
        Free forever up to 25 people. No credit card to start.
      </p>
      <div style={{ marginTop: 30 }}>
        <BillingToggle isAnnual={isAnnual} onToggle={onToggle} />
      </div>
    </div>
  </section>;
}

// ===== Monthly / annual segmented control =====
function BillingToggle({ isAnnual, onToggle }) {
  return <div style={{ display: "inline-flex", flexDirection: "column", alignItems: "center", gap: 10 }}>
    <div className="v2-toggle" role="group" aria-label="Billing interval">
      <button type="button" className={!isAnnual ? "on" : ""} aria-pressed={!isAnnual}
        onClick={() => onToggle(false)}>Monthly</button>
      <button type="button" className={isAnnual ? "on" : ""} aria-pressed={isAnnual}
        onClick={() => onToggle(true)}>Annual</button>
    </div>
    <span className="mono" style={{ fontSize: 11.5, letterSpacing: ".06em", textTransform: "uppercase",
      color: isAnnual ? "var(--accent-ink)" : "var(--muted)" }}>
      {isAnnual ? "2 months free" : "Save with annual billing"}
    </span>
  </div>;
}

// ===== Single plan card =====
function PlanCard({ plan, isAnnual }) {
  const [loading, setLoading] = React.useState(false);
  const price  = isAnnual ? plan.price.annual : plan.price.monthly;
  const suffix = (isAnnual && plan.price.annual > 0) ? "/yr" : "/mo";
  const note   = isAnnual && plan.billingNote ? plan.billingNote.annual : null;

  async function onClick() {
    setLoading(true);
    try { await window.handleCheckout(plan, isAnnual, () => pricingSignup(plan, isAnnual)); }
    finally { setLoading(false); }
  }

  // Popular tier gets the primary button; everyone else a ghost.
  const btnVariant = plan.popular ? "primary" : "ghost";

  return <article className={"v2-plan" + (plan.popular ? " pop" : "")}>
    {plan.popular && <div className="v2-plan-flag">Most popular</div>}

    <div className="v2-plan-name">{plan.name}</div>
    <p className="v2-plan-tag">{plan.tagline}</p>

    <div className="v2-plan-price">
      <span className="v2-plan-amt">${price}</span>
      <span className="v2-plan-suffix">{suffix}</span>
    </div>
    <div className="v2-plan-note">{note || " "}</div>
    <div className="v2-plan-limit">{plan.limit}</div>

    <button type="button" className={"btn btn-" + btnVariant + " btn-md v2-plan-cta"}
      onClick={onClick} disabled={loading} aria-busy={loading}>
      {loading ? "Loading…" : plan.cta}
    </button>

    <ul className="v2-bullets v2-plan-feats">
      {plan.features.map((f, i) => <li key={i}>{f}</li>)}
    </ul>
  </article>;
}

// ===== 4-up plan card grid =====
function PlanCards({ isAnnual }) {
  return <section className="v2-section" style={{ paddingTop: "clamp(20px,2.6vw,32px)" }}>
    <div className="wrap">
      <div className="v2-tiers-full">
        {window.PLANS.map(plan => <PlanCard key={plan.id} plan={plan} isAnnual={isAnnual} />)}
      </div>
    </div>
  </section>;
}

// ===== Renders a single cell value: true → accent ✓, false/"–" → muted dash,
// string → plain text. =====
function CmpCell({ value, isTeam }) {
  const cls = "v2-cmp-cell" + (isTeam ? " v2-cmp-teamcol" : "");
  if (value === true)
    return <td className={cls}><span className="v2-cmp-yes" aria-label="Included">✓</span></td>;
  if (value === false || value === "–" || value === "-")
    return <td className={cls}><span className="v2-cmp-no" aria-label="Not included">–</span></td>;
  return <td className={cls}>{value}</td>;
}

// ===== Comparison table — behind a "Compare all features" toggle =====
function ComparisonTable() {
  const [open, setOpen] = React.useState(false);
  const tableId = "v2-cmp-table";
  return <section className="v2-section v2-cmp-section">
    <div className="wrap">
      <SectionHead eyebrow="COMPARE" title="Every feature, side by side."
        sub="The short version: paid plans add branding, scenario planning and Org Health. The long version is below." />
      <div className="v2-cmp-toggle-row" style={{ marginTop: 26 }}>
        <button type="button" className="v2-cmp-toggle" aria-expanded={open} aria-controls={tableId}
          onClick={() => setOpen(o => !o)}>
          {open ? "Hide full comparison" : "Compare all features"}
          <span className="chev" aria-hidden>▾</span>
        </button>
      </div>

      <div id={tableId} hidden={!open} className="v2-cmp-scroll">
        <table className="v2-cmp">
          <thead>
            <tr>
              <th scope="col">Feature</th>
              <th scope="col">Free</th>
              <th scope="col">Starter</th>
              <th scope="col" className="v2-cmp-teamcol">Team</th>
              <th scope="col">Business</th>
            </tr>
          </thead>
          <tbody>
            {window.TABLE.map((row, i) => {
              if (row.group) {
                return <tr key={i} className="v2-cmp-grouprow">
                  <td colSpan={3}><span className="v2-cmp-group">{row.group}</span></td>
                  <td className="v2-cmp-teamcol" aria-hidden></td>
                  <td aria-hidden></td>
                </tr>;
              }
              return <tr key={i}>
                <th scope="row" style={{ fontWeight: 500, textAlign: "left" }}>{row.label}</th>
                <CmpCell value={row.free} />
                <CmpCell value={row.starter} />
                <CmpCell value={row.team} isTeam />
                <CmpCell value={row.biz} />
              </tr>;
            })}
          </tbody>
        </table>
      </div>
    </div>
  </section>;
}

// ===== Pricing FAQ — same accessible accordion pattern as landing FAQv2 =====
function PricingFAQ() {
  const items = window.FAQS;
  const [open, setOpen] = React.useState(0);
  return <section id="faq" className="v2-section">
    <div className="wrap">
      <SectionHead eyebrow="FAQ" title="Questions, answered." />
      <div className="v2-faq">
        {items.map((item, i) => {
          const isOpen = open === i;
          const panelId = "v2-pfaq-panel-" + i;
          const btnId = "v2-pfaq-btn-" + i;
          return <div key={i} className="v2-faq-item">
            <h3 style={{ margin: 0 }}>
              <button id={btnId} className="v2-faq-q" aria-expanded={isOpen} aria-controls={panelId}
                onClick={() => setOpen(isOpen ? -1 : i)}>
                <span>{item.q}</span>
                <span className="v2-faq-icon" aria-hidden>{isOpen ? "–" : "+"}</span>
              </button>
            </h3>
            <div id={panelId} role="region" aria-labelledby={btnId} hidden={!isOpen} className="v2-faq-a">
              {item.a}
            </div>
          </div>;
        })}
      </div>
    </div>
  </section>;
}

// ===== Final CTA — pricing variant: "Start free — no card" =====
function PricingFinalCTA() {
  return <Section id="final-cta" tone="dark">
    <div style={{ textAlign: "center", maxWidth: 760, margin: "0 auto" }}>
      <div className="eyebrow" style={{ marginBottom: 18 }}>READY WHEN YOU ARE</div>
      <h2 style={{ fontSize: "clamp(40px,6.5vw,72px)", lineHeight: 1.02, letterSpacing: "-.035em", fontWeight: 700, margin: 0 }}>
        Start free.<br />Upgrade when you <span className="serif-i" style={{ color: "var(--accent-2)", fontSize: "1.08em" }}>need to.</span>
      </h2>
      <p style={{ fontSize: 18, lineHeight: 1.5, color: "rgba(246,244,236,.75)", margin: "22px auto 0", maxWidth: 520 }}>
        Free up to 25 employees. No credit card, no trial timer, no procurement form.
      </p>
      <div style={{ marginTop: 30, display: "flex", justifyContent: "center" }}>
        <Btn variant="primary" size="lg" href="/app?mode=signup">Start free — no card →</Btn>
      </div>
      <p className="mono" style={{ marginTop: 22, fontSize: 12.5, color: "rgba(246,244,236,.5)" }}>
        Free to 25 employees · No credit card · Your data stays yours · Encrypted + RLS
      </p>
    </div>
  </Section>;
}

// ===== Page root =====
function PricingPage() {
  const [isAnnual, setIsAnnual] = React.useState(false); // default monthly, matching landing
  return <div>
    <Nav/>
    <StickyCTA/>
    <PricingHero isAnnual={isAnnual} onToggle={setIsAnnual} />
    <PlanCards isAnnual={isAnnual} />
    <section className="v2-section" style={{ paddingTop: 0 }}>
      <div className="wrap"><TrustBar/></div>
    </section>
    <ComparisonTable/>
    <PricingFAQ/>
    <PricingFinalCTA/>
    <Footer/>
  </div>;
}

Object.assign(window, { PricingHero, BillingToggle, PlanCard, PlanCards,
  CmpCell, ComparisonTable, PricingFAQ, PricingFinalCTA, PricingPage });
