// Interactive — Segmentation explorer, Funnel, Timeline, Routes
const { useState: useStateI, Fragment: FragI } = React;

// ---------- Segmentation Explorer ----------
const SEG_AXES = [
  {
    id: 'thesis',
    label: 'Investment thesis',
    hint: 'one or more',
    options: ['Real estate', 'Private credit', 'Growth equity', 'Venture', 'Alternative income'],
    multi: true,
  },
  {
    id: 'geo',
    label: 'Geography',
    hint: 'Canadian provinces',
    options: ['BC', 'AB', 'ON', 'QC', 'Other'],
    multi: true,
  },
  {
    id: 'tier',
    label: 'Accreditation tier',
    hint: 'verified',
    options: ['Institutional', 'Family office', 'Wealth managers', 'HNW accredited', 'Eligible investor'],
    multi: true,
  },
  {
    id: 'check',
    label: 'Check-size capacity',
    hint: 'minimum commitment',
    options: ['$50K–$100K', '$100K–$250K', '$250K–$1M', '$1M+'],
    multi: false,
  },
  {
    id: 'engage',
    label: 'Engagement signal',
    hint: 'recency of contact',
    options: ['Subscribed prior deal', 'Webinar attendee', 'Warm lead', 'Cold opt-in'],
    multi: true,
  },
];

const SEG_DEFAULTS = {
  thesis: ['Real estate', 'Alternative income'],
  geo: ['BC', 'AB', 'ON'],
  tier: ['HNW accredited', 'Family office'],
  check: '$100K–$250K',
  engage: ['Subscribed prior deal', 'Warm lead'],
};

// Deterministic pseudo-population — gives a stable readout for any filter combo.
// Base = total database (~2.3M). Filter factors collapse it to the "addressable
// subset" for the opportunity at hand.
function populationFor(state) {
  let n = 2300000;
  const factors = {
    thesis: { 'Real estate': 0.55, 'Private credit': 0.36, 'Growth equity': 0.28, 'Venture': 0.20, 'Alternative income': 0.45 },
    geo: { 'BC': 0.20, 'AB': 0.18, 'ON': 0.40, 'QC': 0.18, 'Other': 0.10 },
    tier: { 'Institutional': 0.008, 'Family office': 0.022, 'Wealth managers': 0.18, 'HNW accredited': 0.08, 'Eligible investor': 0.30 },
    engage: { 'Subscribed prior deal': 0.10, 'Webinar attendee': 0.15, 'Warm lead': 0.18, 'Cold opt-in': 0.42 },
  };
  const check = { '$50K–$100K': 0.62, '$100K–$250K': 0.51, '$250K–$1M': 0.22, '$1M+': 0.07 }[state.check] || 1;
  let mult = check;
  for (const ax of ['thesis', 'geo', 'tier', 'engage']) {
    const sum = (state[ax] || []).reduce((s, o) => s + (factors[ax][o] || 0), 0);
    mult *= Math.min(1, sum);
  }
  return Math.max(220, Math.round(n * mult));
}

function summaryFor(state) {
  const t = (state.thesis || []).slice(0, 2).join(' · ') || 'all theses';
  const g = (state.geo || []).join('/') || 'all provinces';
  const tier = (state.tier || []).slice(0, 2).join(' & ') || 'all tiers';
  return `${tier} in ${g}, weighted to ${t}, ${state.check || 'any check'}.`;
}

