// Pricing — 3-cycle toggle + 2 plan cards + display-only currency converter
// Accepts optional `data` (from CMS) and `lang` for i18n

// Display-only currency conversion — rates are approximate and for UX only.
// Billing always processes in MAD. Update rates periodically or swap for live API.
const CURRENCIES = [
  { code: 'MAD', symbol: 'MAD', rate: 1       },
  { code: 'USD', symbol: '$',   rate: 0.10     },
  { code: 'EUR', symbol: '€',   rate: 0.092    },
  { code: 'CAD', symbol: 'CA$', rate: 0.14     },
];

// Auto-detect currency from browser locale
function detectCurrency() {
  const loc = navigator.language || '';
  if (loc.startsWith('fr-FR') || loc.startsWith('fr-BE') || loc.startsWith('de') || loc.startsWith('es-ES') || loc.startsWith('it')) return 'EUR';
  if (loc.startsWith('en-CA') || loc.startsWith('fr-CA')) return 'CAD';
  if (loc.startsWith('en-US')) return 'USD';
  return 'MAD';
}

const BILLING = [
  { key: "monthly", tLabel: "pricing.monthly",    tSave: null           },
  { key: "quarter", tLabel: "pricing.threeMonths", tSave: "pricing.save10" },
  { key: "annual",  tLabel: "pricing.annual",      tSave: "pricing.save20" },
];

const PLANS_DEFAULT = [
  {
    tier: "Standard", tag: null,
    blurb: "For steady, ongoing design needs",
    prices: { monthly: 4499, quarter: 3999, annual: 2999 },
    features: ["1 active task at a time","Average delivery: 48–72 hours","Unlimited requests","All core design services included","Pause or resume anytime"],
    note: "Best for startups and small teams",
    cta: "Get Started", dark: false,
  },
  {
    tier: "Pro", tag: "Most Popular",
    blurb: "For fast-moving teams that need priority execution",
    prices: { monthly: 6999, quarter: 5499, annual: 4499 },
    features: ["2 active tasks at a time","Average delivery: 24–48 hours","Priority queue","Unlimited requests","All core design services included","Pause or resume anytime"],
    note: "Best for scaling teams and agencies",
    cta: "Get Started", dark: true,
  },
];

// ─── PricingCard ──────────────────────────────────────────────
const PricingCard = ({ tier, tag, blurb, prices, features, note, cta, dark, billing, lang, currency }) => {
  const scrollTo = (id) =>
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });

  return (
    <article className={"ag-pricing-card" + (dark ? " is-dark" : "") + (tag ? " is-featured" : "")}>
      <header className="ag-pricing-card__head">
        <div className="ag-pricing-card__tier-row">
          <span className="ag-pricing-card__tier">{tier}</span>
          {tag && <span className="ag-pricing-card__tag">{tag}</span>}
        </div>
        <span className="ag-pricing-card__price">
          <sup>{currency.symbol}</sup>{Math.round((prices[billing] || 0) * currency.rate).toLocaleString()}
          <span className="ag-pricing-card__per">/mo</span>
        </span>
        {billing !== "monthly" && (
          <span className="ag-pricing-card__billing-note">
            {t(billing === "quarter" ? "pricing.billedQ" : "pricing.billedA", lang)}
          </span>
        )}
      </header>
      <p className="ag-pricing-card__blurb">{blurb}</p>
      <ul className="ag-pricing-card__list">
        {features.map((f) => <ListTick key={f}>{f}</ListTick>)}
      </ul>
      {note && <p className="ag-pricing-card__note">— {note}</p>}
      <Button variant={dark ? "light" : "dark"} onClick={() => scrollTo("ag-section-contact")}>
        {cta}
      </Button>
    </article>
  );
};

// ─── Pricing ─────────────────────────────────────────────────
const Pricing = ({ data, lang }) => {
  const [billing,  setBilling]  = React.useState("monthly");
  const [currCode, setCurrCode] = React.useState(() => detectCurrency());
  const currency = CURRENCIES.find(c => c.code === currCode) || CURRENCIES[0];
  const scrollTo = (id) =>
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });

  // DB data always wins; PLANS_DEFAULT only when section absent from DB entirely
  const hasSection = data !== null && data !== undefined;
  const plans = hasSection
    ? (Array.isArray(data) ? data.map((p, idx) => ({
        tier:     p.tier || '',
        tag:      i18(p.tag, lang) || null,
        blurb:    i18(p.blurb, lang) || '',
        prices:   p.prices || { monthly: 0, quarter: 0, annual: 0 },
        features: i18(p.features, lang).split('\n').filter(Boolean),
        note:     i18(p.note, lang) || '',
        cta:      p.cta ? i18(p.cta.label, lang) || 'Get Started' : 'Get Started',
        dark:     idx > 0,
      })) : [])
    : PLANS_DEFAULT;

  return (
    <section className="ag-pricing" id="ag-section-pricing">
      <SectionHeading
        eyebrow="Pricing"
        sub="One subscription. Consistent, high-quality design. Delivered fast."
      >
        Simple, Scalable Design —<br/>Without the Overhead.
      </SectionHeading>

      <p className="ag-pricing__pause">Pause anytime. No contracts.</p>

      <div className="ag-pricing__controls">
        <select
          className="ag-pricing__currency-select"
          value={currCode}
          onChange={e => setCurrCode(e.target.value)}
          aria-label="Display currency"
        >
          {CURRENCIES.map(c => (
            <option key={c.code} value={c.code}>{c.code} ({c.symbol})</option>
          ))}
        </select>
        <p className="ag-pricing__currency-note">Display only — billing in MAD</p>
      </div>

      <div className="ag-pricing__toggle" role="tablist" aria-label="Billing period">
        {BILLING.map((b) => (
          <button
            key={b.key}
            type="button"
            role="tab"
            aria-selected={billing === b.key}
            className={"ag-pricing__toggle-opt" + (billing === b.key ? " is-on" : "")}
            onClick={() => setBilling(b.key)}
          >
            {t(b.tLabel, lang)}
            {b.tSave && (
              <span className={"ag-pricing__save" + (billing === b.key ? "" : " is-muted")}>
                {t(b.tSave, lang)}
              </span>
            )}
          </button>
        ))}
      </div>

      <div className="ag-pricing__grid">
        {plans.map((p) => (
          <PricingCard key={p.tier} {...p} billing={billing} lang={lang} currency={currency} />
        ))}
      </div>

      <div className="ag-pricing__footer">
        <div className="ag-pricing__footer-text">
          <p className="ag-pricing__footer-title">No surprises. Just consistent output.</p>
          <p className="ag-pricing__footer-sub">
            No contracts. No hidden fees. Just a reliable design partner.
          </p>
        </div>
        <a
          className="ag-pricing__footer-cta"
          onClick={() => scrollTo("ag-section-contact")}
        >
          Start today
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <line x1="5" y1="12" x2="19" y2="12"/>
            <polyline points="12,5 19,12 12,19"/>
          </svg>
        </a>
      </div>
    </section>
  );
};

window.Pricing = Pricing;
