/* The module catalogue every page sells from: what each module is for, who
   buys it, what the analysis hands over, and the beta price (the server's
   figure replaces the fallback the moment /api/pay answers). One source, so
   the home page finder, /modules/, /pricing/, the demos and the start flow
   never disagree about a price or a promise. */

const MODULE_CATALOG = [
  { id: 'visibility', title: 'AI visibility', status: 'live', product: null, fallback: 0, unit: 'to start',
    problem: 'Buyers ask ChatGPT, Perplexity and Gemini, and you are not the answer.',
    goal: 'Be the business AI recommends', verb: 'Be found',
    who: 'Founders, marketing leads and agencies who need buyers to find them.',
    gets: ['How AI reads your site today, free, in minutes', 'Every fix in order with ready-to-paste files ($499 full report)', 'The engine benchmark: who gets named, where you lose'],
    time: 'Free report in about two minutes. Full report within 24 hours.',
    start: '/#audit', demo: '/r/?c=120-life', startLabel: 'Get the free report' },
  { id: 'stack', title: 'Stack intelligence', status: 'beta', product: 'module_stack', fallback: 990, unit: 'per organization',
    problem: 'Software spend keeps growing and nobody can say what is used, what overlaps, or where an agent could take the work.',
    goal: 'Cut software spend and find agent work', verb: 'See the stack',
    who: 'The COO, CFO or head of IT who signs the renewals.',
    gets: ['Every subscription graded: cost, seats, idle seats, overlap', 'Where an agent could take the work, with the hours and money', 'Includes Execute: the opportunity ledger, approvals and roadmap'],
    time: 'First insights in minutes. The full analysis unlocks the moment you pay.' },
  { id: 'operations', title: 'Operations', status: 'beta', product: 'module_operations', fallback: 1900, unit: 'per organization', sensitive: true,
    problem: 'Processes run on habit and spreadsheets, and every automation pitch skips the step a person must still decide.',
    goal: 'Redesign a process around agents', verb: 'Map the work',
    who: 'Operations leaders and the team leads who run the work day to day.',
    gets: ['Each process mapped across the systems it runs on', 'The step an agent may take and the step a person must decide, by policy', 'Redesign economics per process, handed to the roadmap'],
    time: 'First insights in minutes. The full analysis unlocks the moment you pay.' },
  { id: 'workforce', title: 'Workforce', status: 'beta', product: 'module_workforce', fallback: 2900, unit: 'per organization', sensitive: true,
    problem: 'You need to plan the shape of the organization as automation lands, without a spreadsheet of names.',
    goal: 'Plan the organization for the next 24 months', verb: 'Plan the team',
    who: 'The CEO and the head of people planning the shape of the organization.',
    gets: ['Roles mapped to capabilities and the repetitive hours in each', 'Organization scenarios at 12 and 24 months', 'Transition and skills plans at band level, never individual decisions'],
    time: 'First insights in minutes. The full analysis unlocks the moment you pay.' },
  { id: 'strategy', title: 'Strategy', status: 'beta', product: 'module_strategy', fallback: 3900, unit: 'per organization', sensitive: true,
    problem: 'The board wants to know what to do first and what it is worth under more than one view of the future.',
    goal: 'Decide what to do first, and what to promise', verb: 'Set the strategy',
    who: 'The CEO, CFO and board deciding priorities and commitments.',
    gets: ['The opportunity ledger under conservative, base and aggressive assumptions', 'Operating-model scenarios: tidy first, automate first', 'The P&L lines each initiative moves'],
    time: 'First insights in minutes. The full analysis unlocks the moment you pay.' },
  { id: 'mna', title: 'M&A and NewCo', status: 'beta', product: 'module_mna', fallback: 7900, unit: 'per transaction', sensitive: true,
    problem: 'Two organizations, two stacks, two sets of contracts, and a synergy number nobody can trace.',
    goal: 'Assess a deal or a merger', verb: 'Assess the deal',
    who: 'Acquirers, founders merging, and the deal teams and advisers around them.',
    gets: ['Both organizations assessed with the same templates and evidence standards', 'Overlapping software, contracts and capabilities reconciled into one NewCo stack', 'Synergies graded and tracked, with migration cost and timeline'],
    time: 'First insights in minutes. The full analysis unlocks the moment you pay.' },
  { id: 'portfolio', title: 'Portfolio', status: 'beta', product: 'module_portfolio', fallback: 14900, unit: 'per fund', sensitive: true,
    problem: 'Ten portfolio companies, ten views of spend and opportunity, and no way to compare them without overstepping.',
    goal: 'Run a portfolio on shared evidence', verb: 'See the portfolio',
    who: 'Private-equity operating partners and portfolio operations teams.',
    gets: ['The fund view across the companies that share: stack, spend, opportunities, EBITDA levers', 'Consent recorded on the company side; benchmarks on shared metrics only', 'Up to ten companies in one fund workspace'],
    time: 'First insights in minutes. The full analysis unlocks the moment you pay.' },
];
const MODULE_BY_ID = Object.fromEntries(MODULE_CATALOG.map((m) => [m.id, m]));