function SegmentationExplorer() {
  const [state, setState] = useStateI(SEG_DEFAULTS);
  const togglePill = (axis, opt) => {
    setState(s => {
      if (axis.multi) {
        const cur = s[axis.id] || [];
        return { ...s, [axis.id]: cur.includes(opt) ? cur.filter(x => x !== opt) : [...cur, opt] };
      } else {
        return { ...s, [axis.id]: s[axis.id] === opt ? null : opt };
      }
    });
  };
  const isActive = (axis, opt) => axis.multi
    ? (state[axis.id] || []).includes(opt)
    : state[axis.id] === opt;
  const pop = populationFor(state);
  return (
    <div className="seg-shell">
      <div className="seg-controls">
        {SEG_AXES.map(axis => (
          <div className="seg-axis" key={axis.id}>
            <div className="seg-axis-label">
              <span>{axis.label}</span>
              <span className="seg-axis-hint">{axis.hint}</span>
            </div>
            <div className="seg-pills">
              {axis.options.map(opt => (
                <button
                  key={opt}
                  className={`seg-pill ${isActive(axis, opt) ? 'is-active' : ''}`}
                  onClick={() => togglePill(axis, opt)}
                >{opt}</button>
              ))}
            </div>
          </div>
        ))}
      </div>
      <aside className="seg-readout">
        <div className="seg-readout-top">Live database query</div>
        <div>
          <div className="seg-readout-figure">
            {pop.toLocaleString('en-CA')}
            <small>verified investors matching</small>
          </div>
        </div>
        <div className="seg-readout-summary">{summaryFor(state)}</div>
        <div className="seg-readout-note">
          Indicative figures. Actual database population is updated daily and
          will be reconfirmed inside Anthem's branded retail community at activation.
        </div>
      </aside>
    </div>
  );
}

// ---------- Meta Funnel ----------
const FUNNEL_STAGES = [
  {
    label: 'Targeted impression',
    fill: 100,
    pct: '∞',
    detail: {
      title: 'Targeted impression',
      eyebrow: 'Stage 01 · Meta delivery',
      body: 'Behavioral, demographic, and lookalike layering on Meta (Facebook and Instagram). Audiences are calibrated to HNW professional profiles: executives, professional services, established business owners, prior subscribers to alternative-asset platforms.',
      mech: [
        ['Inventory', 'Facebook Feed, Instagram Reels, Instagram Feed'],
        ['Targeting', 'Behavioral + demographic + interest layering, modeled on prior subscriber LTV'],
        ['Creative', 'Anthem-branded short-form video, static editorial, founder POV'],
        ['Cadence', 'Always-on at low burn; surge during active capital calls'],
      ],
    },
  },
  {
    label: 'Lead-form open',
    fill: 18,
    pct: '~18%',
    detail: {
      title: 'Lead-form open',
      eyebrow: 'Stage 02 · Native lead form',
      body: 'Native Meta lead form opens in-platform. No off-app jump, no broken intent. The form is the first compliance gate, not a marketing brochure. Copy is built in the Anthem voice and previewed inside the panel below before launch.',
      mech: [
        ['Form fields', 'Name · email · phone · province · accreditation self-attestation'],
        ['Conversion lever', 'Pre-filled identity from Meta profile, single-screen submit'],
        ['Compliance posture', 'NI 31-103 / NI 45-106 language reviewed by counsel pre-launch'],
        ['Drop-off recovery', 'Auto-saved partial submissions re-targeted at 24h and 7d'],
      ],
    },
  },
  {
    label: 'Cheque-size confirm ≥ $50K',
    fill: 11,
    pct: '~11%',
    detail: {
      title: 'Cheque-size confirmation',
      eyebrow: 'Stage 03 · Self-qualification',
      body: 'A binary cheque-size attestation gates the pool: prospects who cannot commit a $50,000 minimum exit here. This collapses paid spend onto investors whose stated capacity matches the fund\'s admission profile.',
      mech: [
        ['Floor', '$50,000 minimum subscription (adjustable per call)'],
        ['Method', 'Self-attested in lead form; verified during diligence call'],
        ['Effect', 'Removes ~40% of raw leads. The right ~40%.'],
        ['Override', 'Smaller cheques routed to a separate nurture stream for future calls'],
      ],
    },
  },
  {
    label: 'Accredited / eligible status',
    fill: 6,
    pct: '~6%',
    detail: {
      title: 'Accredited / eligible verification',
      eyebrow: 'Stage 04 · Status verification',
      body: 'No prospect enters the active outreach pool without verified status under National Instrument 45-106. Documentation is requested through a secure intake portal. This is the gate that protects compliance and concentrates spend on real, deployable capital.',
      mech: [
        ['Standards', 'NI 45-106 §1.1 · Accredited investor / Eligible investor'],
        ['Documentation', 'Income, financial-asset, or net-worth attestation + supporting evidence'],
        ['Storage', 'Encrypted intake with audit trail. Retained for jurisdictional minimum'],
        ['Output', 'Tagged record in the database, segmentable for every future call'],
      ],
    },
  },
  {
    label: 'Diligence call booked',
    fill: 3.6,
    pct: '~3.6%',
    detail: {
      title: 'Diligence call booked',
      eyebrow: 'Stage 05 · Senior conversation',
      body: 'A Savvy team member runs a 30-minute diligence call: confirms thesis fit, walks the deck, surfaces objections, and matches the prospect to the appropriate cheque slot. Anthem stays out of these conversations unless they want in.',
      mech: [
        ['Owner', 'Savvy investor-relations team. Senior, named, on-record.'],
        ['Materials', 'Anthem-branded teaser, IC memo, PPM summary, fund factsheet'],
        ['Outcome', 'Verbal commitment, soft commit, or graceful exit'],
        ['Anthem optionality', 'Co-attended on request, otherwise weekly digest only'],
      ],
    },
  },
  {
    label: 'Subscription closed',
    fill: 2.1,
    pct: '~2.1%',
    detail: {
      title: 'Subscription closed',
      eyebrow: 'Stage 06 · Capital in the SPV',
      body: 'Subscription docs are executed, wires are received, and capital is held inside a Savvy-managed SPV that subscribes upstream to the Anthem vehicle as a single LP, keeping Anthem clear of individual investor relations unless that is the preferred route.',
      mech: [
        ['Vehicle', 'Savvy-managed SPV (or direct, at Anthem\'s election)'],
        ['Custody', 'Investor wires received and reconciled by Savvy ops'],
        ['Anthem-facing', 'A single LP entry on the Anthem cap table'],
        ['Ongoing IR', 'Quarterly statements and tax docs issued by Savvy to LPs'],
      ],
    },
  },
];

