/* global React */
const { useState, useEffect, useRef } = React;

// Single source of truth for outbound URLs. Mirror of URLS in app.jsx so
// pricing pages can stand alone without app.jsx loaded.
//
// Auth + signup paths are root-relative (per PR #580) so the same landing
// bundle works on prod (eoma.ai), preview, and any review-app deploy
// without forking the URL list. See sibling note in app.jsx.
//
// IMPORTANT: pricing values are duplicated in this file AND in
// supabase/migrations/*_seed_practice_plan.sql /
// *_set_canonical_plan_prices.sql. When you change a price, update BOTH:
//   (a) the SQL UPDATE on `public.plans` (or a new migration), AND
//   (b) the PRICES table below.
// Static landing HTML cannot read the canonical config at runtime, so we
// duplicate-with-intention rather than fetch-from-anon-API for SEO pages.
const PR_URLS = {
  login: "/login",
  signup: "/signup",
  audit: "mailto:info@eoma.ai?subject=Free%20AEO%20audit&body=Website%20URL%3A%20",
  apply: "mailto:info@eoma.ai?subject=Pro%20plan%20inquiry",
  applyEnterprise: "mailto:info@eoma.ai?subject=Enterprise%20plan%20inquiry",
  contact: "mailto:info@eoma.ai",
  signupStarter: "/signup?plan=starter",
  signupPractice: "/signup?plan=practice",
};

// ─── i18n dictionary ─────────────────────────────────────────────────
const PRICING_I18N = {
  en: {
    nav: {
      home: "Home",
      how: "How it works",
      platforms: "Platforms",
      features: "Features",
      faq: "FAQ",
      pricing: "Pricing",
      login: "Log in",
    },
    eyebrow: "AI visibility platform · GEO + AEO + Social",
    h1a: "ChatGPT does not recommend ",
    h1b: "your business.",
    h1c: " EOMA fixes it.",
    sub: "EOMA monitors how ChatGPT, Perplexity, Gemini, Claude, and Google AI Overview cite your brand, then ships the content, schema, and outreach moves to lift your visibility. You click approve.",
    ctaPrimary: "Get started",
    ctaSecondary: "See plans",
    ctaDemo: "Book a demo",
    trustLine: "Cancel anytime · No setup fees · Secured by iyzico",

    valEyebrow: "Why EOMA",
    val1H: "Replace the agency",
    val1B: "What 3 retainers do, EOMA does autonomously, at 1/10 the cost.",
    val2H: "Approve, don't author",
    val2B: "Agent generates blog posts, FAQ, schema fixes. You click once.",
    val3H: "All 4 LLMs",
    val3B: "Track ChatGPT, Perplexity, Gemini, Claude. Google AI Overviews coming Q3.",

    plansEyebrow: "Plans",
    plansHa: "Pick the plan that ",
    plansHb: "replaces your agency.",
    monthly: "Monthly",
    annual: "Annual",
    saveBadge: "save 2 months",
    perMo: "/mo",
    perYr: "/yr",
    billedAnnually: "Billed annually",
    mostPopular: "Most popular",

    starter: {
      tag: "Analysis + recommendations. No agent execution.",
      cta: "Get started",
      small: "Monthly · cancel anytime",
    },
    practice: {
      tag: "Mid-tier visibility + agent execution for established practices and boutique brands.",
      cta: "Get started",
      small: "Monthly · cancel anytime",
    },
    enterprise: {
      tag: "Custom corpus, manual high-volume onboarding, dedicated support.",
      priceLabel: "Custom",
      priceSub: "Tailored to your scale",
      cta: "Talk to sales",
      small: "We respond within 24h",
    },

    sectionService: "Service level",
    sectionCoverage: "Coverage",
    sectionReports: "Reports & support",
    addOnLabel: "Social Management",
    addOnPrice: "+$39/mo",
    addOnDesc:
      "Compose, schedule, and publish across X, Instagram, TikTok, LinkedIn, YouTube, Threads. Available as an add-on on any plan.",

    faqEyebrow: "FAQ",
    faqHa: "Questions, ",
    faqHb: "answered.",

    finalEyebrow: "Start now",
    finalH: "Make your brand AI-native. Start today.",
    finalCtaTrial: "Get started",
    finalCtaEnterprise: "Talk to sales",
    finalDisclaimer: "Cancel anytime · No setup fees · Secured by iyzico",
  },
};