/* What every buyer wants to know before paying, answered once. */
const MODULE_PROMISES = [
  ['lock', 'The price is the price', 'Beta prices are fixed and one-time for the analysis and the strategy: per organization, per transaction for M&A, per fund for Portfolio. No quote to wait for.'],
  ['eye', 'Look before you pay', 'The first insights of every module are free on your analysis page, with an evidence grade on every fact. Unlock when it has earned it.'],
  ['clock', 'Minutes, not weeks', 'Your analysis starts the moment you send the first screen. Findings and recommendations unlock the moment you pay. A 45-minute strategy walkthrough with the founders follows.'],
  ['shield', 'Nothing is guessed', 'What Lojo cannot know (contracts, private terms) is listed as a gap with what would change once provided. Never estimated and passed off as fact.'],
  ['zap', 'Then run it in the workspace', 'Execution runs in the Lojo workspace on a monthly fee by the modules you keep live and the seats you use. The first 30 days are included with any analysis; cancel any time and your data stays readable and exportable.'],
  ['bot', 'Implement it your way', 'Your own people, a partner you bring, or a Lojo preferred partner. Every external implementer is approved by Lojo and signs a strict confidentiality agreement before they see a record. Lojo does not do the implementation itself.'],
  ['doc', 'Sensitive detail under NDA only', 'Nothing sensitive is asked for before a mutual NDA, signed on the page or your own. Your inputs train no shared model and are seen only by the founders.'],
];

/* The workspace, monthly: the fallbacks the server's figures replace. */
const WORKSPACE_FALLBACK = { base: { usd: 490, seats_included: 3 }, seat: { usd: 49 },
  modules: { stack: { usd: 290, unit: 'per organization' }, operations: { usd: 490, unit: 'per organization' }, workforce: { usd: 690, unit: 'per organization' },
    strategy: { usd: 890, unit: 'per organization' }, mna: { usd: 1490, unit: 'per transaction' }, portfolio: { usd: 2490, unit: 'per fund' } } };
const WORKSPACE_INCLUDES = ['Execute: the opportunity ledger, approvals with a reason, actuals against forecast, the roadmap', 'Three member seats; approved implementation partners never use a seat',
  'Add answers and files and re-run any analysis you own', 'Invite your own people, a partner you bring, or a Lojo preferred partner', 'The audit log, exports, and your data readable even after you cancel'];

/* One anonymous count per page open, for the team's funnel. Never a visitor id. */
function countOpen(kind) {
  try {
    const tag = document.querySelector('meta[name="lojo-api-base"]');
    fetch(((tag && tag.content) || '').replace(/\/+$/, '') + '/api/lojo', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ module: 'metrics', action: 'hit', kind }), keepalive: true }).catch(() => {});
  } catch (e) { /* the page matters more than the count */ }
}
function moduleStartUrl(m) { return m.start || ('/app/?start=' + m.id); }
function moduleDemoUrl(m) { return m.demo || ('/app/?demo=1&m=' + m.id); }
function moduleSampleUrl(m) { return m.status === 'live' ? '/r/?c=120-life' : '/app/?analysis=sample#module-' + m.id; }
function moduleMoney(n) { return '$' + Number(n || 0).toLocaleString('en-US'); }

/* Prices from the server, cached for the page. `prices[id]` is {usd, unit}
   per module id; `enabled` says whether Checkout is switched on. */