function Funnel() {
  const [active, setActive] = useStateI(3);
  const stage = FUNNEL_STAGES[active];
  return (
    <div className="funnel-shell">
      <div className="funnel">
        {FUNNEL_STAGES.map((s, i) => (
          <div
            key={i}
            className={`funnel-stage ${i === active ? 'is-active' : ''}`}
            onClick={() => setActive(i)}
            onMouseEnter={() => setActive(i)}
          >
            <div className="funnel-num">{String(i + 1).padStart(2, '0')}</div>
            <div className="funnel-mid">
              <div className="funnel-label">{s.label}</div>
              <div className="funnel-bar">
                <span className="funnel-bar-fill" style={{ width: `${Math.max(2, s.fill)}%` }} />
              </div>
            </div>
            <div className="funnel-pct">{s.pct}</div>
          </div>
        ))}
      </div>
      <div className="funnel-detail">
        <div className="funnel-detail-eyebrow">{stage.detail.eyebrow}</div>
        <div className="funnel-detail-title">{stage.detail.title}</div>
        <div className="funnel-detail-body">{stage.detail.body}</div>
        <dl className="funnel-detail-mech">
          {stage.detail.mech.map(([k, v]) => (
            <div className="funnel-detail-mech-row" key={k}>
              <dt>{k}</dt>
              <dd>{v}</dd>
            </div>
          ))}
        </dl>
      </div>
    </div>
  );
}