// ─── Pricing data ────────────────────────────────────────────────────
// Enterprise tier is custom-priced; handled separately in the tier card.
//
// IMPORTANT: these prices duplicate the canonical values in
// supabase/migrations/*_plan_tier_seed_and_rls.sql and
// supabase/migrations/*_seed_practice_plan.sql. Static landing HTML cannot
// read the DB at runtime, so we duplicate-with-intention. When the founder
// changes a price, update BOTH:
//   (a) UPDATE public.plans SET monthly_price_cents = ... WHERE id = '...',
//   (b) the matching value in this PRICES table.
const PRICES = {
  USD: {
    sym: "$",
    before: true,
    starter: { mo: 79, yr: 790 },
    practice: { mo: 229, yr: 2290 },
  },
  EUR: {
    sym: "€",
    before: true,
    starter: { mo: 73, yr: 730 },
    practice: { mo: 213, yr: 2130 },
  },
  TRY: {
    sym: "₺",
    before: true,
    starter: { mo: 2390, yr: 23900 },
    practice: { mo: 6990, yr: 69900 },
  },
};
function fmtPrice(amount, code) {
  const p = PRICES[code];
  // Format with thousands separators per locale
  const sep = code === "TRY" || code === "EUR" ? "." : ",";
  const str = amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, sep);
  return `${p.sym}${str}`;
}

// ─── Feature rows definition ─────────────────────────────────────────
// Each row: { label_en, label_tr, tip_en, tip_tr, vals: [starter, practice, enterprise] }
// Use "✓" / "-" / strings.
// (Growth was retired from sale 2026-05-24 — its column was removed here.)
//
// Architecture per docs/superpowers/specs/2026-05-05-subscription-entitlements-architecture-design.md:
// EOMA paket farkı = "service level" (frequency + depth), aksiyon sayma değil.
// Pillars: AEO prompts tracked / brand profile depth / social
// listening cadence / reports / support. Mirrored 1:1 with PlanUsageSettings.jsx
// in-dashboard plan card so the user sees the same vocabulary in-app.
const FEATURE_GROUPS = [
  {
    titleKey: "sectionService",
    icon: "",
    rows: [
      {
        l_en: "Tracked AI prompts",
        t_en: "Queries we run through every AI model on each refresh, like 'best CRM for startups'. Lifetime cap per workspace.",
        v: ["25", "50", "500+"],
      },
      {
        l_en: "Brand profile depth",
        t_en: "Basic = entity-level extraction from your site. Deep AI training = competitor benchmarks, voice analysis, vertical context fed to the agent.",
        v: ["Basic", "Deep AI training", "Deep + custom corpus"],
      },
      {
        l_en: "Social listening refresh",
        t_en: "How often we re-scrape competitor social activity, brand mentions, and surfaced conversations.",
        v: ["Once at onboarding", "Weekly", "Daily"],
      },
      {
        l_en: "Agent execution",
        t_en: "The agent prepares content, schema, and outreach moves for your one-click approval. Starter is analysis only.",
        v: ["Recommendations only", "✓", "✓ + custom"],
      },
    ],
  },
  {
    titleKey: "sectionCoverage",
    icon: "",
    rows: [
      {
        l_en: "AI engines monitored",
        t_en: "Generative engines whose answers we sweep for your brand mentions and citations.",
        v: [
          "ChatGPT · Perplexity · Gemini · Claude",
          "ChatGPT · Perplexity · Gemini · Claude",
          "ChatGPT · Perplexity · Gemini · Claude + AI Overviews",
        ],
      },
      {
        l_en: "Social platforms",
        t_en: "Public mentions and conversations we ingest for your brand and competitors.",
        v: [
          "X · Reddit · TikTok · YouTube · Instagram",
          "X · Reddit · TikTok · YouTube · Instagram",
          "X · Reddit · TikTok · YouTube · Instagram",
        ],
      },
      {
        l_en: "Brand workspaces",
        t_en: "How many separate brands you can run inside one EOMA account.",
        v: ["1", "1", "Custom"],
      },
      {
        l_en: "Integrations",
        t_en: "Wire EOMA to your CMS and analytics stack so the agent can publish and read context.",
        v: ["GA4 · GSC", "GA4 · GSC · WordPress · Webflow", "All + custom API"],
      },
    ],
  },
  {
    titleKey: "sectionReports",
    icon: "",
    rows: [
      {
        l_en: "Reports cadence",
        t_en: "PDF / shareable summary of your AI visibility, citations, and competitive position.",
        v: ["-", "Monthly", "On demand + white-label"],
      },
      {
        l_en: "Support",
        t_en: "How fast we respond and through which channels.",
        v: ["Email (48h)", "Email (24h)", "Priority + scheduled call"],
      },
      {
        l_en: "Onboarding",
        t_en: "Initial setup. Agent-led on Starter and Practice. Enterprise gets manual, high-volume onboarding with a human.",
        v: ["Agent-led", "Agent-led", "Manual + dedicated support"],
      },
    ],
  },
];

