/* pricing.jsx — the ONE pricing implementation.
 *
 * Pricing is no longer a page. It is a set of sections that live inside the
 * public Enterprise sales journey (globly.jsx → MiraBusinessScreen), so a
 * visitor never leaves Enterprise to find out what it costs.
 *
 * Everything renders from window.MIRA_PLANS. No price, seat count, limit or
 * entitlement is written here — if a number looks wrong, fix pricing-config.js.
 *
 * Exports
 *   window.MiraPricing = { Section, SouthAsiaAccess, SponsoredAccess, FAQ }
 *   window.MiraPricingScreen — thin standalone wrapper. #/pricing redirects
 *     into Enterprise wherever the Enterprise page is available; on production
 *     Enterprise is still hostname-gated, so this wrapper renders the SAME
 *     Section rather than leaving #/pricing a dead link. Same component, same
 *     data — not a second pricing experience.
 *
 * There is no checkout. Paid plans route to the existing early-access contact
 * flow with plan context, and say so plainly. No button implies a payment will
 * start.
 */
(function () {
  'use strict';
  var h = React.createElement;

  // ── Billing toggle. Annual is the default everywhere it is mounted. ───────
  function Toggle(p) {
    return h('div', { className: 'pr-toggle', role: 'group', 'aria-label': 'Billing period' },
      h('button', {
        className: 'pr-toggle-b' + (p.annual ? ' on' : ''), 'aria-pressed': p.annual,
        onClick: function () { p.set(true); },
      }, 'Annual'),
      h('button', {
        className: 'pr-toggle-b' + (!p.annual ? ' on' : ''), 'aria-pressed': !p.annual,
        onClick: function () { p.set(false); },
      }, 'Monthly'));
  }

  // ── Plan card ────────────────────────────────────────────────────────────
  // Deliberately short (§12): who it is for, the price, the seats, the main
  // reason to upgrade, and ~6 high-value lines. The full entitlement detail
  // lives in the comparison table, not in the card.
  function PlanCard(p) {
    var M = window.MIRA_PLANS, plan = p.plan, annual = p.annual;
    var isFree = plan.monthlyPrice === 0;
    var price, sub;
    if (isFree) { price = M.money(0); sub = 'free forever'; }
    else if (annual) {
      price = M.money(plan.annualMonthlyEquivalent);
      sub = 'per month equivalent · ' + M.money(plan.annualTotal) + ' billed annually';
    } else { price = M.money(plan.monthlyPrice); sub = 'per month · billed monthly'; }

    return h('div', {
      className: 'pr-card' + (plan.highlighted ? ' pr-card--hi' : '') +
        (p.selected ? ' pr-card--sel' : ''),
    },
      plan.badge ? h('div', { className: 'pr-badge' }, plan.badge) : null,
      h('div', { className: 'pr-card-h' },
        h('h3', { className: 'pr-card-n' }, plan.name),
        h('p', { className: 'pr-card-t' }, 'For ' + plan.targetCustomer.charAt(0).toLowerCase() + plan.targetCustomer.slice(1))),
      h('div', { className: 'pr-price' },
        h('span', { className: 'pr-price-v' }, price),
        h('span', { className: 'pr-price-s' }, sub)),
      h('div', { className: 'pr-users' },
        plan.usersIncluded === M.CUSTOM ? 'Custom users' :
          plan.usersIncluded + (plan.usersIncluded === 1 ? ' user' : ' users') + ' included'),
      h('p', { className: 'pr-mainval' },
        h('span', { className: 'pr-mainval-k' }, 'Main value'), plan.mainValue),
      h('ul', { className: 'pr-feats' }, plan.coreFeatures.map(function (f, i) {
        return h('li', { key: i }, h('span', { className: 'pr-tick' }, '✓'), f);
      })),
      h('div', { className: 'pr-ctas' },
        h('a', {
          className: 'pr-cta' + (plan.highlighted ? ' pr-cta--primary' : ''),
          href: plan.ctaRoute,
          'data-plan': plan.id,
        }, plan.ctaLabel)),
      !plan.selfServiceAvailable
        ? h('p', { className: 'pr-note' }, 'No card required. Early access, not a subscription.')
        : null);
  }

  // ── Enterprise: a wider block, never a cramped fifth column, never a
  //    monthly price (§13). ─────────────────────────────────────────────────
  function EnterpriseBlock() {
    var M = window.MIRA_PLANS, ent = M.byId('enterprise');
    return h('section', { className: 'pr-ent', id: 'enterprise-plan' },
      h('div', { className: 'pr-ent-l' },
        h('h3', { className: 'pr-h2' }, ent.name),
        h('p', { className: 'pr-ent-p' },
          'For multi-country organisations that need central oversight without taking control away from local teams.'),
        h('ul', { className: 'pr-ent-f' }, ent.coreFeatures.map(function (f, i) {
          return h('li', { key: i }, h('span', { className: 'pr-tick' }, '✓'), f);
        }))),
      h('div', { className: 'pr-ent-r' },
        h('div', { className: 'pr-price-v' }, 'From ' + M.money(ent.annualFrom) + '/year'),
        h('div', { className: 'pr-price-s' }, 'annual contract · invoice available'),
        h('a', { className: 'pr-cta pr-cta--primary', href: ent.ctaRoute }, ent.ctaLabel),
        h('a', { className: 'pr-cta pr-cta--ghost', href: ent.secondaryCtaRoute }, ent.secondaryCtaLabel)));
  }

  // ── Full entitlement comparison, driven by MIRA_PLANS.comparison ─────────
  function Comparison() {
    var M = window.MIRA_PLANS;
    var plans = M.plans;
    return h('div', { className: 'pr-cmp-wrap' },
      h('table', { className: 'pr-cmp' },
        h('thead', null, h('tr', null,
          h('th', null, 'Feature'),
          plans.map(function (pl) { return h('th', { key: pl.id }, pl.name); }))),
        h('tbody', null, M.comparison.map(function (grp) {
          return [
            h('tr', { key: grp.group, className: 'pr-cmp-grp' },
              h('td', { colSpan: plans.length + 1 }, grp.group)),
          ].concat(grp.rows.map(function (row) {
            return h('tr', { key: grp.group + row.key },
              h('td', { className: 'pr-cmp-l' }, row.label),
              plans.map(function (pl) {
                return h('td', { key: pl.id, className: 'pr-cmp-c' }, M.cell(pl.entitlements[row.key]));
              }));
          }));
        }))));
  }

  // ── The pricing section as mounted inside Enterprise ─────────────────────
  // props: bridge (string|null) — the contextual line that connects the demo
  //        to the plans; selectedPlan (id|null) — plan context carried in from
  //        a #/pricing?plan=… link.
  function Section(props) {
    props = props || {};
    var M = window.MIRA_PLANS;
    var aS = React.useState(true); var annual = aS[0], setAnnual = aS[1];
    var cS = React.useState(false); var showCmp = cS[0], setShowCmp = cS[1];

    return h('section', { className: 'pr-scope pr-section', id: 'pricing' },
      props.bridge ? h('p', { className: 'pr-bridge' }, props.bridge) : null,
      h('div', { className: 'pr-sec-hd' },
        h('h2', { className: 'pr-h1' }, 'Choose the level that fits your team'),
        h('p', { className: 'pr-lede' },
          'Start free, then add the workflow and collaboration your grant team needs.'),
        h(Toggle, { annual: annual, set: setAnnual }),
        h('p', { className: 'pr-save' }, 'Save approximately 20% with annual billing')),

      h('div', { className: 'pr-cards' },
        M.plans.filter(function (p) { return p.id !== 'enterprise'; }).map(function (p) {
          return h(PlanCard, {
            key: p.id, plan: p, annual: annual,
            selected: props.selectedPlan === p.id,
          });
        })),

      h(EnterpriseBlock),

      h('div', { className: 'pr-cmp-s' },
        h('button', {
          className: 'pr-cmp-toggle', 'aria-expanded': showCmp, 'aria-controls': 'pr-cmp-panel',
          onClick: function () { setShowCmp(!showCmp); },
        }, showCmp ? 'Hide full comparison' : 'Compare all features',
          h('span', { className: 'pr-cmp-chev', 'aria-hidden': 'true' }, showCmp ? '▲' : '▼')),
        showCmp ? h('div', { id: 'pr-cmp-panel' }, h(Comparison)) : null));
  }

  // ── South Asia Access — visually lighter than the plan cards (§16) ───────
  function SouthAsiaAccess() {
    return h('section', { className: 'pr-scope pr-access-s', id: 'access' },
      h('div', { className: 'pr-access-c' },
        h('h2', { className: 'pr-h2' }, 'South Asia Access'),
        h('p', null, 'Independent local NGOs may qualify for reduced pricing through our verified access programme.'),
        h('ul', { className: 'pr-access-l' },
          h('li', null, '25% support'),
          h('li', null, '40% support'),
          h('li', null, 'Up to 50% in exceptional cases'),
          h('li', null, 'Sponsored access, where a partner funds the licence')),
        h('p', { className: 'pr-muted' },
          'Eligibility may consider country of registration, independent local ownership, annual operating budget, organisation size, parent organisation and nonprofit status. Country offices of large international organisations are normally handled through NGO Pro or Enterprise.'),
        h('a', { className: 'pr-cta pr-cta--primary', href: '#/business?type=south-asia-access' }, 'Apply for access')));
  }

  // ── Sponsored access — compact block for donors and networks (§17) ───────
  function SponsoredAccess() {
    return h('section', { className: 'pr-scope pr-sponsor', id: 'sponsored' },
      h('div', { className: 'pr-sponsor-in' },
        h('div', null,
          h('h2', { className: 'pr-h2' }, 'Fund access for partner organisations'),
          h('p', null, 'Provide Mira access to selected local organisations through sponsored licences.'),
          h('p', { className: 'pr-muted' },
            'For donors, foundations, NGO networks and Enterprise customers. A sponsor never sees a recipient organisation’s private grant data.')),
        h('a', { className: 'pr-cta', href: '#/business?type=sponsored-access' }, 'Discuss sponsored access')));
  }

  // ── Pricing questions, merged into the single Enterprise FAQ (§19) ───────
  var FAQ = [
    ['Is there a free plan?', 'Yes. Community is free for one user, with limited monthly searches and up to five active shortlisted grants.'],
    ['Can local South Asian NGOs receive reduced pricing?', 'Independent local NGOs may qualify through the verified South Asia Access programme. Eligibility is reviewed individually.'],
    ['Can a large INGO use discounted local pricing?', 'No. Country offices of large international organisations are normally handled through NGO Pro or Enterprise.'],
    ['Can a donor sponsor access?', 'Yes. Foundations, donors and networks can fund access for selected partner organisations. Arrangements are handled through sales.'],
    ['Can we pay annually?', 'Yes. Annual billing is available on all three paid NGO plans and saves roughly 20% against monthly. Enterprise is annual only.'],
    ['Can we pay by invoice?', 'Annual invoice arrangements are available for approved NGO Pro and Enterprise customers through sales.'],
    ['Is pricing based on grants won?', 'No. There are no success fees and no commission on any grant you receive.'],
    ['What happens when billing launches?', 'Early-access customers will receive plan and billing details before any paid subscription begins. Nobody is enrolled automatically.'],
    ['Are taxes included?', 'Prices exclude any applicable taxes. Tax treatment is confirmed at the point of invoicing.'],
  ];

  window.MiraPricing = {
    Section: Section,
    SouthAsiaAccess: SouthAsiaAccess,
    SponsoredAccess: SponsoredAccess,
    FAQ: FAQ,
  };

  // Standalone wrapper — see the file header. Renders the same Section.
  function PricingScreen(props) {
    React.useEffect(function () {
      try {
        document.title = 'Pricing — Mira Grants';
        var d = document.querySelector('meta[name="description"]');
        if (d) d.setAttribute('content', 'Grant intelligence and workflow plans for South Asian NGOs, national organisations and international grant teams.');
      } catch (e) {}
    }, []);
    return h('div', { className: 'pr-page', 'data-ui-version': 'mira-grants-pricing-v2' },
      h(Section, { selectedPlan: (props || {}).selectedPlan }),
      h(SouthAsiaAccess),
      h(SponsoredAccess));
  }

  window.MiraPricingScreen = PricingScreen;
})();
