// narrio-shared.jsx — small components reused across all 3 variants
// Exposed on window so other Babel scripts can pick them up.

// ─────────────────────────────────────────────────────────────
// NavBar — same nav across all 3 variants. Difference is purely in copy weight.
// ─────────────────────────────────────────────────────────────
function NarrioNav({ ctaLabel = 'Apply', tone = 'default' }) {
  return (
    <nav style={{
      position: 'sticky', top: 0, zIndex: 50, height: 64,
      display: 'flex', alignItems: 'center',
      background: 'color-mix(in srgb, var(--bg) 92%, transparent)',
      backdropFilter: 'blur(20px)',
      borderBottom: '.5px solid var(--bd)',
    }}>
      <div style={{ width: '100%', maxWidth: 1280, margin: '0 auto', padding: '0 40px',
        display: 'grid', gridTemplateColumns: '180px 1fr 280px', alignItems: 'center', gap: 24 }}>
        <a href="editorial.html" style={{ display: 'flex', alignItems: 'center', gap: 9, fontWeight: 600, fontSize: 17, letterSpacing: '-0.025em' }}>
          <NarrioMark size={22} />
          <span>Narrio</span>
          <span className="lbl" style={{ fontSize: 8.5, padding: '2px 6px', border: '.5px solid var(--bd-hi)', borderRadius: 4, marginLeft: 4, color: 'var(--t2)' }}>OS</span>
        </a>
        <ul style={{ display: 'flex', gap: 32, justifyContent: 'center', listStyle: 'none', margin: 0, padding: 0 }}>
          {[['Operators','operators.html'],['Contributors','contributors.html'],['Communities','marketplace.html'],['Pricing','pricing.html'],['Field notes','blog.html']].map(([x,h]) => (
            <li key={x}><a href={h} style={{ fontSize: 13.5, color: 'var(--t2)' }}>{x}</a></li>
          ))}
        </ul>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', alignItems: 'center' }}>
          <a href="profile.html" style={{ fontSize: 13.5, color: 'var(--t2)' }}>Dashboard</a>
          <a href="apply.html" className="btn btn-pri" style={{ padding: '8px 16px', fontSize: 13 }}>{ctaLabel} →</a>
        </div>
      </div>
    </nav>
  );
}

// Logomark: a tiny "narrative arc" — solid disc with a slim arc that loops back on itself.
function NarrioMark({ size = 22, color = 'var(--ac)' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden>
      <circle cx="12" cy="12" r="11" stroke={color} strokeWidth="1" opacity=".35" />
      <path d="M5 16 C 5 8, 12 6, 14 10 S 19 16, 19 8" stroke={color} strokeWidth="1.6" strokeLinecap="round" fill="none" />
      <circle cx="5" cy="16" r="1.6" fill={color} />
      <circle cx="19" cy="8" r="1.6" fill={color} />
    </svg>
  );
}

