/* ================================================================
   PricingIntelligence.jsx -- SA-only Pricing & Revenue Dashboard
   v1.0.0 | design/PricingIntelligence.jsx

   Two tabs:
     1. Revenue Model  -- interactive P&L calculator (300-customer model)
     2. Pricing Reference -- competitive stacks + margin tables

   SA access only. Wire-in:
     Shell.jsx NAV_SA SA Command -> { id: 'pricingintel', label: 'Pricing Intelligence', icon: 'chart', sa: true }
     App.jsx allowed.sa -> add 'pricingintel'
     App.jsx switch     -> case 'pricingintel': return <window.PricingIntelligence/>;

   Pattern: IIFE, window.PricingIntelligence, CSS vars only, React.createElement.
   Update TIER_CONFIG / ADDON_CONFIG / COMP_* when pricing changes.
   Source of truth: _PLATFORM-LIMITS-AND-PRICING.md + MASTER-PRICING-REFERENCE.md
   ================================================================ */

(function () {
  'use strict';

  var VERSION = '1.0.0';
  console.log('[PricingIntelligence] v' + VERSION + ' loaded');

  var _useState    = React.useState;
  var _useCallback = React.useCallback;
  var ce = React.createElement;

  /* -- helpers ---------------------------------------------------- */
  var fmt = function (n) {
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(n);
  };
  var pct = function (n, d) {
    d = d === undefined ? 1 : d;
    return n.toFixed(d) + '%';
  };

  /* -- PRICING CONFIG -------------------------------------------
     UPDATE HERE when _PLATFORM-LIMITS-AND-PRICING.md changes.
  --------------------------------------------------------------- */
  var TIER_CONFIG = [
    { key: 'solo',       label: 'Solo',       price: 49,  byok: 39,  gm: 0.935, color: '#38bdf8', defaultCt: 100, sites: 1,   ai: 200   },
    { key: 'starter',    label: 'Starter',    price: 99,  byok: 79,  gm: 0.917, color: '#818cf8', defaultCt: 100, sites: 3,   ai: 800   },
    { key: 'pro',        label: 'Pro',        price: 199, byok: 159, gm: 0.886, color: '#c084fc', defaultCt: 60,  sites: 20,  ai: 5000  },
    { key: 'agency',     label: 'Agency',     price: 599, byok: 479, gm: 0.880, color: '#f472b6', defaultCt: 30,  sites: 150, ai: 20000 },
    { key: 'enterprise', label: 'Enterprise', price: 999, byok: 799, gm: 0.865, color: '#fb923c', defaultCt: 10,  sites: 250, ai: 30000 },
  ];

  var ADDON_CONFIG = [
    { key: 'daily',    label: 'Daily SEO upgrade',  note: 'Starter/Pro/Agency avg $79', defaultAttach: 10, avgPrice: 79, gm: 0.86, eligibleTiers: ['starter', 'pro', 'agency'] },
    { key: 'boost',    label: 'Keyword boost pack',  note: 'Any tier avg M-pack $19',   defaultAttach: 8,  avgPrice: 19, gm: 0.91, eligibleTiers: null },
    { key: 'geo',      label: 'GEO/AI Visibility',   note: '$49/domain avg 1.5 domains', defaultAttach: 6,  avgPrice: 74, gm: 0.97, eligibleTiers: null },
    { key: 'dir_pro',  label: 'Directory Pro',        note: 'Agency only $29/mo',         defaultAttach: 30, avgPrice: 29, gm: 0.95, eligibleTiers: ['agency'] },
  ];

  var DEFAULT_OPEX = [
    { key: 'salary',    label: 'Your salary',        amt: 120000 },
    { key: 'cs',        label: 'Customer Support',   amt: 48000  },
    { key: 'marketer',  label: 'Marketer',           amt: 48000  },
    { key: 'developer', label: 'Developer',          amt: 78000  },
    { key: 'legal',     label: 'Legal / accounting', amt: 8000   },
    { key: 'marketing', label: 'Marketing budget',   amt: 60000  },
    { key: 'software',  label: 'Software / tools',   amt: 6000   },
    { key: 'misc',      label: 'Misc',               amt: 8000   },
  ];

  var OPEX_PHASES = {
    y1: { label: 'Y1 -- launch', values: { salary: 120000, cs: 24000,  marketer: 0,     developer: 0,      legal: 8000,  marketing: 30000,  software: 6000,  misc: 8000  } },
    y2: { label: 'Y2 -- hires',  values: { salary: 120000, cs: 48000,  marketer: 24000, developer: 0,      legal: 8000,  marketing: 48000,  software: 6000,  misc: 8000  } },
    y3: { label: 'Y3 -- growth', values: { salary: 130000, cs: 48000,  marketer: 48000, developer: 40000,  legal: 10000, marketing: 60000,  software: 8000,  misc: 10000 } },
    y4: { label: 'Y4 -- scale',  values: { salary: 140000, cs: 96000,  marketer: 48000, developer: 78000,  legal: 12000, marketing: 80000,  software: 10000, misc: 12000 } },
    y5: { label: 'Y5 -- team',   values: { salary: 150000, cs: 96000,  marketer: 60000, developer: 156000, legal: 15000, marketing: 100000, software: 12000, misc: 15000 } },
  };

  /* -- AI COST LAYERS ------------------------------------------- */
  var AI_LAYERS = [
    { label: 'Baseline (Sonnet only)',    cost: 0.01530, savings: 0,    status: 'dev',  badge: 'Dev' },
    { label: '+ Model routing (L1)',      cost: 0.00969, savings: 36.7, status: 'live', badge: 'Live' },
    { label: '+ Prompt caching (L2)',     cost: 0.00521, savings: 66.0, status: 'live', badge: 'Live' },
    { label: '+ Batch API 30% (L3)',      cost: 0.00443, savings: 71.1, status: 'p1',   badge: 'P1' },
    { label: '+ Enterprise discount (L4)',cost: 0.00310, savings: 79.7, status: 'p2',   badge: 'Y2+' },
  ];

  /* -- COMPETITIVE DATA ----------------------------------------- */
  var COMP_SEO = [
    { tool: 'WPSB Solo $49',       price: '$49',  kw: '500',   freq: 'Weekly', audit: true,  wcag: true,  mig: '-',     hi: true  },
    { tool: 'Moz Starter*',        price: '$47',  kw: '~200',  freq: 'Weekly', audit: false, wcag: false, mig: '-'              },
    { tool: 'SE Ranking Core',     price: '$103', kw: '~1,000',freq: 'Daily',  audit: false, wcag: false, mig: '-'              },
    { tool: 'Semrush SEO',         price: '$117', kw: '500',   freq: 'Daily',  audit: false, wcag: false, mig: '-'              },
    { tool: 'Ahrefs Lite',         price: '$107', kw: '750',   freq: 'Wkly**', audit: false, wcag: false, mig: '-'              },
    { tool: 'WPSB Starter $99',    price: '$99',  kw: '1,500', freq: 'Weekly', audit: true,  wcag: true,  mig: '3/mo',  hi: true  },
    { tool: 'WPSB Pro $199',       price: '$199', kw: '3,000', freq: 'Weekly', audit: true,  wcag: true,  mig: '10/mo', hi: true  },
    { tool: 'Ahrefs Standard',     price: '$207', kw: '2,000', freq: 'Wkly**', audit: false, wcag: false, mig: '-'              },
    { tool: 'SE Ranking Growth',   price: '$223', kw: '~2,500',freq: 'Daily',  audit: false, wcag: false, mig: '-'              },
    { tool: 'Semrush Pro+',        price: '$248', kw: '1,500', freq: 'Daily',  audit: false, wcag: false, mig: '-'              },
    { tool: 'WPSB Agency $599',    price: '$599', kw: '6,000', freq: 'Weekly', audit: true,  wcag: true,  mig: '20/mo', hi: true  },
  ];

  var COMP_AEO = [
    { tool: 'WPSB GEO Visibility', price: '$49/domain', platforms: '5 LLMs',      wp: true,  agency: true,  hi: true  },
    { tool: 'Searchable Starter',  price: '$50/domain', platforms: '5 LLMs',      wp: false, agency: false             },
    { tool: 'Searchable Pro',      price: '$125/mo',    platforms: '5 unlimited', wp: false, agency: false             },
    { tool: 'SE Ranking AI Search',price: '~$71/mo',    platforms: 'Limited',     wp: false, agency: false             },
    { tool: 'Semrush brand mon.',  price: '~$99/mo',    platforms: 'Limited',     wp: false, agency: false             },
    { tool: 'SearchAtlas',         price: '$99+/mo',    platforms: '3 LLMs',      wp: false, agency: 'Partial'         },
  ];

  var COMP_CONTENT = [
    { tool: 'WPSB Content Module', price: '$39/mo', articles: '10-20 est.', autopub: true,  approval: true,      hi: true },
    { tool: 'AutoSEO',             price: '$99/mo', articles: '30',          autopub: true,  approval: 'Optional'          },
    { tool: 'BabyLoveGrowth',      price: '$99/mo', articles: '30',          autopub: true,  approval: false               },
  ];

  /* -- MARGIN SCENARIOS ----------------------------------------- */
  var MARGIN_DATA = [
    { scenario: 'Worst (100% quota, L1+L2 live)',  rows: [
      { plan: 'Solo $49',    rev: 49,  ai: 1.04,  dforseo: 0.72, infra: 3.00, stripe: 1.72, margin: 86.8 },
      { plan: 'Starter $99', rev: 99,  ai: 4.16,  dforseo: 2.16, infra: 3.00, stripe: 3.17, margin: 87.4 },
      { plan: 'Pro $199',    rev: 199, ai: 26.00, dforseo: 4.32, infra: 4.00, stripe: 6.08, margin: 79.7 },
      { plan: 'Agency $599', rev: 599, ai: 104.0, dforseo: 17.28,infra: 6.00, stripe: 17.67,margin: 75.8 },
      { plan: 'Ent. $999',   rev: 999, ai: 156.0, dforseo: 17.28,infra: 8.00, stripe: 29.27,margin: 78.9 },
    ]},
    { scenario: 'Typical (50% quota, L1+L2 live)', rows: [
      { plan: 'Solo $49',    rev: 49,  ai: 0.52,  dforseo: 0.72, infra: 3.00, stripe: 1.72, margin: 87.8 },
      { plan: 'Starter $99', rev: 99,  ai: 2.08,  dforseo: 2.16, infra: 3.00, stripe: 3.17, margin: 89.5 },
      { plan: 'Pro $199',    rev: 199, ai: 13.00, dforseo: 4.32, infra: 4.00, stripe: 6.08, margin: 86.2 },
      { plan: 'Agency $599', rev: 599, ai: 52.00, dforseo: 17.28,infra: 6.00, stripe: 17.67,margin: 84.5 },
      { plan: 'Ent. $999',   rev: 999, ai: 78.00, dforseo: 17.28,infra: 8.00, stripe: 29.27,margin: 86.7 },
    ]},
    { scenario: 'Target (50% quota, L4 Year 2+)', rows: [
      { plan: 'Solo $49',    rev: 49,  ai: 0.31,  dforseo: 0.72, infra: 3.00, stripe: 1.72, margin: 88.3 },
      { plan: 'Starter $99', rev: 99,  ai: 1.24,  dforseo: 2.16, infra: 3.00, stripe: 3.17, margin: 90.3 },
      { plan: 'Pro $199',    rev: 199, ai: 7.75,  dforseo: 4.32, infra: 4.00, stripe: 6.08, margin: 88.9 },
      { plan: 'Agency $599', rev: 599, ai: 31.00, dforseo: 17.28,infra: 6.00, stripe: 17.67,margin: 88.0 },
      { plan: 'Ent. $999',   rev: 999, ai: 46.50, dforseo: 17.28,infra: 8.00, stripe: 29.27,margin: 89.9 },
    ]},
  ];

  /* ===============================================================
     SUB-COMPONENTS
  =============================================================== */

  /* Shared CSS injected once */
  var CSS_INJECTED = false;
  function injectCSS() {
    if (CSS_INJECTED) return;
    CSS_INJECTED = true;
    var style = document.createElement('style');
    style.textContent = [
      '.pi-wrap { font-family: inherit; width: 100%; }',
      '.pi-tabs { display: flex; gap: 4px; margin-bottom: 18px; border-bottom: 1px solid var(--border); padding-bottom: 0; }',
      '.pi-tab { background: none; border: none; border-bottom: 2px solid transparent; padding: 8px 16px; font-family: inherit; font-size: 13px; font-weight: 500; color: var(--dim); cursor: pointer; margin-bottom: -1px; transition: color .15s, border-color .15s; }',
      '.pi-tab.active { color: var(--beam, #38bdf8); border-bottom-color: var(--beam, #38bdf8); }',
      '.pi-tab:hover:not(.active) { color: var(--text); }',
      '.pi-kpi-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 8px; margin-bottom: 14px; }',
      '.pi-kpi { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 10px 12px; }',
      '.pi-kpi-label { font-size: 9px; color: var(--dim); text-transform: uppercase; letter-spacing: .06em; }',
      '.pi-kpi-val { font-size: 16px; font-weight: 700; line-height: 1.15; margin-top: 3px; word-break: break-all; }',
      '.pi-section { border: 1px solid var(--border); border-radius: 10px; margin-bottom: 10px; overflow: hidden; }',
      '.pi-section-hd { background: var(--panel); border: none; width: 100%; display: flex; justify-content: space-between; align-items: center; padding: 11px 14px; cursor: pointer; font-family: inherit; }',
      '.pi-section-hd-title { font-size: 13px; font-weight: 600; color: var(--text); }',
      '.pi-section-body { background: var(--bg, #0c0c18); padding: 12px 14px; }',
      '.pi-badge { font-size: 10px; padding: 2px 8px; border-radius: 99px; border: 1px solid; }',
      '.pi-badge-info { color: var(--beam, #7dd3fc); background: transparent; border-color: var(--beam, #1e3a5f); opacity: .8; }',
      '.pi-num-input { width: 100%; background: var(--bg, #0a0a12); border: 1px solid var(--border); border-radius: 6px; padding: 6px 8px; color: var(--text); font-family: inherit; font-size: 13px; text-align: right; outline: none; }',
      '.pi-num-input:focus { border-color: var(--beam, #38bdf8); }',
      '.pi-range { width: 100%; display: block; accent-color: var(--beam, #38bdf8); }',
      '.pi-tog { cursor: pointer; border: 1px solid var(--border); border-radius: 8px; background: var(--panel); font-family: inherit; font-size: 11px; padding: 4px 12px; transition: all .15s; }',
      '.pi-tog.on { border-color: var(--beam, #38bdf8); background: transparent; color: var(--beam, #7dd3fc); }',
      '.pi-tog.off { color: var(--dim); }',
      '.pi-divider { border: none; border-top: 1px solid var(--border); margin: 10px 0; }',
      '.pi-phase-btn { background: var(--bg, #0a0a12); border: 1px solid var(--border); color: var(--dim); padding: 6px 10px; border-radius: 6px; font-size: 11px; font-family: inherit; cursor: pointer; transition: all .15s; }',
      '.pi-phase-btn.active { background: var(--beam-muted, #0891b2); border-color: var(--beam, #06b6d4); color: #fff; font-weight: 600; }',
      '.pi-ref-table { width: 100%; border-collapse: collapse; font-size: 12px; }',
      '.pi-ref-table th { font-size: 10px; text-transform: uppercase; letter-spacing: .05em; color: var(--dim); font-weight: 500; padding: 6px 8px; border-bottom: 1px solid var(--border); text-align: left; }',
      '.pi-ref-table td { padding: 7px 8px; border-bottom: 1px solid var(--border); color: var(--text); vertical-align: middle; }',
      '.pi-ref-table tr:last-child td { border-bottom: none; }',
      '.pi-ref-table tr.hi td { background: color-mix(in srgb, var(--beam, #38bdf8) 5%, transparent); }',
      '.pi-ref-table tr.hi td:first-child { border-left: 2px solid var(--beam, #38bdf8); }',
      '.pi-check-y { color: var(--green, #4ade80); font-size: 13px; }',
      '.pi-check-n { color: var(--dim); font-size: 13px; }',
      '.pi-margin-good { color: var(--green, #4ade80); font-weight: 600; }',
      '.pi-margin-warn { color: var(--warn, #f5b800); font-weight: 600; }',
      '.pi-margin-bad  { color: var(--red, #f87171); font-weight: 600; }',
      '.pi-layer-live { color: var(--green, #4ade80); }',
      '.pi-layer-p1   { color: var(--warn, #f5b800); }',
      '.pi-layer-p2   { color: var(--dim); }',
      '.pi-layer-dev  { color: var(--dim); }',
      '.pi-scenario-tabs { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 12px; }',
      '.pi-scenario-btn { background: var(--panel); border: 1px solid var(--border); border-radius: 6px; padding: 5px 10px; font-size: 11px; font-family: inherit; color: var(--dim); cursor: pointer; transition: all .15s; }',
      '.pi-scenario-btn.active { border-color: var(--beam, #38bdf8); color: var(--beam, #38bdf8); }',
      '@media (max-width: 640px) { .pi-kpi-grid { grid-template-columns: repeat(2, 1fr); } .pi-ref-table { font-size: 11px; } .pi-ref-table th, .pi-ref-table td { padding: 5px 5px; } }',
    ].join('\n');
    document.head.appendChild(style);
  }

  /* Section collapsible */
  function Section(props) {
    var _s = _useState(props.defaultOpen !== false);
    var open = _s[0]; var setOpen = _s[1];
    return ce('div', { className: 'pi-section' },
      ce('button', { className: 'pi-section-hd', onClick: function () { setOpen(function (o) { return !o; }); } },
        ce('span', { className: 'pi-section-hd-title' }, props.title),
        ce('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
          props.badge ? ce('span', { className: 'pi-badge pi-badge-info' }, props.badge) : null,
          ce('span', { style: { fontSize: 11, color: 'var(--dim)' } }, open ? '^' : 'v')
        )
      ),
      open ? ce('div', { className: 'pi-section-body' }, props.children) : null
    );
  }

  /* Number input */
  function NumInput(props) {
    return ce('input', {
      type: 'number', className: 'pi-num-input',
      min: props.min || 0, max: props.max || 9999999, step: props.step || 1,
      value: props.value,
      onChange: function (e) {
        var v = Math.max(props.min || 0, Math.min(props.max || 9999999, Number(e.target.value) || 0));
        props.onChange(v);
      },
    });
  }

  /* KPI card */
  function Kpi(props) {
    return ce('div', { className: 'pi-kpi', style: props.accent ? { borderTop: '2px solid ' + props.accent } : {} },
      ce('div', { className: 'pi-kpi-label' }, props.label),
      ce('div', { className: 'pi-kpi-val', style: { color: props.color || 'var(--text)' } }, props.value)
    );
  }

  /* ===============================================================
     TAB 1 -- REVENUE MODEL CALCULATOR
  =============================================================== */
  function RevenueModel() {
    var _counts    = _useState(function () { return Object.fromEntries(TIER_CONFIG.map(function (t) { return [t.key, t.defaultCt]; })); });
    var counts = _counts[0]; var setCounts = _counts[1];

    var _byok      = _useState(30);
    var byokPct = _byok[0]; var setByokPct = _byok[1];

    var _attach    = _useState(function () { return Object.fromEntries(ADDON_CONFIG.map(function (a) { return [a.key, a.defaultAttach]; })); });
    var addonAttach = _attach[0]; var setAddonAttach = _attach[1];

    var _addonsOn  = _useState(true);
    var addonsOn = _addonsOn[0]; var setAddonsOn = _addonsOn[1];

    var _opex      = _useState(DEFAULT_OPEX);
    var opex = _opex[0]; var setOpex = _opex[1];

    var _customOpex = _useState([]);
    var customOpex = _customOpex[0]; var setCustomOpex = _customOpex[1];

    var _opexPhase = _useState('custom');
    var opexPhase = _opexPhase[0]; var setOpexPhase = _opexPhase[1];

    var updateOpex = function (key, val) {
      setOpex(function (rows) { return rows.map(function (r) { return r.key === key ? Object.assign({}, r, { amt: val }) : r; }); });
      setOpexPhase('custom');
    };
    var addOpexRow = function () {
      setCustomOpex(function (r) { return r.concat([{ key: 'c_' + Date.now(), label: 'New item', amt: 0 }]); });
    };
    var removeCustom = function (key) {
      setCustomOpex(function (r) { return r.filter(function (x) { return x.key !== key; }); });
    };
    var updateCustom = function (key, field, val) {
      setCustomOpex(function (r) { return r.map(function (x) { return x.key === key ? Object.assign({}, x, { [field]: val }) : x; }); });
    };
    var applyPhase = function (phaseKey) {
      setOpexPhase(phaseKey);
      if (phaseKey === 'custom') return;
      var phase = OPEX_PHASES[phaseKey];
      if (!phase) return;
      setOpex(function (rows) { return rows.map(function (r) { return phase.values[r.key] !== undefined ? Object.assign({}, r, { amt: phase.values[r.key] }) : r; }); });
    };

    /* Calculations */
    var totalCt = Object.values(counts).reduce(function (a, b) { return a + b; }, 0);

    var tierCalcs = TIER_CONFIG.map(function (t) {
      var ct = counts[t.key] || 0;
      var blendedPrice = t.price * (1 - byokPct / 100) + t.byok * (byokPct / 100);
      var revenue = ct * blendedPrice;
      var gp = revenue * t.gm;
      return Object.assign({}, t, { ct: ct, blendedPrice: blendedPrice, revenue: revenue, gp: gp });
    });

    var baseMRR   = tierCalcs.reduce(function (a, r) { return a + r.revenue; }, 0);
    var baseGPMRR = tierCalcs.reduce(function (a, r) { return a + r.gp; }, 0);

    var addonCalcs = ADDON_CONFIG.map(function (a) {
      var eligibleCt = a.eligibleTiers
        ? a.eligibleTiers.reduce(function (sum, tier) { return sum + (counts[tier] || 0); }, 0)
        : totalCt;
      var attachedCt = eligibleCt * (addonAttach[a.key] / 100);
      var revenue = attachedCt * a.avgPrice;
      var gp = revenue * a.gm;
      return Object.assign({}, a, { eligibleCt: eligibleCt, attachedCt: attachedCt, revenue: revenue, gp: gp });
    });

    var addonMRR   = addonsOn ? addonCalcs.reduce(function (a, r) { return a + r.revenue; }, 0) : 0;
    var addonGPMRR = addonsOn ? addonCalcs.reduce(function (a, r) { return a + r.gp; }, 0) : 0;

    var totalMRR      = baseMRR + addonMRR;
    var totalGPMRR    = baseGPMRR + addonGPMRR;
    var totalARR      = totalMRR * 12;
    var totalGPAnnual = totalGPMRR * 12;
    var blendedGM     = totalMRR > 0 ? (totalGPMRR / totalMRR) * 100 : 0;

    var allOpex      = opex.concat(customOpex);
    var totalOpexAmt = allOpex.reduce(function (a, r) { return a + (Number(r.amt) || 0); }, 0);
    var salaryAmt    = (opex.find(function (r) { return r.key === 'salary'; }) || {}).amt || 0;
    var oi           = totalGPAnnual - totalOpexAmt;
    var netMargin    = totalARR > 0 ? (oi / totalARR) * 100 : 0;
    var jordanTotal  = salaryAmt + Math.max(0, oi);

    var dim = { fontSize: 10, color: 'var(--dim)', marginTop: 2 };
    var lbl = { fontSize: 10, color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 6, display: 'block' };

    return ce('div', null,
      /* KPI grid */
      ce('div', { className: 'pi-kpi-grid' },
        ce(Kpi, { label: 'Customers',        value: totalCt,          color: 'var(--dim)' }),
        ce(Kpi, { label: 'MRR',              value: fmt(totalMRR),    color: 'var(--beam)' }),
        ce(Kpi, { label: 'ARR',              value: fmt(totalARR),    color: 'var(--beam)' }),
        ce(Kpi, { label: 'Gross margin',     value: pct(blendedGM),   color: 'var(--green, #4ade80)' }),
        ce(Kpi, { label: 'GP / yr',          value: fmt(totalGPAnnual), color: 'var(--green, #4ade80)' }),
        ce(Kpi, { label: 'Total OpEx / yr',  value: fmt(totalOpexAmt),  color: 'var(--red, #f87171)' }),
        ce(Kpi, { label: 'Operating income', value: fmt(oi),            color: oi >= 0 ? 'var(--green, #4ade80)' : 'var(--red, #f87171)' }),
        ce(Kpi, { label: 'Your total comp',  value: fmt(jordanTotal),   color: 'var(--purple, #c084fc)' })
      ),

      /* Customers */
      ce(Section, { title: 'Customers per tier', badge: totalCt + ' total' },
        ce('div', { style: { marginBottom: 12 } },
          ce('span', { style: lbl }, 'BYOK customers (20% discount): ' + byokPct + '%'),
          ce('input', { type: 'range', className: 'pi-range', min: 0, max: 60, value: byokPct, onChange: function (e) { setByokPct(Number(e.target.value)); } })
        ),
        ce('hr', { className: 'pi-divider' }),
        tierCalcs.map(function (c) {
          return ce('div', { key: c.key, style: { display: 'grid', gridTemplateColumns: '10px 1fr 80px', gap: 14, alignItems: 'center', marginBottom: 11 } },
            ce('span', { style: { width: 8, height: 8, borderRadius: '50%', background: c.color, display: 'block' } }),
            ce('div', { style: { minWidth: 0 } },
              ce('div', { style: { fontSize: 12, fontWeight: 500, color: 'var(--text)' } }, c.label + ' -- ' + fmt(c.blendedPrice) + '/mo blended'),
              ce('div', { style: dim }, fmt(c.revenue) + '/mo . ' + pct(c.gm * 100) + ' GM')
            ),
            ce(NumInput, { value: counts[c.key], onChange: function (v) { setCounts(function (p) { return Object.assign({}, p, { [c.key]: v }); }); }, max: 9999 })
          );
        }),
        ce('hr', { className: 'pi-divider' }),
        ce('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: 11 } },
          ce('span', { style: { color: 'var(--dim)' } }, 'Base total'),
          ce('div', null,
            ce('span', { style: { color: 'var(--beam)', fontWeight: 600 } }, fmt(baseMRR) + '/mo'),
            ce('span', { style: { color: 'var(--green, #4ade80)', marginLeft: 10 } }, fmt(baseGPMRR) + '/mo GP')
          )
        )
      ),

      /* Add-ons */
      ce(Section, { title: 'Recurring add-ons', badge: addonsOn ? fmt(addonMRR) + '/mo' : 'off' },
        ce('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 } },
          ce('span', { style: { fontSize: 11, color: 'var(--dim)' } }, 'Toggle all addons'),
          ce('button', { className: 'pi-tog ' + (addonsOn ? 'on' : 'off'), onClick: function () { setAddonsOn(function (o) { return !o; }); } }, addonsOn ? 'ON' : 'OFF')
        ),
        addonCalcs.map(function (a) {
          return ce('div', { key: a.key, style: { background: 'var(--panel)', border: '1px solid var(--border)', borderRadius: 8, padding: 11, marginBottom: 9, opacity: addonsOn ? 1 : 0.35 } },
            ce('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 } },
              ce('div', { style: { flex: 1, minWidth: 0 } },
                ce('div', { style: { fontSize: 12, fontWeight: 500, color: 'var(--text)' } }, a.label),
                ce('div', { style: dim }, a.note + ' . ' + pct(a.gm * 100) + ' GM')
              ),
              ce('div', { style: { textAlign: 'right', flexShrink: 0 } },
                ce('div', { style: { fontSize: 12, color: 'var(--text)', fontWeight: 600 } }, fmt(a.revenue) + '/mo'),
                ce('div', { style: { fontSize: 10, color: 'var(--green, #4ade80)' } }, fmt(a.gp) + ' GP')
              )
            ),
            ce('div', { style: { marginTop: 9 } },
              ce('span', { style: lbl }, 'Attach: ' + addonAttach[a.key] + '% -- ' + Math.round(a.attachedCt) + ' of ' + Math.round(a.eligibleCt) + ' eligible'),
              ce('input', { type: 'range', className: 'pi-range', min: 0, max: 40, value: addonAttach[a.key], disabled: !addonsOn, onChange: function (e) { setAddonAttach(function (p) { return Object.assign({}, p, { [a.key]: Number(e.target.value) }); }); } })
            )
          );
        }),
        addonsOn ? ce('div', null,
          ce('hr', { className: 'pi-divider' }),
          ce('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: 11 } },
            ce('span', { style: { color: 'var(--dim)' } }, 'Addon total'),
            ce('div', null,
              ce('span', { style: { color: 'var(--beam)', fontWeight: 600 } }, fmt(addonMRR) + '/mo'),
              ce('span', { style: { color: 'var(--green, #4ade80)', marginLeft: 10 } }, fmt(addonGPMRR) + '/mo GP')
            )
          )
        ) : null
      ),

      /* OpEx */
      ce(Section, { title: 'Annual operating expenses', badge: fmt(totalOpexAmt) + '/yr' },
        /* Phase presets */
        ce('div', { style: { background: 'var(--panel)', border: '1px solid var(--border)', borderRadius: 8, padding: 10, marginBottom: 14 } },
          ce('div', { style: { fontSize: 10, color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 8 } }, 'Phase preset -- apply realistic OpEx ramp'),
          ce('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 6 } },
            ['y1', 'y2', 'y3', 'y4', 'y5', 'custom'].map(function (pk) {
              var labels = { y1: 'Y1 launch', y2: 'Y2 hires', y3: 'Y3 growth', y4: 'Y4 scale', y5: 'Y5 team', custom: 'Custom' };
              var active = opexPhase === pk;
              return ce('button', { key: pk, className: 'pi-phase-btn' + (active ? ' active' : ''), type: 'button', onClick: function () { applyPhase(pk); } }, labels[pk]);
            })
          )
        ),
        opex.map(function (r) {
          return ce('div', { key: r.key, style: { display: 'grid', gridTemplateColumns: '1fr 92px', gap: 14, alignItems: 'center', marginBottom: 11 } },
            ce('div', null,
              ce('div', { style: { fontSize: 12, color: 'var(--text)' } }, r.label),
              r.key === 'salary' ? ce('div', { style: { fontSize: 10, color: 'var(--beam)', marginTop: 2 } }, 'guaranteed -- paid from OpEx') : null
            ),
            ce(NumInput, { value: r.amt, onChange: function (v) { updateOpex(r.key, v); }, step: 1000 })
          );
        }),
        customOpex.length > 0 ? ce('hr', { className: 'pi-divider' }) : null,
        customOpex.map(function (r) {
          return ce('div', { key: r.key, style: { display: 'grid', gridTemplateColumns: '1fr 92px 28px', gap: 10, alignItems: 'center', marginBottom: 11 } },
            ce('input', {
              value: r.label, onChange: function (e) { updateCustom(r.key, 'label', e.target.value); },
              style: { background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6, padding: '6px 8px', color: 'var(--text)', fontFamily: 'inherit', fontSize: 12, outline: 'none', width: '100%' }
            }),
            ce(NumInput, { value: r.amt, onChange: function (v) { updateCustom(r.key, 'amt', v); }, step: 1000 }),
            ce('button', {
              onClick: function () { removeCustom(r.key); },
              style: { background: 'transparent', border: '1px solid var(--red, #f87171)', borderRadius: 6, color: 'var(--red, #f87171)', cursor: 'pointer', fontSize: 12, padding: 4, lineHeight: 1 }
            }, 'x')
          );
        }),
        ce('button', {
          onClick: addOpexRow,
          style: { marginTop: 4, width: '100%', background: 'transparent', border: '1px dashed var(--border)', borderRadius: 8, color: 'var(--dim)', cursor: 'pointer', padding: 8, fontSize: 11, fontFamily: 'inherit' }
        }, '+ Add expense line'),
        ce('hr', { className: 'pi-divider' }),
        ce('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: 11 } },
          ce('span', { style: { color: 'var(--dim)' } }, 'Total OpEx'),
          ce('span', { style: { color: 'var(--red, #f87171)', fontWeight: 600 } }, fmt(totalOpexAmt) + '/yr')
        )
      ),

      /* P&L */
      ce(Section, { title: 'Annual P&L breakdown' },
        [
          { label: 'Revenue (ARR)',    val: totalARR,               color: 'var(--beam)',            note: 'What customers pay -- not profit' },
          { label: '-- COGS',          val: -(totalARR - totalGPAnnual), color: 'var(--red, #f87171)', note: 'AI, infra, Stripe, DataForSEO' },
          { label: '= Gross profit',  val: totalGPAnnual,           color: 'var(--green, #4ade80)',  note: pct(blendedGM) + ' GM' },
          null,
          { label: '-- Your salary',   val: -salaryAmt,              color: 'var(--red, #f87171)',    note: 'Paid regardless of profit' },
          { label: '-- Other OpEx',    val: -(totalOpexAmt - salaryAmt), color: 'var(--red, #f87171)', note: 'CS, marketer, dev, marketing, tools...' },
          { label: '= Operating income', val: oi,                   color: oi >= 0 ? 'var(--green, #4ade80)' : 'var(--red, #f87171)', note: 'Real bottom line' },
        ].map(function (row, i) {
          if (row === null) return ce('hr', { key: 'div' + i, className: 'pi-divider' });
          return ce('div', { key: i, style: { display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 9, gap: 8 } },
            ce('div', { style: { flex: 1, minWidth: 0 } },
              ce('div', { style: { fontSize: 12, color: 'var(--text)' } }, row.label),
              ce('div', { style: { fontSize: 10, color: 'var(--dim)', marginTop: 2 } }, row.note)
            ),
            ce('div', { style: { color: row.color, fontWeight: 600, whiteSpace: 'nowrap', fontSize: 12 } }, fmt(row.val))
          );
        }),
        ce('div', { style: { borderTop: '2px solid var(--border)', paddingTop: 10, marginTop: 4, display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
          ce('span', { style: { fontSize: 10, color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.05em' } }, 'Net operating margin'),
          ce('span', { style: { fontSize: 20, fontWeight: 700, color: netMargin >= 0 ? 'var(--green, #4ade80)' : 'var(--red, #f87171)' } }, pct(Math.max(0, netMargin)))
        )
      ),

      /* What you make */
      ce(Section, { title: 'What you actually make' },
        ce('div', { style: { background: 'var(--panel)', border: '1px solid var(--border)', borderRadius: 8, padding: 12, marginBottom: 8 } },
          ce('div', { style: { fontSize: 10, color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 6 } }, 'Salary (guaranteed)'),
          ce('div', { style: { fontSize: 20, fontWeight: 700, color: 'var(--beam)' } }, fmt(salaryAmt) + '/yr'),
          ce('div', { style: { fontSize: 10, color: 'var(--dim)', marginTop: 2 } }, 'Paid regardless of profit')
        ),
        ce('div', { style: { background: 'var(--panel)', border: '1px solid var(--border)', borderRadius: 8, padding: 12, marginBottom: 8 } },
          ce('div', { style: { fontSize: 10, color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 6 } }, 'Distributions (operating income)'),
          ce('div', { style: { fontSize: 20, fontWeight: 700, color: oi >= 0 ? 'var(--green, #4ade80)' : 'var(--red, #f87171)' } }, oi >= 0 ? fmt(oi) : '(' + fmt(Math.abs(oi)) + ')' + '/yr'),
          ce('div', { style: { fontSize: 10, color: 'var(--dim)', marginTop: 2 } }, oi >= 0 ? 'Business profit to distribute' : 'Operating at a loss')
        ),
        ce('div', { style: { background: 'var(--panel)', border: '1px solid var(--border)', borderRadius: 8, padding: 12 } },
          ce('div', { style: { fontSize: 10, color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 6 } }, 'Total comp (before tax)'),
          ce('div', { style: { fontSize: 22, fontWeight: 700, color: 'var(--purple, #c084fc)' } }, fmt(jordanTotal)),
          ce('div', { style: { fontSize: 10, color: 'var(--dim)', marginTop: 2 } }, 'salary + distributions')
        )
      )
    );
  }

  /* ===============================================================
     TAB 2 -- PRICING REFERENCE
  =============================================================== */
  function PricingReference() {
    var _scenario = _useState(0);
    var scenarioIdx = _scenario[0]; var setScenarioIdx = _scenario[1];

    var marginData = MARGIN_DATA[scenarioIdx];

    function marginClass(m) {
      if (m >= 88) return 'pi-margin-good';
      if (m >= 82) return 'pi-margin-warn';
      return 'pi-margin-bad';
    }

    function Check(val) {
      if (val === true)    return ce('span', { className: 'pi-check-y' }, 'Y');
      if (val === false)   return ce('span', { className: 'pi-check-n' }, '--');
      return ce('span', { style: { color: 'var(--warn, #f5b800)', fontSize: 11 } }, String(val));
    }

    return ce('div', null,

      /* WPSB Plans quick ref */
      ce(Section, { title: 'WPSB Plans -- Quick Reference', badge: '5 tiers' },
        ce('div', { style: { overflowX: 'auto' } },
          ce('table', { className: 'pi-ref-table' },
            ce('thead', null,
              ce('tr', null,
                ['Plan', 'All-Inc', 'BYOK', 'Annual (AI)', 'Sites', 'AI/mo', 'SEO kw'].map(function (h) { return ce('th', { key: h }, h); })
              )
            ),
            ce('tbody', null,
              TIER_CONFIG.map(function (t) {
                var annualAI = (t.price * 0.9 * 12).toFixed(2);
                var kw = ['500', '1,500', '3,000', '6,000', '6,000+'];
                var kwMap = { solo: '500', starter: '1,500', pro: '3,000', agency: '6,000', enterprise: '6,000+' };
                return ce('tr', { key: t.key },
                  ce('td', null, ce('span', { style: { color: t.color, fontWeight: 600 } }, t.label)),
                  ce('td', null, '$' + t.price),
                  ce('td', null, '$' + t.byok),
                  ce('td', null, '$' + annualAI + '/yr'),
                  ce('td', null, t.sites === 250 ? '250+' : t.sites),
                  ce('td', null, t.ai.toLocaleString()),
                  ce('td', null, kwMap[t.key])
                );
              })
            )
          )
        ),
        ce('div', { style: { marginTop: 10, fontSize: 11, color: 'var(--dim)' } }, 'Annual = 10% off base plans. BYOK = 20% off (customer brings Anthropic key). Founding promo: Agency $499/mo first 6 months.')
      ),

      /* AI cost layers */
      ce(Section, { title: 'AI Cost per Invocation (3,100 in + 400 out tokens)', badge: 'L1+L2 live' },
        ce('div', { style: { overflowX: 'auto' } },
          ce('table', { className: 'pi-ref-table' },
            ce('thead', null,
              ce('tr', null, ['Layer', 'Cost/invoc', 'Savings', 'Status'].map(function (h) { return ce('th', { key: h }, h); }))
            ),
            ce('tbody', null,
              AI_LAYERS.map(function (l, i) {
                var statusClass = { live: 'pi-layer-live', p1: 'pi-layer-p1', p2: 'pi-layer-p2', dev: 'pi-layer-dev' }[l.status];
                return ce('tr', { key: i },
                  ce('td', null, l.label),
                  ce('td', { style: { fontFamily: 'monospace', fontWeight: 600, color: 'var(--text)' } }, '$' + l.cost.toFixed(5)),
                  ce('td', null, l.savings > 0 ? ce('span', { style: { color: 'var(--green, #4ade80)' } }, pct(l.savings) + ' saved') : '--'),
                  ce('td', null, ce('span', { className: 'pi-badge pi-badge-info ' + statusClass, style: { borderColor: 'currentColor' } }, l.badge))
                );
              })
            )
          )
        ),
        ce('div', { style: { marginTop: 10, fontSize: 11, color: 'var(--dim)' } }, 'DataForSEO rank checks: $0.0006/check standard queue (never Live mode). 40% cache hit assumed at scale.')
      ),

      /* Margin model */
      ce(Section, { title: 'Per-Plan Margin Model', badge: marginData.scenario },
        ce('div', { className: 'pi-scenario-tabs' },
          MARGIN_DATA.map(function (s, i) {
            return ce('button', { key: i, className: 'pi-scenario-btn' + (scenarioIdx === i ? ' active' : ''), onClick: function () { setScenarioIdx(i); } }, s.scenario);
          })
        ),
        ce('div', { style: { overflowX: 'auto' } },
          ce('table', { className: 'pi-ref-table' },
            ce('thead', null,
              ce('tr', null, ['Plan', 'Revenue', 'AI cost', 'DataForSEO', 'Infra', 'Stripe', 'Net margin'].map(function (h) { return ce('th', { key: h }, h); }))
            ),
            ce('tbody', null,
              marginData.rows.map(function (r) {
                return ce('tr', { key: r.plan },
                  ce('td', { style: { fontWeight: 600 } }, r.plan),
                  ce('td', null, '$' + r.rev),
                  ce('td', { style: { color: 'var(--red, #f87171)' } }, '$' + r.ai.toFixed(2)),
                  ce('td', { style: { color: 'var(--red, #f87171)' } }, '$' + r.dforseo.toFixed(2)),
                  ce('td', { style: { color: 'var(--red, #f87171)' } }, '$' + r.infra.toFixed(2)),
                  ce('td', { style: { color: 'var(--red, #f87171)' } }, '$' + r.stripe.toFixed(2)),
                  ce('td', null, ce('span', { className: marginClass(r.margin) }, pct(r.margin)))
                );
              })
            )
          )
        ),
        ce('div', { style: { marginTop: 10, fontSize: 11, color: 'var(--dim)' } }, 'BYOK customers: AI cost = $0 (their own Anthropic key), 20% lower revenue. Blended margin improves at high BYOK adoption rates.')
      ),

      /* Competitor: SEO tools */
      ce(Section, { title: 'Competitor Stack -- SEO / Audit Tools', badge: 'WPSB wins on value', defaultOpen: false },
        ce('div', { style: { overflowX: 'auto' } },
          ce('table', { className: 'pi-ref-table' },
            ce('thead', null,
              ce('tr', null, ['Tool', 'Price', 'Keywords', 'Freq', 'WP Audit', 'WCAG', 'Migration'].map(function (h) { return ce('th', { key: h }, h); }))
            ),
            ce('tbody', null,
              COMP_SEO.map(function (r) {
                return ce('tr', { key: r.tool, className: r.hi ? 'hi' : '' },
                  ce('td', { style: r.hi ? { fontWeight: 600, color: 'var(--beam)' } : {} }, r.tool),
                  ce('td', null, r.price),
                  ce('td', null, r.kw),
                  ce('td', null, r.freq),
                  ce('td', null, Check(r.audit)),
                  ce('td', null, Check(r.wcag)),
                  ce('td', null, r.mig === '-' ? ce('span', { className: 'pi-check-n' }, '--') : ce('span', { style: { color: 'var(--beam)' } }, r.mig))
                );
              })
            )
          )
        ),
        ce('div', { style: { marginTop: 10, fontSize: 11, color: 'var(--dim)' } }, '* Moz Starter = rank tracking only, 1 site. ** Ahrefs = weekly only at all price points, confirmed.')
      ),

      /* Competitor: AEO/LLM tools */
      ce(Section, { title: 'Competitor Stack -- AEO / LLM Visibility', badge: 'GEO Phase 1.5b', defaultOpen: false },
        ce('div', { style: { overflowX: 'auto' } },
          ce('table', { className: 'pi-ref-table' },
            ce('thead', null,
              ce('tr', null, ['Tool', 'Price', 'Platforms', 'WP Native', 'Agency WF'].map(function (h) { return ce('th', { key: h }, h); }))
            ),
            ce('tbody', null,
              COMP_AEO.map(function (r) {
                return ce('tr', { key: r.tool, className: r.hi ? 'hi' : '' },
                  ce('td', { style: r.hi ? { fontWeight: 600, color: 'var(--beam)' } : {} }, r.tool),
                  ce('td', null, r.price),
                  ce('td', null, r.platforms),
                  ce('td', null, Check(r.wp)),
                  ce('td', null, Check(r.agency))
                );
              })
            )
          )
        ),
        ce('div', { style: { marginTop: 10, fontSize: 11, color: 'var(--dim)' } }, 'GEO Visibility $49/domain/mo ships Phase 1.5b (90-120d post-launch). Undercuts Searchable Starter ($50) by $1 with WP-native workflow advantage.')
      ),

      /* Competitor: content automation */
      ce(Section, { title: 'Competitor Stack -- Content Automation', badge: 'Phase 2 / $39', defaultOpen: false },
        ce('div', { style: { overflowX: 'auto' } },
          ce('table', { className: 'pi-ref-table' },
            ce('thead', null,
              ce('tr', null, ['Tool', 'Price', 'Articles/mo', 'Auto-publish WP', 'Approval gate'].map(function (h) { return ce('th', { key: h }, h); }))
            ),
            ce('tbody', null,
              COMP_CONTENT.map(function (r) {
                return ce('tr', { key: r.tool, className: r.hi ? 'hi' : '' },
                  ce('td', { style: r.hi ? { fontWeight: 600, color: 'var(--beam)' } : {} }, r.tool),
                  ce('td', null, r.price),
                  ce('td', null, r.articles),
                  ce('td', null, Check(r.autopub)),
                  ce('td', null, Check(r.approval))
                );
              })
            )
          )
        ),
        ce('div', { style: { marginTop: 10, fontSize: 11, color: 'var(--dim)' } }, 'WPSB $39/mo = 59% cheaper than AutoSEO/BabyLoveGrowth ($99). Human-approval-before-publish differentiates on quality. Phase 2 / Q1 2027.')
      ),

      /* Add-on margins ref */
      ce(Section, { title: 'Add-on Margins Reference', badge: '90%+ all', defaultOpen: false },
        ce('div', { style: { overflowX: 'auto' } },
          ce('table', { className: 'pi-ref-table' },
            ce('thead', null,
              ce('tr', null, ['Add-on', 'Price', 'GM (raw)', 'GM (cached)', 'Phase'].map(function (h) { return ce('th', { key: h }, h); }))
            ),
            ce('tbody', null,
              [
                { name: 'Daily upgrade (Starter)', price: '$39/mo', raw: 98.6, cached: 98.6, phase: '1.5a' },
                { name: 'Daily upgrade (Pro)',      price: '$79/mo', raw: 98.2, cached: 98.2, phase: '1.5a' },
                { name: 'Daily upgrade (Agency)',   price: '$149/mo',raw: 98.6, cached: 98.6, phase: '1.5a' },
                { name: 'Boost S (+300 kw)',        price: '$9/mo',  raw: 92.0, cached: 95.2, phase: '1.5a' },
                { name: 'Boost M (+750 kw)',        price: '$19/mo', raw: 90.5, cached: 94.3, phase: '1.5a' },
                { name: 'Boost L (+1,500 kw)',      price: '$39/mo', raw: 90.8, cached: 94.5, phase: '1.5a' },
                { name: 'Boost XL (+3,000 kw)',     price: '$79/mo', raw: 90.9, cached: 94.5, phase: '1.5a' },
                { name: 'GEO Visibility',           price: '$49/domain/mo', raw: 96.8, cached: 97.9, phase: '1.5b' },
                { name: 'Content Module',           price: '$39/mo', raw: 89.7, cached: 94.9, phase: '2' },
              ].map(function (r) {
                return ce('tr', { key: r.name },
                  ce('td', null, r.name),
                  ce('td', null, r.price),
                  ce('td', null, ce('span', { className: marginClass(r.raw) }, pct(r.raw))),
                  ce('td', null, ce('span', { className: marginClass(r.cached) }, pct(r.cached))),
                  ce('td', { style: { color: 'var(--dim)', fontSize: 11 } }, r.phase)
                );
              })
            )
          )
        )
      )
    );
  }

  /* ===============================================================
     MAIN COMPONENT
  =============================================================== */
  function PricingIntelligence() {
    injectCSS();

    var _tab = _useState('calculator');
    var mainTab = _tab[0]; var setMainTab = _tab[1];

    return ce('div', { className: 'pi-wrap', style: { padding: '0 2px' } },
      /* Header */
      ce('div', { style: { display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 4, flexWrap: 'wrap' } },
        ce('h2', { style: { fontSize: 16, fontWeight: 700, color: 'var(--text)', margin: 0 } }, 'Pricing Intelligence'),
        ce('span', { className: 'pi-badge pi-badge-info' }, 'SA only'),
        ce('span', { style: { fontSize: 11, color: 'var(--dim)', marginLeft: 'auto' } }, 'Source: _PLATFORM-LIMITS-AND-PRICING.md + MASTER-PRICING-REFERENCE.md')
      ),
      ce('div', { style: { fontSize: 12, color: 'var(--dim)', marginBottom: 16 } }, 'Interactive P&L model + competitive pricing stacks + margin reference.'),

      /* Main tabs */
      ce('div', { className: 'pi-tabs' },
        ce('button', { className: 'pi-tab' + (mainTab === 'calculator' ? ' active' : ''), onClick: function () { setMainTab('calculator'); } }, 'Revenue Model'),
        ce('button', { className: 'pi-tab' + (mainTab === 'reference' ? ' active' : ''), onClick: function () { setMainTab('reference'); } }, 'Pricing Reference')
      ),

      mainTab === 'calculator' ? ce(RevenueModel, null) : ce(PricingReference, null),

      ce('div', { style: { fontSize: 10, color: 'var(--dimmer, #64748b)', textAlign: 'center', padding: '12px 0 4px' } }, 'v' + VERSION + ' -- update TIER_CONFIG / ADDON_CONFIG at top of PricingIntelligence.jsx when pricing changes')
    );
  }

  window.PricingIntelligence = PricingIntelligence;

})();