// ─── FAQ items ───────────────────────────────────────────────────────
const FAQ_PRICING = {
  en: [
    {
      q: "What's a 'tracked prompt'?",
      a: "A query you want to monitor, like 'best CRM for startups' or 'running shoes for flat feet.' EOMA runs each prompt through your LLMs on your refresh schedule, then tells you if and how your brand appears.",
    },
    {
      q: "How does billing work?",
      a: "Pick a plan, pay monthly or annual via iyzico (cards, BKM Express, supported wallets). Your card is charged on signup. Cancel any time from your settings, no commitment.",
    },
    {
      q: "Can I switch plans?",
      a: "Yes. Upgrade or downgrade anytime from your settings. Annual plans pro-rate.",
    },
    {
      q: "Why isn't there a free plan?",
      a: "Each EOMA user runs real LLM queries, scrapes competitor data, and consumes API tokens. A free tier would burn cash without serving you well. Starter at $79/mo is the entry point.",
    },
    {
      q: "What if I exceed my plan's limits?",
      a: "We notify you at 80% of any cap. Past 100%, the action queues until the next cycle, or you can upgrade. Your existing data stays intact.",
    },
    {
      q: "Does the agent publish to my website automatically?",
      a: "No, and that's intentional. The agent prepares every blog post, FAQ entry, and technical fix. You review and approve with one click. You stay in control.",
    },
    {
      q: "Which LLMs do you cover?",
      a: "ChatGPT, Perplexity, Gemini, and Claude. Google AI Overviews coverage ships in Q3 2026.",
    },
    {
      q: "Can I get a custom plan?",
      a: "Yes. Enterprise covers custom prompt corpus, SLA, SSO, and multi-language support. Starts at $3,200/mo. Talk to us.",
    },
  ],
};

// ─── Tooltip component ───────────────────────────────────────────────
function InfoTip({ text }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const onDocClick = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    };
    const onKey = (e) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("click", onDocClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("click", onDocClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);
  return (
    <span
      ref={ref}
      className={`tip ${open ? "is-open" : ""}`}
      tabIndex={0}
      role="button"
      aria-label={text}
      aria-expanded={open}
      onClick={(e) => {
        e.stopPropagation();
        setOpen((v) => !v);
      }}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          setOpen((v) => !v);
        }
      }}
    >
      <span className="tip-i" aria-hidden="true">
        ⓘ
      </span>
      <span className="tip-bubble" role="tooltip">
        {text}
      </span>
    </span>
  );
}

// ─── Pricing Nav (reuses landing styles, adds lang switch) ───────────
function PricingNav({ lang, t, landingHref, onDemoClick }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? "is-scrolled" : ""}`}>
      <a className="nav-brand" href={landingHref}>
        <Logomark width={28} />
        eoma
      </a>
      <div className="nav-links">
        <a className="nav-link" href={landingHref}>
          {t.nav.home}
        </a>
        <a className="nav-link" href={`${landingHref}#how`}>
          {t.nav.how}
        </a>
        <a className="nav-link" href={`${landingHref}#platforms`}>
          {t.nav.platforms}
        </a>
        <a className="nav-link is-active" href="#top" aria-current="page">
          {t.nav.pricing}
        </a>
        <a className="nav-link" href="#faq">
          {t.nav.faq}
        </a>
      </div>
      <div className="nav-actions">
        <a className="btn btn-ghost" href={PR_URLS.login}>
          {t.nav.login}
        </a>
        <button type="button" className="btn btn-ghost" onClick={() => onDemoClick("pricing_nav")}>
          {t.ctaDemo}
        </button>
        <a className="btn btn-primary" href={PR_URLS.signup}>
          <LogoBadge size={36} />
          {t.ctaPrimary}
        </a>
      </div>
    </nav>
  );
}

