// Pricing page — annual toggle, comparison table, FAQ
const { Btn: PrBtn, Pill: PrPill, Avatar: PrAvatar } = window.UI;

function Pricing({ onNav, onLaunch }) {
  const [annual, setAnnual] = React.useState(true);

  const plans = [
    {
      id: "starter",
      name: "Starter",
      tag: "Solo operators",
      monthly: 29, annual: 23,
      desc: "Get your first widget live, free for 14 days.",
      feats: ["1 website", "1 agent seat", "Live chat widget", "30-day history", "Email support"],
      cta: "Start free trial",
      tint: "#7AB6FF",
    },
    {
      id: "team",
      name: "Team",
      tag: "Most popular",
      monthly: 59, annual: 47,
      desc: "Run a small CSR floor across multiple brands.",
      feats: ["Unlimited websites","Up to 25 seats","Smart routing","Canned + AI suggest","Analytics dashboard","Priority chat support","Custom domains"],
      cta: "Start free trial",
      featured: true,
      tint: "#A6F84A",
    },
    {
      id: "scale",
      name: "Scale",
      tag: "Enterprises",
      monthly: "Custom", annual: "Custom",
      desc: "24/7 ops with SSO, audit, and a dedicated CSM.",
      feats: ["Everything in Team","Unlimited seats","SSO + SCIM","SOC 2 audit logs","Custom DPA + DPO","Dedicated CSM","99.99% SLA","Private edge nodes"],
      cta: "Contact sales",
      tint: "#FF9DD2",
    },
  ];

  // Comparison table
  const compareGroups = [
    {
      h: "Core platform",
      rows: [
        ["Live chat widget","Unlimited","Unlimited","Unlimited"],
        ["Websites","1","Unlimited","Unlimited"],
        ["Agent seats","1","25","Unlimited"],
        ["Concurrent conversations","20","Unlimited","Unlimited"],
        ["Chat history","30 days","1 year","Unlimited"],
        ["File attachments","10 MB","100 MB","1 GB"],
      ],
    },
    {
      h: "Routing & automation",
      rows: [
        ["Round-robin routing","✓","✓","✓"],
        ["Skill-based routing","—","✓","✓"],
        ["Language-aware routing","—","✓","✓"],
        ["AI Copilot drafts","—","✓","✓"],
        ["Canned responses","10","Unlimited","Unlimited"],
        ["Trigger campaigns","—","20","Unlimited"],
      ],
    },
    {
      h: "Analytics & ops",
      rows: [
        ["Live dashboard","Basic","Full","Full"],
        ["CSAT surveys","—","✓","✓"],
        ["Custom reports","—","10","Unlimited"],
        ["CSV / API export","—","✓","✓"],
        ["Webhooks","—","✓","✓"],
      ],
    },
    {
      h: "Security & compliance",
      rows: [
        ["GDPR + PH DPA","✓","✓","✓"],
        ["SSO (SAML / OIDC)","—","—","✓"],
        ["SCIM provisioning","—","—","✓"],
        ["Audit logs","30 days","1 year","Unlimited"],
        ["SOC 2 Type II","—","—","✓"],
        ["Custom DPA","—","—","✓"],
        ["Private edge node","—","—","✓"],
      ],
    },
    {
      h: "Support",
      rows: [
        ["Email","< 24h","< 4h","< 1h"],
        ["Live chat","—","✓","24/7"],
        ["Dedicated CSM","—","—","✓"],
        ["Onboarding","Self-serve","Group","White-glove"],
        ["Uptime SLA","99.9%","99.95%","99.99%"],
      ],
    },
  ];

  const faqs = [
    { q: "Do you charge per conversation?", a: "No. Every plan includes unlimited conversations and unlimited websites. You pay per agent seat — and seats are paused, not deleted, when an agent is off shift." },
    { q: "Can I switch plans later?", a: "Anytime. Upgrade instantly, downgrade at the end of your billing cycle. Annual plans pro-rate when you upgrade mid-term." },
    { q: "What counts as an agent seat?", a: "Anyone who replies to conversations from the Loop dashboard. Admins who only manage settings, view analytics, or supervise are free." },
    { q: "Is there a free plan?", a: "Every plan starts with a 14-day free trial — no credit card. After that you pick a paid plan or your widgets pause until you do." },
    { q: "Where is data stored?", a: "Loop runs on edge nodes in Singapore, Manila, Sydney, Tokyo, and Frankfurt. You choose the primary region; replication is region-locked." },
    { q: "Do you offer SSO and SCIM?", a: "Yes, on the Scale plan. We support SAML 2.0, OIDC, and SCIM 2.0 — and we'll write the integration with your IdP if you're a paying Scale customer." },
    { q: "What's your refund policy?", a: "Cancel any monthly plan and you're refunded for the unused portion. Annual plans are refundable in the first 30 days; pro-rated after." },
    { q: "Can I see audit logs of my agents?", a: "Yes. Every action — login, reply sent, conversation closed, settings changed — is logged. Scale customers get unlimited retention and downloadable logs." },
  ];

  return (
    <window.MarketingShell active="pricing" onNav={onNav} onLaunch={onLaunch}>
      {/* Hero */}
      <section className="relative max-w-[1280px] mx-auto px-8 pt-20 pb-12 text-center">
        <PrPill tone="lime">Pricing</PrPill>
        <h1 className="font-sans tracking-[-0.03em] text-white text-[64px] leading-[1.02] font-semibold mt-5">
          Pay per agent. <br/>Not per conversation.
        </h1>
        <p className="text-[17px] text-white/55 mt-6 max-w-[560px] mx-auto leading-relaxed">
          Unlimited websites, unlimited conversations, unlimited chats — on every plan. The only thing that changes is how many CSRs are on your floor.
        </p>

        {/* Billing toggle */}
        <div className="mt-9 inline-flex items-center gap-3 glass rounded-2xl p-1.5">
          <button onClick={() => setAnnual(false)} className={`h-9 px-5 rounded-xl text-[12.5px] font-medium transition ${!annual ? "bg-white/[0.08] text-white" : "text-white/55"}`}>Monthly</button>
          <button onClick={() => setAnnual(true)} className={`h-9 px-5 rounded-xl text-[12.5px] font-medium transition flex items-center gap-2 ${annual ? "bg-lime text-ink-950" : "text-white/55"}`}>
            Annual <span className={`text-[10.5px] px-1.5 py-0.5 rounded-full ${annual ? "bg-ink-950/15 text-ink-950" : "bg-lime/15 text-lime"}`}>−20%</span>
          </button>
        </div>
      </section>

      {/* Plans */}
      <section className="relative max-w-[1280px] mx-auto px-8 pb-16">
        <div className="grid md:grid-cols-3 gap-5">
          {plans.map(p => (
            <div key={p.id} className={`relative glass rounded-3xl p-7 ${p.featured ? "ring-1 ring-lime/40 border-lime/40 shadow-[0_30px_80px_-20px_rgba(166,248,74,0.3)]" : ""}`}>
              {p.featured && (
                <div className="absolute -top-3 left-7 px-3 py-1 rounded-full bg-lime text-ink-950 text-[10.5px] font-bold tracking-wider uppercase">{p.tag}</div>
              )}
              {!p.featured && (
                <div className="text-[11px] uppercase tracking-[0.15em] text-white/45 mb-1">{p.tag}</div>
              )}
              <div className="text-[20px] font-semibold text-white mt-1" style={{ color: p.featured ? "white" : null }}>{p.name}</div>
              <p className="text-[13px] text-white/55 mt-2 leading-relaxed min-h-[40px]">{p.desc}</p>

              <div className="flex items-baseline gap-1.5 mt-5">
                {typeof p.monthly === "number" ? (
                  <>
                    <span className="text-[48px] font-semibold tracking-tight text-white leading-none">${annual ? p.annual : p.monthly}</span>
                    <div className="flex flex-col leading-tight">
                      <span className="text-[11px] text-white/55">per agent</span>
                      <span className="text-[11px] text-white/55">/ month</span>
                    </div>
                  </>
                ) : (
                  <span className="text-[40px] font-semibold tracking-tight text-white">{p.monthly}</span>
                )}
              </div>
              {typeof p.monthly === "number" && annual && (
                <div className="text-[11px] text-white/40 mt-1.5">Billed ${p.annual * 12}/agent annually · save ${(p.monthly - p.annual) * 12}/yr</div>
              )}

              <button onClick={onLaunch} className={`w-full mt-6 h-12 rounded-xl text-[13.5px] font-semibold ${p.featured ? "btn-lime" : "bg-white/[0.05] hover:bg-white/[0.08] border border-white/[0.08] text-white/90"}`}>{p.cta}</button>

              <div className="border-t border-white/[0.06] mt-7 pt-5 space-y-3">
                {p.feats.map(f => (
                  <div key={f} className="flex items-start gap-2.5 text-[13px] text-white/80">
                    <Icon.Check size={15} className="mt-0.5 shrink-0" style={{ color: p.tint }}/> {f}
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>

        {/* All plans include */}
        <div className="mt-10 glass rounded-2xl p-6">
          <div className="flex flex-wrap items-center justify-between gap-y-3">
            <div className="text-[12.5px] uppercase tracking-[0.15em] text-white/45">Every plan includes</div>
            <div className="flex flex-wrap gap-x-6 gap-y-2 text-[12.5px] text-white/80">
              {["Unlimited conversations","Unlimited websites","14-day free trial","No credit card","Cancel anytime","99.9% uptime"].map(x => (
                <span key={x} className="flex items-center gap-1.5"><Icon.Check size={13} className="text-lime"/>{x}</span>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* Comparison table */}
      <section className="relative max-w-[1280px] mx-auto px-8 py-16">
        <div className="text-center mb-10">
          <PrPill>Compare plans</PrPill>
          <h2 className="font-sans tracking-[-0.025em] text-white text-[40px] leading-[1.05] font-semibold mt-4">Every line, side by side.</h2>
        </div>

        <div className="glass-strong rounded-2xl overflow-hidden">
          <div className="grid grid-cols-[1.6fr_1fr_1fr_1fr] sticky top-0 backdrop-blur-xl bg-ink-950/80 border-b border-white/[0.06] z-10">
            <div className="px-6 py-4 text-[11px] uppercase tracking-[0.12em] text-white/45">Feature</div>
            {plans.map(p => (
              <div key={p.id} className={`px-5 py-4 text-center border-l border-white/[0.04] ${p.featured ? "bg-lime/[0.04]" : ""}`}>
                <div className="text-[13px] font-semibold text-white">{p.name}</div>
                <div className="text-[11px] text-white/55 mt-0.5">{typeof p.monthly === "number" ? `$${annual ? p.annual : p.monthly}/agent` : p.monthly}</div>
              </div>
            ))}
          </div>

          {compareGroups.map(g => (
            <div key={g.h}>
              <div className="px-6 py-3 bg-white/[0.02] border-t border-white/[0.04] text-[11px] uppercase tracking-[0.12em] text-lime/80 font-medium">{g.h}</div>
              {g.rows.map((r, i) => (
                <div key={i} className="grid grid-cols-[1.6fr_1fr_1fr_1fr] border-t border-white/[0.03] hover:bg-white/[0.02]">
                  <div className="px-6 py-3 text-[13px] text-white/85">{r[0]}</div>
                  {r.slice(1).map((cell, j) => (
                    <div key={j} className={`px-5 py-3 text-center text-[13px] border-l border-white/[0.03] ${plans[j].featured ? "bg-lime/[0.025]" : ""} ${cell === "✓" ? "text-lime" : cell === "—" ? "text-white/25" : "text-white/85"}`}>
                      {cell === "✓" ? <Icon.Check size={16} className="text-lime mx-auto"/> : cell}
                    </div>
                  ))}
                </div>
              ))}
            </div>
          ))}
        </div>
      </section>

      {/* FAQ */}
      <section className="relative max-w-[920px] mx-auto px-8 py-20">
        <div className="text-center mb-10">
          <PrPill>FAQ</PrPill>
          <h2 className="font-sans tracking-[-0.025em] text-white text-[40px] leading-[1.05] font-semibold mt-4">Things people ask before signing up.</h2>
        </div>
        <div className="space-y-2">
          {faqs.map((f, i) => <Faq key={i} q={f.q} a={f.a} defaultOpen={i === 0}/>)}
        </div>

        <div className="glass-strong rounded-2xl p-7 mt-10 flex flex-col md:flex-row items-center justify-between gap-4">
          <div className="text-center md:text-left">
            <div className="text-[15px] font-medium text-white">Still have a question?</div>
            <div className="text-[12.5px] text-white/55 mt-0.5">Talk to a human — we promise it's fast.</div>
          </div>
          <div className="flex items-center gap-2">
            <PrBtn variant="ghost"><Icon.Mail size={14}/> sales@loop.cs</PrBtn>
            <PrBtn variant="primary"><Icon.Chat size={14}/> Live chat</PrBtn>
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="relative max-w-[1280px] mx-auto px-8 pb-16">
        <div className="relative glass-strong rounded-3xl overflow-hidden p-12 lg:p-16 text-center">
          <div className="absolute inset-0" style={{ background: "radial-gradient(60% 80% at 50% 0%, rgba(166,248,74,0.16), transparent 60%)" }}/>
          <div className="relative">
            <h2 className="font-sans tracking-[-0.02em] text-white text-[40px] leading-[1.05] font-semibold">Try Loop. Pay nothing for 14 days.</h2>
            <p className="text-[15px] text-white/55 mt-3 max-w-[460px] mx-auto">No card required. Drop the snippet and answer your first real visitor inside ten minutes.</p>
            <div className="flex items-center justify-center gap-3 mt-7">
              <button onClick={onLaunch} className="btn-lime h-12 px-6 rounded-xl text-[14px] font-semibold">Start free trial <Icon.ArrowRight size={15}/></button>
              <button onClick={() => onNav("customers")} className="h-12 px-5 rounded-xl text-[14px] text-white/85 border border-white/[0.12] hover:bg-white/[0.04]">Read customer stories</button>
            </div>
          </div>
        </div>
      </section>
    </window.MarketingShell>
  );
}

function Faq({ q, a, defaultOpen }) {
  const [open, setOpen] = React.useState(!!defaultOpen);
  return (
    <div className="glass rounded-2xl overflow-hidden">
      <button onClick={() => setOpen(o => !o)} className="w-full text-left flex items-center justify-between gap-4 px-6 py-5 hover:bg-white/[0.02]">
        <span className="text-[14.5px] font-medium text-white/95">{q}</span>
        <span className={`grid place-items-center w-7 h-7 rounded-lg shrink-0 transition ${open ? "bg-lime text-ink-950 rotate-45" : "bg-white/[0.04] text-white/55"}`}>
          <Icon.Plus size={14}/>
        </span>
      </button>
      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.22 }}
            className="overflow-hidden"
          >
            <div className="px-6 pb-5 text-[13.5px] text-white/65 leading-relaxed border-t border-white/[0.04] pt-4">{a}</div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

window.Pricing = Pricing;
