// Top navigation
function TopNav({ wordmark, page }) {
  const [session, setSession] = React.useState(null);
  const [authReady, setAuthReady] = React.useState(false);

  React.useEffect(() => {
    if (!window.sb || !window.sb.auth) { setAuthReady(true); return; }
    let unsub = () => {};
    window.sb.auth.getSession().then(({ data }) => {
      setSession(data && data.session ? data.session : null);
      setAuthReady(true);
    });
    const { data: subData } = window.sb.auth.onAuthStateChange((_evt, s) => setSession(s));
    if (subData && subData.subscription) unsub = () => subData.subscription.unsubscribe();
    return unsub;
  }, []);

  return (
    <nav className="hub-nav" data-screen-label="Top Nav">
      <div className="hub-nav-brand">
        <a href="index.html" className="hub-wordmark">
          <span className="wm-dim">{wordmark.pre}</span> {wordmark.mid} <span className="wm-accent">{wordmark.end}</span>
        </a>
      </div>
      <div className="hub-nav-links">
        <a href="index.html#pillars" className={`hub-nav-link ${page === 'home' ? '' : ''}`}>Platform</a>
        <a href="index.html#intelligence" className="hub-nav-link">Content Agent</a>
        <a href="index.html#industries" className="hub-nav-link">Industries</a>
        <a href="index.html#work" className="hub-nav-link">Case Studies</a>
        <a href="Team.html" className={`hub-nav-link ${page === 'team' ? 'active' : ''}`}>Team</a>
        <a href="index.html#insights" className="hub-nav-link">Writing</a>
      </div>
      <div className="hub-nav-cta">
        <a href="#contact" className="btn btn-primary">Book discovery call <IconArrowRight size={14} /></a>
        {authReady && (session ?
          <a href="/portal/" className="btn btn-secondary"><IconLock size={14} /> Dashboard</a> :
          <a href="/login.html" className="btn btn-secondary"><IconLock size={14} /> Client Login</a>)}
      </div>
    </nav>);

}
window.TopNav = TopNav;

// HERO
function HeroSection({ variant }) {
  const editorial = variant === 'editorial';
  const [wordIdx, setWordIdx] = React.useState(0);
  const words = ['your business', 'insurance', 'founders', 'operators', 'fintech', 'sales teams'];
  React.useEffect(() => {
    const t = setInterval(() => setWordIdx((i) => (i + 1) % words.length), 2400);
    return () => clearInterval(t);
  }, []);
  return (
    <section id="top" className={`hub-hero-section ${editorial ? 'hero-variant-editorial' : ''}`} data-screen-label="Hero">
      <div className="hub-hero-inner" style={{ maxWidth: 1600 }}>
        <div className="hero-grid">
          <div>
            <div className="hub-hero-accent" />
            <span className={`hub-eyebrow ${editorial ? '' : 'hub-eyebrow-on-dark'}`}>Now building · 12 active engagements</span>
            <h1 className="hub-hero-headline">
              Custom AI built for<br />
              <strong style={{ color: editorial ? 'var(--emerald)' : 'var(--emerald-light)', display: 'inline-block', minWidth: 280, transition: 'all 300ms' }} key={wordIdx}>
                {words[wordIdx]}.
              </strong>
            </h1>
            <p className="hub-hero-sub">
              Not a template. Not a generic playbook. A living AI system designed around your actual workflows,
              your actual team, and your actual goals. Deployed in 30 days.
            </p>
            <div className="hub-hero-ctas">
              <a href="#contact" className="btn btn-primary">Book a discovery call <IconArrowRight size={16} /></a>
              <a href="#pillars" className="btn btn-ghost-on-dark"><IconPlay size={14} /> See how it works</a>
            </div>
            <div className="hub-hero-meta">
              <span><IconClock size={14} /> 30 min</span>
              <span><IconCheck size={14} /> Free</span>
              <span><IconFile size={14} /> No slide deck</span>
            </div>
          </div>
          <HeroShowcase editorial={editorial} />
        </div>
      </div>
    </section>);

}