// ─── Hero ────────────────────────────────────────────────────────────
function PricingHero({ t, lang }) {
  return (
    <section className="pr-hero" id="top">
      <div className="wrap">
        <Reveal className="pr-hero-inner">
          <span className="eyebrow">
            <span className="dot"></span>
            {t.eyebrow}
          </span>
          <h1 className="pr-h1">
            {t.h1a}
            <span className="accent">{t.h1b}</span>
            {t.h1c}
          </h1>
          <p className="pr-sub">{t.sub}</p>
          <div className="pr-hero-ctas">
            <a className="btn btn-primary btn-lg" href={PR_URLS.signupPractice}>
              <LogoBadge size={44} />
              {t.ctaPrimary}
            </a>
            <a className="btn btn-ghost btn-lg" href="#plans">
              {t.ctaSecondary}
            </a>
          </div>
          <div className="pr-trust">{t.trustLine}</div>
          <IyzicoBadge />
        </Reveal>
      </div>
    </section>
  );
}

// ─── iyzico checkout badge (for use near pricing CTAs) ───────────────
function IyzicoBadge() {
  const src = "/landing/design-system/assets/iyzico/pay-with-iyzico-en.svg";
  const alt = "Pay with iyzico";
  return (
    <div className="pr-iyzico-badge" aria-label={alt}>
      <img src={src} alt={alt} loading="lazy" />
    </div>
  );
}