// ---------- Timeline comparison ----------
function TimelineCompare() {
  const [mode, setMode] = useStateI('warm');
  // 0..120 days
  const ticks = [0, 30, 60, 90, 120];
  return (
    <div className="timeline-shell">
      <div className="timeline-toggle">
        <button className={mode === 'cold' ? 'is-active' : ''} onClick={() => setMode('cold')}>Cold start</button>
        <button className={mode === 'warm' ? 'is-active' : ''} onClick={() => setMode('warm')}>Always-on engine</button>
      </div>
      <div className="timeline">
        <div className="timeline-axis">
          {ticks.flatMap(t => [
            <span key={`t${t}`} className="timeline-tick" style={{ left: `${(t / 120) * 100}%` }} />,
            <span key={`l${t}`} className="timeline-tick-label" style={{ left: `${(t / 120) * 100}%` }}>
              {t === 0 ? 'Day 0' : `Day ${t}`}
            </span>
          ])}
          {mode === 'cold' ? [
              <span key="a" className="timeline-block cold" style={{ left: '0%', width: '50%' }}>
                Audience build · qualification · warm-up
              </span>,
              <span key="b" className="timeline-block live" style={{ left: '50%', width: '50%' }}>
                Capital deployable
              </span>
          ] : (
              <span className="timeline-block warm" style={{ left: '0%', width: '100%' }}>
                Audience already qualified · capital deployable from day 0
              </span>
          )}
        </div>
      </div>
      <div className="timeline-readout">
        {mode === 'cold' ? [
            <div key="r">
              <div className="timeline-stat-num">60–90<span style={{fontSize: 28}}>d</span></div>
              <div className="timeline-stat-label">Ramp time</div>
              <div className="timeline-stat-body">Typical wait before a fresh retail raise can close meaningful capital.</div>
            </div>,
            <div key="a">
              <div className="timeline-stat-num">~3×</div>
              <div className="timeline-stat-label">Acquisition cost</div>
              <div className="timeline-stat-body">CPL under active-call urgency runs materially higher than steady-state.</div>
            </div>,
            <div key="x">
              <div className="timeline-stat-num">High</div>
              <div className="timeline-stat-label">Execution risk</div>
              <div className="timeline-stat-body">Audience is unfamiliar with the sponsor; objections compress into a tight window.</div>
            </div>
        ] : [
            <div key="r">
              <div className="timeline-stat-num">0d</div>
              <div className="timeline-stat-label">Ramp time</div>
              <div className="timeline-stat-body">Audience is already accredited, segmented, and educated when a call goes live.</div>
            </div>,
            <div key="a">
              <div className="timeline-stat-num">−40 to 60%</div>
              <div className="timeline-stat-label">Acquisition cost</div>
              <div className="timeline-stat-body">Steady-state nurture spend is meaningfully lower than active-call burn.</div>
            </div>,
            <div key="x">
              <div className="timeline-stat-num">Compounding</div>
              <div className="timeline-stat-label">Per-call yield</div>
              <div className="timeline-stat-body">Each deployment leaves a larger, warmer audience for the next one.</div>
            </div>
        ]}
      </div>
    </div>
  );
}

// ---------- Routes ----------
function Routes() {
  return (
    <div className="routes-shell">
      <div className="route">
        <div className="route-eyebrow">Route A · Direct</div>
        <div className="route-title">Direct subscription to the Anthem vehicle</div>
        <div className="route-diagram">
          <div className="route-node">Qualified<br/>investor</div>
          <div className="route-arrow">→</div>
          <div className="route-node is-gold">Savvy<br/>diligence</div>
          <div className="route-arrow">→</div>
          <div className="route-node is-anthem">Anthem<br/>vehicle</div>
        </div>
        <dl className="route-detail">
          <div className="route-detail-row"><dt>Cap table</dt><dd>One LP entry per investor</dd></div>
          <div className="route-detail-row"><dt>IR / reporting</dt><dd>Handled by Anthem</dd></div>
          <div className="route-detail-row"><dt>Best for</dt><dd>Calls where Anthem prefers direct investor relationships</dd></div>
          <div className="route-detail-row"><dt>Savvy role</dt><dd>Acquisition, qualification, close-out</dd></div>
        </dl>
      </div>
      <div className="route is-recommended">
        <div className="route-eyebrow">Route B · SPV</div>
        <div className="route-title">Subscription via a Savvy-managed SPV</div>
        <div className="route-diagram">
          <div className="route-node">Qualified<br/>investor</div>
          <div className="route-arrow">→</div>
          <div className="route-node is-gold">Savvy SPV<br/>(manager)</div>
          <div className="route-arrow">→</div>
          <div className="route-node is-anthem">Anthem<br/>vehicle</div>
        </div>
        <dl className="route-detail">
          <div className="route-detail-row"><dt>Cap table</dt><dd>Single LP entry: the SPV</dd></div>
          <div className="route-detail-row"><dt>IR / reporting</dt><dd>Held by Savvy, end-to-end</dd></div>
          <div className="route-detail-row"><dt>Best for</dt><dd>Calls where Anthem wants to stay clear of individual IR</dd></div>
          <div className="route-detail-row"><dt>Savvy role</dt><dd>Acquisition, qualification, close, custody, reporting</dd></div>
        </dl>
      </div>
    </div>
  );
}

Object.assign(window, { SegmentationExplorer, Funnel, TimelineCompare, Routes });
