// Hero terminal — a live-looking system-at-work feed.
// Ticks a new line in every 2–4s; old lines dim and scroll up.
const { useState: useStateTF, useEffect: useEffectTF, useRef: useRefTF } = React;

// Curated line pool. Each line: [channel, glyph, text, meta]
// channel drives the left badge color; glyph is a small symbol.
const FEED_POOL = [
  ['call',  '📞', 'inbound · routed → Agent-03',                'ops.voice'],
  ['mail',  '✉',  'follow-up drafted · synced → HubSpot',        'cx.sequences'],
  ['flag',  '⚑',  'invoice variance flagged · ticket opened',    'finance.ap'],
  ['save',  '▼',  'spend audit · $4,217 recovered this week',    'spend.audit'],
  ['sched', '◷',  'meeting rescheduled · 3 calendars reconciled','ops.scheduling'],
  ['doc',   '≡',  'contract parsed · 14 clauses extracted',      'doc.pipeline'],
  ['call',  '📞', 'after-hours overflow · 1 voicemail → ticket', 'ops.voice'],
  ['intel', '◎',  'lead scored · handed to SDR queue',           'rev.routing'],
  ['ops',   '→',  'QuickBooks sync · 83 entries reconciled',     'finance.gl'],
  ['ai',    '✦',  'agent-02 deployed · 0 incidents (24h)',       'ops.agents'],
  ['save',  '▼',  'license de-provisioned · $312 / mo reclaimed','spend.licenses'],
  ['sec',   '◆',  'access review · 2 stale tokens revoked',      'sec.iam'],
  ['flag',  '⚑',  'SLA watch · response time nominal',           'obs.sla'],
  ['doc',   '≡',  'onboarding packet · sent to client.04',       'cx.onboard'],
  ['call',  '📞', 'VoIP failover · health check passed',         'ops.voice'],
  ['ai',    '✦',  'model routed · cost-per-task ↓ 22%',          'rev.router'],
  ['ops',   '→',  'Zapier flow · 41 records updated',            'automation'],
  ['save',  '▼',  'cloud rightsized · $1,840 / mo saved',        'spend.cloud'],
];

// Channel → accent color (CSS var refs handled in CSS).
const CHANNEL_LABEL = {
  call: 'CALL', mail: 'MAIL', flag: 'FLAG', save: 'SAVE', sched: 'SCHED',
  doc: 'DOC', intel: 'INTEL', ops: 'OPS', ai: 'AI', sec: 'SEC',
};

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

window.HeroTerminal = function HeroTerminal() {
  // Seed with 5 lines so it doesn't look empty on load.
  const [lines, setLines] = useStateTF(() => {
    const seeded = [];
    for (let i = 0; i < 5; i++) {
      const p = FEED_POOL[Math.floor(Math.random() * FEED_POOL.length)];
      // Age 0 for the top (newest), increasing downward but capped so none vanish.
      seeded.push({ id: 'seed-' + i, ch: p[0], glyph: p[1], text: p[2], meta: p[3], ts: now(), age: i });
    }
    return seeded;
  });
  const rootRef = useRefTF(null);
  const [paused, setPaused] = useStateTF(false);

  useEffectTF(() => {
    if (paused) return;
    let mounted = true;

    // Pause when not visible (battery/perf).
    let visible = true;
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => { visible = e.isIntersecting; });
    }, { threshold: 0.1 });
    if (rootRef.current) io.observe(rootRef.current);

    const tick = () => {
      if (!mounted) return;
      if (visible) {
        const p = FEED_POOL[Math.floor(Math.random() * FEED_POOL.length)];
        const newLine = {
          id: 'l-' + Math.random().toString(36).slice(2, 9),
          ch: p[0], glyph: p[1], text: p[2], meta: p[3], ts: now(), age: 0, fresh: true,
        };
        setLines(prev => {
          const aged = prev.map(l => ({ ...l, age: l.age + 1 }));
          const next = [newLine, ...aged].slice(0, 6);
          return next;
        });
      }
      const delay = 1800 + Math.random() * 2400;
      timer = setTimeout(tick, delay);
    };
    let timer = setTimeout(tick, 1400);
    return () => { mounted = false; clearTimeout(timer); io.disconnect(); };
  }, [paused]);

  return (
    <div
      className="hero-terminal cursor-interactive"
      ref={rootRef}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
      aria-label="Live system activity feed"
    >
      <div className="hero-terminal-chrome">
        <div className="hero-terminal-dots">
          <span /><span /><span />
        </div>
        <div className="hero-terminal-title">
          <span className="mono" style={{ color: 'var(--text-dim)' }}>ops</span>
          <span className="mono" style={{ color: 'var(--text-dim)' }}>/</span>
          <span className="mono">system.live</span>
        </div>
        <div className="hero-terminal-status">
          <span className="hero-terminal-pulse" />
          <span className="mono">live</span>
        </div>
      </div>
      <div className="hero-terminal-body">
        <div className="hero-terminal-scroll">
          {lines.map((l) => (
            <div
              key={l.id}
              className={`hero-terminal-line age-${Math.min(l.age, 5)}${l.fresh ? ' anim-in' : ''}`}
            >
              <span className="htl-ts mono">{l.ts}</span>
              <span className={`htl-chan htl-chan-${l.ch} mono`}>{CHANNEL_LABEL[l.ch]}</span>
              <span className="htl-glyph">{l.glyph}</span>
              <span className="htl-text">{l.text}</span>
              <span className="htl-meta mono">{l.meta}</span>
            </div>
          ))}
        </div>
        <div className="hero-terminal-fade" />
      </div>
      <div className="hero-terminal-footer mono">
        <span className="hero-terminal-pulse sm" />
        <span>agents · 12 online</span>
        <span style={{ opacity: 0.4 }}>·</span>
        <span>uptime · 99.98%</span>
        <span style={{ marginLeft: 'auto', opacity: 0.6 }}>{paused ? 'paused' : 'streaming'}</span>
      </div>
    </div>
  );
};