function useModulePrices() {
  const [state, setState] = React.useState(() => window.__lojoPrices || { prices: {}, enabled: false, loaded: false, workspace: WORKSPACE_FALLBACK });
  React.useEffect(() => {
    if (state.loaded) return;
    const tag = document.querySelector('meta[name="lojo-api-base"]');
    fetch(((tag && tag.content) || '').replace(/\/+$/, '') + '/api/pay').then((r) => r.json()).then((d) => {
      const prices = {};
      Object.entries((d && d.module_prices) || {}).forEach(([product, p]) => { prices[p.module] = { usd: p.usd, unit: p.unit, product }; });
      if (d && d.prices && d.prices.full_report) prices.visibility = { usd: 0, unit: 'to start', full: d.prices.full_report.usd };
      window.__lojoPrices = { prices, enabled: !!(d && d.enabled), loaded: true, workspace: (d && d.workspace) || WORKSPACE_FALLBACK };
      setState(window.__lojoPrices);
    }).catch(() => setState({ prices: {}, enabled: false, loaded: true, workspace: WORKSPACE_FALLBACK }));
  }, []);
  return state;
}
function modulePrice(m, prices) { const p = prices && prices[m.id]; return p && p.usd !== undefined ? p.usd : m.fallback; }

/* The workspace price table, rendered the same everywhere. */
function WorkspacePricing({ workspace, compact }) {
  const w = workspace || WORKSPACE_FALLBACK;
  const rows = Object.entries(w.modules || {}).map(([id, p]) => [(MODULE_BY_ID[id] || {}).title || id, p.usd, p.unit]);
  return (
    <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
      <div style={{ display: 'grid', gridTemplateColumns: compact ? '1fr' : 'minmax(0, 1fr) minmax(0, 1fr)' }}>
        <div style={{ padding: 'clamp(18px,2.4vw,26px)', borderRight: compact ? 'none' : '1px solid var(--line)', borderBottom: compact ? '1px solid var(--line)' : 'none' }}>
          <div className="overline" style={{ marginBottom: 8 }}>Workspace · monthly</div>
          <div className="display" style={{ fontSize: 'clamp(28px,3vw,36px)', lineHeight: 1 }}>{moduleMoney(w.base.usd)}<span style={{ fontSize: 13, fontFamily: 'var(--font-sans)', fontWeight: 400, color: 'var(--fg-muted)', marginLeft: 8 }}>per month</span></div>
          <div style={{ fontSize: 13, color: 'var(--fg-muted)', margin: '6px 0 12px' }}>Includes Execute and {w.base.seats_included} seats. Extra seats {moduleMoney(w.seat.usd)} each per month.</div>
          <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 7 }}>
            {WORKSPACE_INCLUDES.map((t) => <li key={t} style={{ display: 'flex', gap: 8, fontSize: 13.5, lineHeight: 1.5 }}><span style={{ color: 'var(--accent)', marginTop: 2, flex: '0 0 auto' }}><Icon name="check" size={14} stroke={2.4} /></span>{t}</li>)}
          </ul>
        </div>
        <div style={{ padding: 'clamp(18px,2.4vw,26px)' }}>
          <div className="overline" style={{ marginBottom: 8 }}>Modules kept live · per month</div>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}><tbody>
            {rows.map(([t, usd, unit]) => <tr key={t} style={{ borderTop: '1px solid var(--line)' }}><td style={{ padding: '8px 0' }}>{t}<span style={{ color: 'var(--fg-subtle)', fontSize: 12 }}> · {unit}</span></td><td className="mono" style={{ textAlign: 'right', padding: '8px 0', color: 'var(--accent)' }}>+{moduleMoney(usd)}</td></tr>)}
          </tbody></table>
          <div style={{ fontSize: 12.5, color: 'var(--fg-subtle)', marginTop: 10, lineHeight: 1.55 }}>The first 30 days are included with any analysis you buy. Switch modules on and off and change seats any month; cancel any time. Card through Stripe.</div>
        </div>
      </div>
    </div>);
}

Object.assign(window, { MODULE_CATALOG, MODULE_BY_ID, MODULE_PROMISES, WORKSPACE_FALLBACK, WORKSPACE_INCLUDES, WorkspacePricing, countOpen, moduleStartUrl, moduleDemoUrl, moduleSampleUrl, moduleMoney, useModulePrices, modulePrice });