// Footer — minimal, but signals trust.
function NarrioFooter() {
  const cols = [
    { h: 'Product', items: ['Operator OS', 'Contributor program', 'Marketplace', 'Pricing', 'Changelog'] },
    { h: 'Communities', items: ['Browse all 20', 'AI Workplace', 'Wealth Signal', 'Climate Capital', 'Longevity Stack'] },
    { h: 'Company', items: ['Manifesto', 'Press', 'Careers', 'Contact'] },
    { h: 'Legal', items: ['Terms', 'Privacy', 'What we own', 'Editor disclosure'] },
  ];
  return (
    <footer style={{ borderTop: '.5px solid var(--bd)', background: 'var(--bg-1)', padding: '64px 0 40px', marginTop: 0 }}>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 40px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr repeat(4, 1fr)', gap: 48 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
              <NarrioMark size={22} />
              <span style={{ fontWeight: 600, fontSize: 17, letterSpacing: '-0.025em' }}>Narrio</span>
            </div>
            <p style={{ color: 'var(--t2)', fontSize: 13, marginTop: 14, lineHeight: 1.6, maxWidth: 240 }}>
              The operating system for narrative businesses.
              You bring the idea. Narrio builds, runs, and evolves the business.
            </p>
            <div style={{ marginTop: 18, display: 'flex', gap: 8 }}>
              <span className="lbl" style={{ padding: '4px 9px', border: '.5px solid var(--bd-hi)', borderRadius: 999 }}>SOC 2 · Type I</span>
              <span className="lbl" style={{ padding: '4px 9px', border: '.5px solid var(--bd-hi)', borderRadius: 999 }}>GDPR</span>
            </div>
          </div>
          {cols.map((c) => (
            <div key={c.h}>
              <div className="lbl" style={{ marginBottom: 14 }}>{c.h}</div>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 8 }}>
                {c.items.map((i) => <li key={i}><a href="#" style={{ fontSize: 13, color: 'var(--t2)' }}>{i}</a></li>)}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 56, paddingTop: 24, borderTop: '.5px solid var(--bd)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12, color: 'var(--t3)' }}>
          <span>© 2025 Narrio Labs · Built for narrative operators.</span>
          <span className="mono">v1.0 · status <span style={{ color: 'var(--green)' }}>● operational</span></span>
        </div>
      </div>
    </footer>
  );
}

// ─────────────────────────────────────────────────────────────
// SystemFeed — the live "OS at work" stream, used as a hero element on
// Variant A (Terminal) and as a sidebar on Variant B (Editorial).
// ─────────────────────────────────────────────────────────────
const SYSTEM_EVENTS = [
  { t: 'DRAFT',     comm: 'Wealth Signal',     msg: 'Draft proposed · "What the bond market is pricing in"',  meta: '3 contributor reviews queued' },
  { t: 'PUBLISH',   comm: 'The AI Workplace',  msg: 'Issue #047 sent · 12,840 subscribers',                   meta: 'Open rate tracking · live' },
  { t: 'INTEL',     comm: 'Climate Capital',   msg: 'Intelligence accepted · DOE awards $1.2B in grid',       meta: '+8 pts · A. Ohanian' },
  { t: 'REVIEW',    comm: 'Longevity Stack',   msg: 'Lead Editor approved 3 drafts in 11 minutes',            meta: 'Streak 7 → 8 · 1.25× active' },
  { t: 'GROWTH',    comm: 'Creator Ledger',    msg: '+184 paid subs (24h) · referral attribution 38%',        meta: 'MoM +12.4%' },
  { t: 'ROUTE',     comm: 'Brick Intelligence',msg: 'Lead Editor on waiver · brokerage matched coverage',     meta: 'Coverage by S. Park · 14d' },
  { t: 'SPONSOR',   comm: 'SaaS Signals',      msg: 'Sponsor slot filled · $4,200 · Q3 cycle',                meta: 'Inserted in issue #122' },
  { t: 'REPUTATION',comm: 'Mind Architecture', msg: 'Contributor reached 9.0 · Community Lead unlocked',      meta: '4th community slot opened' },
  { t: 'PUBLISH',   comm: 'Zero to Operator',  msg: 'Podcast episode #18 distributed to 6 platforms',         meta: 'Avg listen 28m41s' },
  { t: 'DRAFT',     comm: 'Points Insider',    msg: 'Auto-rerouted angle: "Star Alliance devaluation"',       meta: 'Audience signal: 2.4× normal' },
  { t: 'GROWTH',    comm: 'Frontier Markets',  msg: 'Subscriber milestone · 1,000 paid',                      meta: 'Transfer activation cleared' },
  { t: 'INTEL',     comm: 'Breach Brief',      msg: '14 intelligence items submitted this week',              meta: 'Intel→publish rate 71%' },
];

function eventDot(t) {
  const map = {
    DRAFT: 'var(--blue)', PUBLISH: 'var(--green)', INTEL: 'var(--amber)',
    REVIEW: 'var(--ac)', GROWTH: 'var(--green)', ROUTE: 'var(--purple)',
    SPONSOR: 'var(--teal)', REPUTATION: 'var(--ac)',
  };
  return map[t] || 'var(--ac)';
}

function useTickingFeed(speed = 1800, depth = 8) {
  const [events, setEvents] = React.useState(() => SYSTEM_EVENTS.slice(0, depth).map((e, i) => ({ ...e, id: i, age: i })));
  const counter = React.useRef(SYSTEM_EVENTS.length);
  React.useEffect(() => {
    const tick = () => {
      setEvents((prev) => {
        const next = SYSTEM_EVENTS[counter.current % SYSTEM_EVENTS.length];
        counter.current += 1;
        const updated = [{ ...next, id: counter.current, age: 0 }, ...prev.map((e) => ({ ...e, age: e.age + 1 }))];
        return updated.slice(0, depth);
      });
    };
    const id = setInterval(tick, speed);
    return () => clearInterval(id);
  }, [speed, depth]);
  return events;
}

// ─────────────────────────────────────────────────────────────
// Counters
// ─────────────────────────────────────────────────────────────
function Stat({ k, v, sub, trend, mono = true }) {
  return (
    <div style={{ display: 'grid', gap: 6 }}>
      <div className="lbl">{k}</div>
      <div className={mono ? 'mono num' : 'num'} style={{ fontSize: 28, color: 'var(--t1)', fontWeight: 500, letterSpacing: '-0.02em', lineHeight: 1.05 }}>{v}</div>
      {sub && <div style={{ fontSize: 12, color: 'var(--t2)', display: 'flex', alignItems: 'center', gap: 6 }}>
        {trend && <span style={{ color: trend === 'up' ? 'var(--green)' : trend === 'down' ? 'var(--red)' : 'var(--t3)', fontSize: 11 }}>{trend === 'up' ? '▲' : trend === 'down' ? '▼' : '·'}</span>}
        {sub}
      </div>}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Day-1 communities (truncated for homepage modules)
// ─────────────────────────────────────────────────────────────
const COMMUNITIES = [
  { name: 'The AI Workplace',   niche: 'AI × Future of Work',     tam: '50k+',  mon: 'Sponsorship', rate: 'Strong Buy', color: 'green',  est: '$2.4–4.1k/mo' },
  { name: 'Wealth Signal',      niche: 'Personal Finance',        tam: '80k+',  mon: 'Membership',  rate: 'Strong Buy', color: 'green',  est: '$3.1–6.0k/mo' },
  { name: 'Zero to Operator',   niche: 'Startups',                tam: '120k+', mon: 'Sponsorship', rate: 'Strong Buy', color: 'green',  est: '$2.8–5.4k/mo' },
  { name: 'Climate Capital',    niche: 'Climate Tech',            tam: '40k+',  mon: 'Sponsorship', rate: 'Buy',        color: 'teal',   est: '$1.6–3.2k/mo' },
  { name: 'Longevity Stack',    niche: 'Health Optimization',     tam: '90k+',  mon: 'Membership',  rate: 'Buy',        color: 'teal',   est: '$2.0–4.4k/mo' },
  { name: 'Creator Ledger',     niche: 'Creator Economy',         tam: '70k+',  mon: 'Sponsorship', rate: 'Buy',        color: 'teal',   est: '$1.8–3.6k/mo' },
  { name: 'Brick Intelligence', niche: 'Real Estate Investing',   tam: '55k+',  mon: 'Membership',  rate: 'Accumulate', color: 'amber',  est: '$1.2–2.8k/mo' },
  { name: 'SaaS Signals',       niche: 'B2B SaaS Growth',         tam: '65k+',  mon: 'Sponsorship', rate: 'Accumulate', color: 'amber',  est: '$1.5–3.1k/mo' },
  { name: 'Mind Architecture',  niche: 'Mental Performance',      tam: '100k+', mon: 'Membership',  rate: 'Accumulate', color: 'amber',  est: '$1.8–3.4k/mo' },
  { name: 'Points Insider',     niche: 'Travel Hacking',          tam: '110k+', mon: 'Affiliate',   rate: 'Watch',      color: 'blue',   est: '$1.0–2.6k/mo' },
  { name: 'Capital Mechanics',  niche: 'VC & Private Markets',    tam: '55k+',  mon: 'Membership',  rate: 'Watch',      color: 'blue',   est: '$1.4–2.9k/mo' },
  { name: 'Sports Intelligence',niche: 'Sports Analytics',        tam: '60k+',  mon: 'Sponsorship', rate: 'Watch',      color: 'blue',   est: '$1.1–2.4k/mo' },
];

// ─────────────────────────────────────────────────────────────
// Operator pricing (from business case §3 Path B)
// ─────────────────────────────────────────────────────────────
const OPERATOR_TIERS = [
  { id: 'launch',     name: 'Launch',     price: 49,   share: 30, blurb: 'First-time operators, starting from zero.', features: ['1 community', 'Full Narrio OS', 'Subscriber tools', 'Standard cadence', 'Community support'] },
  { id: 'growth',     name: 'Growth',     price: 199,  share: 15, blurb: 'Operators ready to accelerate.',            features: ['Up to 2 communities', 'Format expansion (newsletter → podcast)', 'Audience intelligence layer', 'Priority distribution', 'Direct support'] },
  { id: 'operator',   name: 'Operator',   price: 499,  share: 5,  blurb: 'Serious builders running a portfolio.',     features: ['Up to 3 communities', 'Custom branding & domain', 'Sponsor brokerage', 'Editorial brokerage access', 'Dedicated success lead'], featured: true },
  { id: 'enterprise', name: 'Enterprise', price: null, share: 'Custom', blurb: 'Multi-vertical operators.',          features: ['Unlimited communities', 'White-label OS', 'API & data export', 'Bespoke editorial workflows', 'Account team + SLA'] },
];

// ─────────────────────────────────────────────────────────────
// Earnings calculator — uses the actual formulas from §5 + §10
// ─────────────────────────────────────────────────────────────
function calcContributorEarnings({ subs, arpu, role, streakWeeks, engagementScore, contributorCount }) {
  const gross = subs * arpu;
  const referralRate = 0.02;
  const referralBonus = gross * referralRate;
  const net = gross - referralBonus;
  const platformShare = role === 'lead-only' ? 0.40 : role === 'lead+1' ? 0.45 : role === 'lead+2' ? 0.40 : 0.35;
  const platformCut = net * platformShare;
  const contribPool = net - platformCut;
  let leadBaseFraction = 0.40 / (role === 'lead-only' ? 0.40 : role === 'lead+1' ? 0.50 : role === 'lead+2' ? 0.60 : 0.70);
  const leadBase = contribPool * leadBaseFraction;
  const supportingTotalFraction = 1 - leadBaseFraction;
  const supportingPool = contribPool * supportingTotalFraction;
  const perSupporting = role === 'lead-only' ? 0 : supportingPool / (contributorCount - 1);
  const streakMult = streakWeeks >= 12 ? 1.5 : streakWeeks >= 8 ? 1.25 : streakWeeks >= 4 ? 1.1 : 1.0;
  const engagementWeight = Math.max(0.5, Math.min(1.2, engagementScore / 100));
  const leadTotal = (leadBase + referralBonus) * streakMult * engagementWeight;
  return {
    gross, referralBonus, platformCut, contribPool,
    leadBase, perSupporting, leadTotal,
    streakMult, engagementWeight,
  };
}

// ─────────────────────────────────────────────────────────────
// Operator break-even math (license + share)
// ─────────────────────────────────────────────────────────────
function operatorTake(tier, monthlyRev) {
  if (tier.price == null) return monthlyRev * 0.97 - 999; // illustrative enterprise
  const share = monthlyRev * (tier.share / 100);
  return monthlyRev - share - tier.price;
}

// ─────────────────────────────────────────────────────────────
// Reputation tiers (§9)
// ─────────────────────────────────────────────────────────────
const REPUTATION_TIERS = [
  { name: 'New Contributor',   range: [0, 5],    perks: ['Platform access', 'Basic earnings'] },
  { name: 'Active Contributor',range: [5, 7],    perks: ['Brokerage access', 'Referral tier 1'] },
  { name: 'Senior Contributor',range: [7, 9],    perks: ['Lead coverage', '4-slot access', 'Referral tier 2'] },
  { name: 'Community Lead',    range: [9, 9.5],  perks: ['4th slot unlocked', '6 annual waivers', 'Priority Lead matching'] },
  { name: 'Narrio Fellow',     range: [9.5, 10], perks: ['Advisory access', 'Early features', 'Public badge'] },
];

// ─────────────────────────────────────────────────────────────
// Engagement actions — for the scoreboard
// ─────────────────────────────────────────────────────────────
const ENGAGE_ACTIONS = [
  { id: 'reviews',  label: 'Content reviews',          rate: 3,  unit: 'per review',     max: 30, hint: 'Approve, edit, redirect' },
  { id: 'edits',    label: 'Content improvements',     rate: 5,  unit: 'per edited piece',max: 25, hint: 'Substantive edits' },
  { id: 'intel',    label: 'Intelligence submissions', rate: 6,  unit: 'per item',        max: 30, hint: 'Ideas, sources, signals' },
  { id: 'replies',  label: 'Subscriber interactions',  rate: 3,  unit: 'per interaction', max: 15, hint: 'Replies, threads' },
  { id: 'referrals',label: 'Referral activity',        rate: 5,  unit: 'per attributed', max: 20, hint: 'Tracked referral subs' },
];

// Format helpers
function fmt$(n)    { return '$' + Math.round(n).toLocaleString(); }
function fmt$k(n)   { return n >= 1000 ? '$' + (n / 1000).toFixed(n >= 10000 ? 0 : 1) + 'k' : '$' + Math.round(n); }
function fmtPct(n)  { return (n * 100).toFixed(0) + '%'; }

Object.assign(window, {
  NarrioNav, NarrioMark, NarrioFooter,
  SYSTEM_EVENTS, useTickingFeed, eventDot,
  Stat, COMMUNITIES, OPERATOR_TIERS,
  calcContributorEarnings, operatorTake,
  REPUTATION_TIERS, ENGAGE_ACTIONS,
  fmt$, fmt$k, fmtPct,
});