function HeroShowcase({ editorial }) {
  // Pool of agent activities — cycles through to simulate live AI ops
  const pool = React.useMemo(() => [
  { role: 'Content Agent', action: 'Drafted 4 LinkedIn posts & 1 newsletter', client: 'Cornerstone Insurance', dur: 2800 },
  { role: 'RevOps', action: 'Flagged 7 stale deals > 30 days', client: 'MeridianIQ', dur: 1900 },
  { role: 'Chief of Staff', action: "Built today's priority plan from 12 inputs", client: 'Ferran Holdings', dur: 3400 },
  { role: 'Analyst', action: 'Delivered competitor brief (18 pages)', client: 'Northline Capital', dur: 4100 },
  { role: 'Lead Gen', action: 'Enriched 48 new contacts via LinkedIn', client: 'Axis Partners', dur: 2200 },
  { role: 'Success', action: 'Sent renewal check-ins to 23 accounts', client: 'Vaultline', dur: 1600 },
  { role: 'Talent', action: 'Screened 84 candidates against JD', client: 'Osprey Labs', dur: 3600 },
  { role: 'Integration', action: 'Synced Salesforce → Notion → Slack', client: 'Helix Capital', dur: 1200 },
  { role: 'Content Agent', action: 'Repurposed podcast into 6 carousels', client: 'Bright & Co.', dur: 2900 },
  { role: 'RevOps', action: 'Updated forecast: +$142k pipeline', client: 'Quantify.io', dur: 2100 }],
  []);

  const roleColors = {
    'Content Agent': { bg: 'rgba(5,146,108,.14)', fg: '#10b981' },
    'RevOps': { bg: 'rgba(37,99,235,.14)', fg: '#60a5fa' },
    'Chief of Staff': { bg: 'rgba(168,85,247,.14)', fg: '#c084fc' },
    'Analyst': { bg: 'rgba(245,158,11,.14)', fg: '#fbbf24' },
    'Lead Gen': { bg: 'rgba(236,72,153,.14)', fg: '#f472b6' },
    'Success': { bg: 'rgba(20,184,166,.14)', fg: '#2dd4bf' },
    'Talent': { bg: 'rgba(99,102,241,.14)', fg: '#818cf8' },
    'Integration': { bg: 'rgba(148,163,184,.14)', fg: '#cbd5e1' }
  };

  const [feed, setFeed] = React.useState(() => pool.slice(0, 5).map((x, i) => ({ ...x, id: i, status: 'done', typed: x.action })));
  const [counter, setCounter] = React.useState(5);
  const [thinking, setThinking] = React.useState(null); // {id, role, client, action, typed}
  const [filter, setFilter] = React.useState('All');
  const counterRef = React.useRef(5);
  counterRef.current = counter;

  const now = () => {
    const d = new Date();
    return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`;
  };

  // Stream loop: pick next agent → "thinking" (1.2s) → type action → add to feed
  React.useEffect(() => {
    let cancelled = false;
    let timers = [];
    const runOne = () => {
      if (cancelled) return;
      const pick = pool[counterRef.current % pool.length];
      const id = counterRef.current + 1;
      setCounter(id);
      setThinking({ id, role: pick.role, client: pick.client, action: pick.action, typed: '', time: now() });
      timers.push(setTimeout(() => {
        // Typing phase
        let i = 0;
        const typeInterval = setInterval(() => {
          if (cancelled) return clearInterval(typeInterval);
          i++;
          setThinking((t) => t && t.id === id ? { ...t, typed: pick.action.slice(0, i) } : t);
          if (i >= pick.action.length) {
            clearInterval(typeInterval);
            timers.push(setTimeout(() => {
              if (cancelled) return;
              setFeed((f) => [{ ...pick, id, status: 'done', typed: pick.action, time: now() }, ...f].slice(0, 5));
              setThinking(null);
              timers.push(setTimeout(runOne, 900 + Math.random() * 1200));
            }, 350));
          }
        }, 24);
      }, 1100));
    };
    const kickoff = setTimeout(runOne, 1400);
    timers.push(kickoff);
    return () => {cancelled = true;timers.forEach(clearTimeout);};
  }, [pool]);

  const filters = ['All', 'Content Agent', 'RevOps', 'Analyst', 'Lead Gen'];
  const visibleFeed = filter === 'All' ? feed : feed.filter((x) => x.role === filter);
  const visibleThinking = thinking && (filter === 'All' || thinking.role === filter) ? thinking : null;

  return (
    <div className="hero-showcase">
      <div className="hero-showcase-head">
        <div className="hero-showcase-dots"><i /><i /><i /></div>
        <span>integrated · live from client ops</span>
        <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--emerald-light)' }}>
          <span className="pulse-dot" /> {thinking ? 'thinking' : 'streaming'}
        </span>
      </div>

      <div className="hero-filters">
        {filters.map((f) =>
        <button key={f} className={`hero-filter ${filter === f ? 'on' : ''}`} onClick={() => setFilter(f)}>{f}</button>
        )}
      </div>

      <div style={{ background: editorial ? '#f8fafc' : '#0b1220', borderRadius: 8, padding: 12, border: `1px solid ${editorial ? '#e5e7eb' : '#1e293b'}`, display: 'flex', flexDirection: 'column', gap: 8, minHeight: 280 }}>
        {visibleThinking &&
        <FeedRow editorial={editorial} item={visibleThinking} roleColors={roleColors} thinking />
        }
        {visibleFeed.map((x) =>
        <FeedRow key={x.id} editorial={editorial} item={x} roleColors={roleColors} />
        )}
        {!visibleThinking && visibleFeed.length === 0 &&
        <div style={{ padding: '40px 12px', textAlign: 'center', font: '500 13px/1.4 var(--font-sans)', color: editorial ? 'var(--fg-3)' : '#64748b' }}>Waiting for {filter} activity…</div>
        }
      </div>

      <div className="hero-footline">
        <span><IconCheck size={11} /> {counter} actions completed today</span>
        <span style={{ marginLeft: 'auto' }}>8 agents online</span>
      </div>
    </div>);

}

function FeedRow({ item, editorial, roleColors, thinking }) {
  const c = roleColors[item.role] || { bg: 'rgba(5,146,108,.1)', fg: 'var(--emerald)' };
  return (
    <div className={`feed-row ${thinking ? 'is-thinking' : ''}`} style={{ background: editorial ? '#fff' : 'rgba(255,255,255,.02)', border: `1px solid ${editorial ? '#e5e7eb' : thinking ? 'rgba(16,185,129,.35)' : '#1e293b'}` }}>
      <div style={{ font: '600 10px/1 var(--font-sans)', color: c.fg, textTransform: 'uppercase', letterSpacing: '.1em', background: c.bg, padding: '5px 8px', borderRadius: 999, whiteSpace: 'nowrap' }}>{item.role}</div>
      <div style={{ minWidth: 0 }}>
        <div style={{ font: '500 13px/1.3 var(--font-sans)', color: editorial ? 'var(--navy)' : '#fff', marginBottom: 3, display: 'flex', alignItems: 'center', gap: 6 }}>
          {thinking && item.typed.length < item.action.length ?
          <>
              <span>{item.typed}</span>
              <span className="caret" />
            </> :

          <span>{item.typed || item.action}</span>
          }
        </div>
        <div style={{ font: '400 11px/1 var(--font-mono)', color: editorial ? 'var(--fg-3)' : '#64748b' }}>
          {item.time || '—'} · {item.client}
        </div>
      </div>
      <div>
        {thinking && item.typed.length < item.action.length ?
        <span className="thinking-chip">◌ working</span> :
        <IconCheck size={14} style={{ color: editorial ? 'var(--emerald)' : '#10b981' }} />}
      </div>
    </div>);

}
window.HeroSection = HeroSection;

// OPS TICKER (replaces generic trust bar)
function OpsTicker() {
  const items = [
  'Multiply AI Platform', 'Content Agent · Beta', '30-Day Full Implementation',
  'Insurance: 11 validated use cases', 'IT & Cybersecurity sales automation',
  'B2B SaaS & Fintech GTM automation', 'Team Training: on-site & remote',
  'Professional Services leverage', 'AI Governance frameworks'];

  const doubled = [...items, ...items];
  return (
    <div className="ops-ticker">
      <div className="ops-ticker-inner">
        <div className="ops-live"><span className="ops-live-dot" /> Live Capabilities</div>
        <div className="ops-stream">
          <div className="ops-stream-track">
            {doubled.map((t, i) =>
            <span key={i} className="ops-item">
                <svg width="8" height="8" viewBox="0 0 8 8" style={{ flexShrink: 0 }}><circle cx="4" cy="4" r="4" fill="var(--emerald)" /></svg>
                <strong>{t}</strong>
              </span>
            )}
          </div>
        </div>
      </div>
    </div>);

}
window.OpsTicker = OpsTicker;
window.TrustBar = OpsTicker;