// ─── Value Anchor strip ──────────────────────────────────────────────
function ValueStrip({ t }) {
  const cols = [
    { icon: <ValIcon name="agency" />, h: t.val1H, b: t.val1B },
    { icon: <ValIcon name="approve" />, h: t.val2H, b: t.val2B },
    { icon: <ValIcon name="llm" />, h: t.val3H, b: t.val3B },
  ];
  return (
    <section className="pr-value">
      <div className="wrap">
        <Reveal className="pr-value-grid">
          {cols.map((c, i) => (
            <div key={i} className="pr-value-col">
              <div className="pr-value-icon">{c.icon}</div>
              <h3 className="pr-value-h">{c.h}</h3>
              <p className="pr-value-b">{c.b}</p>
            </div>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

function ValIcon({ name }) {
  const stroke = "var(--ink)";
  if (name === "agency") {
    return (
      <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
        <rect x="4" y="6" width="20" height="16" rx="2" stroke={stroke} strokeWidth="1.5" />
        <path d="M9 12h10M9 16h6" stroke={stroke} strokeWidth="1.5" strokeLinecap="round" />
        <path
          d="M19 4l3 3-3 3"
          stroke="var(--hue-coral)"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    );
  }
  if (name === "approve") {
    return (
      <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
        <circle cx="14" cy="14" r="10" stroke={stroke} strokeWidth="1.5" />
        <path
          d="M9 14l3.5 3.5L20 10"
          stroke="var(--hue-mint)"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    );
  }
  return (
    <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
      <circle cx="7" cy="9" r="3" stroke={stroke} strokeWidth="1.5" />
      <circle cx="21" cy="9" r="3" stroke={stroke} strokeWidth="1.5" />
      <circle cx="7" cy="20" r="3" stroke={stroke} strokeWidth="1.5" />
      <circle
        cx="21"
        cy="20"
        r="3"
        stroke="var(--hue-yellow)"
        strokeWidth="1.5"
        fill="var(--hue-yellow)"
        fillOpacity="0.3"
      />
    </svg>
  );
}

// ─── Pricing Controls + Tier Cards + Comparison Table ────────────────
function PricingPlans({ t, lang }) {
  const [period, setPeriodState] = useState(() => {
    return localStorage.getItem("eoma_pricing_period") || "monthly";
  });
  // Currency locked to USD; founder decision (2026-05-06): single
  // billing currency keeps the contract simple, iyzico/Stripe accept
  // USD globally including from TR cards. The PRICES table still
  // contains EUR/TRY for reference / future re-introduction.
  const currency = "USD";
  const setPeriod = (p) => {
    setPeriodState(p);
    localStorage.setItem("eoma_pricing_period", p);
  };

  // Mobile compare-table: only one tier column visible at a time.
  // Default to "practice" (most popular). 0=starter, 1=practice, 2=enterprise.
  const [mobileTier, setMobileTier] = useState(1);

  const isAnnual = period === "annual";

  // Monthly-displayed pricing in both periods.
  // Monthly toggle: show the headline monthly price.
  // Annual toggle: show monthly-equivalent (yearly ÷ 12, floor) with the
  // headline monthly price struck through above it. We never render the
  // yearly total as a number; founder decision (2026-05-10).
  const headlineMonthly = (tier) => fmtPrice(PRICES[currency][tier].mo, currency);
  const annualMonthlyEquivalent = (tier) =>
    fmtPrice(Math.floor(PRICES[currency][tier].yr / 12), currency);
  const perLabel = t.perMo;

  const tiers = [
    {
      id: "starter",
      name: "Starter",
      popular: false,
      ...t.starter,
      href: PR_URLS.signupStarter,
    },
    {
      id: "practice",
      name: "Practice",
      popular: true,
      ...t.practice,
      href: PR_URLS.signupPractice,
    },
    // Growth retired from sale 2026-05-24 — removed as a public checkout tier.
    {
      id: "enterprise",
      name: "Enterprise",
      popular: false,
      custom: true,
      ...t.enterprise,
      href: PR_URLS.applyEnterprise,
    },
  ];

  return (
    <section className="pr-plans" id="plans">
      <div className="wrap">
        <Reveal className="pr-plans-head">
          <span className="eyebrow">
            <span className="dot"></span>
            {t.plansEyebrow}
          </span>
          <TwoTone
            parts={[
              { tone: "gray", text: t.plansHa },
              { tone: "navy", text: t.plansHb },
            ]}
          />
        </Reveal>

        <div className="pr-controls">
          <div className="pr-toggle" role="tablist" aria-label="Billing period">
            <button
              role="tab"
              aria-selected={!isAnnual}
              className={!isAnnual ? "is-active" : ""}
              onClick={() => setPeriod("monthly")}
            >
              {t.monthly}
            </button>
            <button
              role="tab"
              aria-selected={isAnnual}
              className={isAnnual ? "is-active" : ""}
              onClick={() => setPeriod("annual")}
            >
              {t.annual} <span className="pr-toggle-save">· {t.saveBadge}</span>
            </button>
          </div>
          {/* Currency switcher removed; locked to USD. */}
        </div>

        {/* Tier cards */}
        <div className="pr-tiers">
          {tiers.map((tier) => (
            <div
              key={tier.id}
              className={`pr-tier ${tier.popular ? "is-popular" : ""} ${tier.custom ? "is-custom" : ""}`}
            >
              {tier.popular && <span className="pr-popular-badge">{t.mostPopular}</span>}
              <div className="pr-tier-name">{tier.name}</div>
              <div className="pr-tier-tag">{tier.tag}</div>
              <div className="pr-tier-price">
                {tier.custom ? (
                  <span className="pr-tier-price-num pr-tier-price-custom">{tier.priceLabel}</span>
                ) : isAnnual ? (
                  <>
                    <span className="pr-tier-price-was" aria-label="Monthly list price">
                      {headlineMonthly(tier.id)}
                      <span className="pr-tier-price-was-per">{t.perMo}</span>
                    </span>
                    <span className="pr-tier-price-num">{annualMonthlyEquivalent(tier.id)}</span>
                    <span className="pr-tier-price-per">{perLabel}</span>
                  </>
                ) : (
                  <>
                    <span className="pr-tier-price-num">{headlineMonthly(tier.id)}</span>
                    <span className="pr-tier-price-per">{perLabel}</span>
                  </>
                )}
              </div>
              {tier.custom && tier.priceSub && (
                <div className="pr-tier-price-sub">{tier.priceSub}</div>
              )}
              {!tier.custom && isAnnual && (
                <div className="pr-tier-price-sub">{t.billedAnnually}</div>
              )}
              <a
                className={`btn ${tier.popular ? "btn-primary" : "btn-ghost"} btn-lg pr-tier-cta`}
                href={tier.href}
              >
                {tier.cta}
              </a>
              <div className="pr-tier-small">{tier.small}</div>
            </div>
          ))}
        </div>

        {/* Mobile tier picker; only visible on small screens via CSS */}
        <div className="pr-compare-picker" role="tablist" aria-label="Compared plan">
          {tiers.map((tier, i) => (
            <button
              key={tier.id}
              role="tab"
              aria-selected={mobileTier === i}
              className={mobileTier === i ? "is-active" : ""}
              onClick={() => setMobileTier(i)}
            >
              {tier.name}
            </button>
          ))}
        </div>

        {/* Comparison table */}
        <div className="pr-compare" data-mobile-tier={mobileTier}>
          <div className="pr-compare-head">
            <div className="pr-compare-h pr-compare-feature"></div>
            {tiers.map((tier, i) => (
              <div
                key={tier.id}
                className={`pr-compare-h ${tier.popular ? "is-popular" : ""} ${mobileTier === i ? "is-mobile-active" : ""}`}
              >
                {tier.name}
              </div>
            ))}
          </div>

          {FEATURE_GROUPS.map((g, gi) => (
            <FeatureGroup key={gi} group={g} t={t} lang={lang} mobileTier={mobileTier} />
          ))}
        </div>

        {/* Social Management add-on band; works on top of any plan */}
        <div className="pr-addon">
          <div className="pr-addon-left">
            <div className="pr-addon-label">{t.addOnLabel}</div>
            <div className="pr-addon-desc">{t.addOnDesc}</div>
          </div>
          <div className="pr-addon-price">{t.addOnPrice}</div>
        </div>
      </div>
    </section>
  );
}

function FeatureGroup({ group, t, lang, mobileTier = 1 }) {
  const [open, setOpen] = useState(true);
  return (
    <div className={`pr-group ${open ? "is-open" : ""}`}>
      <button className="pr-group-head" onClick={() => setOpen(!open)} aria-expanded={open}>
        {group.icon ? <span className="pr-group-icon">{group.icon}</span> : null}
        <span className="pr-group-title">{t[group.titleKey]}</span>
        <span className="pr-group-toggle">{open ? "−" : "+"}</span>
      </button>
      {open && (
        <div className="pr-group-body">
          {group.rows.map((r, ri) => {
            const label = r.l_en;
            const tip = r.t_en;
            const vals = r.v;
            return (
              <div key={ri} className="pr-row">
                <div className="pr-row-l">
                  <span>{label}</span>
                  <InfoTip text={tip} />
                </div>
                {vals.map((v, vi) => (
                  <div
                    key={vi}
                    className={`pr-row-v ${vi === 1 ? "is-popular-col" : ""} ${mobileTier === vi ? "is-mobile-active" : ""}`}
                  >
                    <span className={v === "-" ? "muted" : v === "✓" ? "check" : ""}>{v}</span>
                  </div>
                ))}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ─── FAQ ─────────────────────────────────────────────────────────────
function PricingFAQ({ t, lang }) {
  const [open, setOpen] = useState(0);
  const items = FAQ_PRICING[lang];
  return (
    <section className="faq pr-faq" id="faq">
      <div className="wrap">
        <Reveal className="faq-head">
          <span className="eyebrow">
            <span className="dot"></span>
            {t.faqEyebrow}
          </span>
          <TwoTone
            parts={[
              { tone: "gray", text: t.faqHa },
              { tone: "navy", text: t.faqHb },
            ]}
          />
        </Reveal>
        <div className="faq-list">
          {items.map((it, i) => (
            <div key={i} className={`faq-item ${open === i ? "is-open" : ""}`}>
              <button
                className="faq-q"
                onClick={() => setOpen(open === i ? -1 : i)}
                aria-expanded={open === i}
              >
                <span>{it.q}</span>
                <span className="toggle">+</span>
              </button>
              <div className="faq-a" style={{ maxHeight: open === i ? 360 : 0 }}>
                <div className="faq-a-inner">{it.a}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── Final CTA block + footer ────────────────────────────────────────
function PricingFinal({ t, lang, landingHref, onDemoClick }) {
  return (
    <section className="final pr-final">
      <div className="final-clouds">
        <div className="hero-cloud c1"></div>
        <div className="hero-cloud c2"></div>
        <div className="hero-cloud c3"></div>
      </div>
      <div className="final-tokens">
        <div className="token t1">SEO</div>
        <div className="token t2">GEO</div>
        <div className="token t3" style={{ left: "60%", bottom: "40%" }}>
          $
        </div>
      </div>

      <div className="final-top">
        <div className="final-cta pr-final-cta">
          <span className="eyebrow frost">
            <span className="dot"></span>
            {t.finalEyebrow}
          </span>
          <h2>{t.finalH}</h2>
          <div className="pr-final-actions">
            <a className="btn btn-primary btn-lg" href={PR_URLS.signupPractice}>
              <LogoBadge size={44} />
              {t.finalCtaTrial}
            </a>
            <button
              type="button"
              className="btn btn-ghost-light btn-lg"
              onClick={() => onDemoClick("pricing_final")}
            >
              {t.ctaDemo}
            </button>
            <a className="btn btn-ghost-light btn-lg" href={PR_URLS.applyEnterprise}>
              {t.finalCtaEnterprise}
            </a>
          </div>
          <div className="pr-final-disclaimer">{t.finalDisclaimer}</div>
        </div>
        <div className="footer-cols">
          <div className="footer-col">
            <h4>Product</h4>
            <ul>
              <li>
                <a href={`${landingHref}#how`}>{t.nav.how}</a>
              </li>
              <li>
                <a href={`${landingHref}#platforms`}>{t.nav.platforms}</a>
              </li>
              <li>
                <a href="#top" aria-current="page">
                  {t.nav.pricing}
                </a>
              </li>
              <li>
                <a href="#faq">{t.nav.faq}</a>
              </li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Company</h4>
            <ul>
              <li>
                <a href="mailto:info@eoma.ai">Contact</a>
              </li>
              <li>
                <a href="/privacy">Privacy Policy</a>
              </li>
              <li>
                <a href="/terms">Terms of Use</a>
              </li>
            </ul>
          </div>
        </div>
      </div>

      <div className="iyzico-band" aria-label="Pay with iyzico">
        <img
          src="/landing/design-system/assets/iyzico/logo-band-colored.svg"
          alt="Payment methods via iyzico"
          loading="lazy"
        />
      </div>

      <div className="final-bottom">
        <span>© 2026 EOMA · All rights reserved</span>
        <div className="socials">
          <a className="social-pill" href="#">
            X
          </a>
          <a className="social-pill" href="#">
            Ig
          </a>
          <a className="social-pill" href="#">
            Li
          </a>
          <a className="social-pill" href="#">
            Yt
          </a>
        </div>
      </div>
    </section>
  );
}

// ─── Sticky mobile CTA ───────────────────────────────────────────────
function StickyCTA({ t }) {
  const [show, setShow] = useState(false);
  useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 600);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <div className={`pr-sticky-cta ${show ? "is-visible" : ""}`} aria-hidden={!show}>
      <a className="btn btn-primary btn-lg" href={PR_URLS.signupPractice} tabIndex={show ? 0 : -1}>
        {t.finalCtaTrial}
      </a>
    </div>
  );
}

// ─── Main wrapper ────────────────────────────────────────────────────
function PricingApp({ landingHref = "/" } = {}) {
  // English-only landing — `lang` prop ignored; kept default for HTML mount.
  const lang = "en";
  const t = PRICING_I18N.en;

  // Demo modal state. `source` identifies which CTA opened the modal so
  // conversions attribute to specific pricing-page CTAs in GA4. The modal
  // itself ships from demo-modal.jsx (window.DemoBookingModal), loaded by
  // pricing.html before this bundle.
  const [demoOpen, setDemoOpen] = useState(false);
  const [demoSource, setDemoSource] = useState("");
  const openDemo = (source) => {
    setDemoSource(source);
    setDemoOpen(true);
  };
  const closeDemo = () => setDemoOpen(false);

  return (
    <>
      <PricingNav lang={lang} t={t} landingHref={landingHref} onDemoClick={openDemo} />
      <PricingHero t={t} lang={lang} />
      <ValueStrip t={t} />
      <PricingPlans t={t} lang={lang} />
      <PricingFAQ t={t} lang={lang} />
      <PricingFinal t={t} lang={lang} landingHref={landingHref} onDemoClick={openDemo} />
      <StickyCTA t={t} />

      {typeof window !== "undefined" && window.DemoBookingModal && (
        <window.DemoBookingModal
          open={demoOpen}
          onClose={closeDemo}
          source={demoSource}
          lang={lang}
        />
      )}
    </>
  );
}

Object.assign(window, { PricingApp });
