// Hi-fi Terminal homepage components
// - Animated ticker (CSS marquee)
// - Animated code → response (typewriter on enter)
// - Hound mark
// - Real watchlist with hover

// All values resolve to CSS variables so a [data-theme="light"] flip on <html>
// re-themes the entire site without re-rendering. Vars defined in each page's <style>.
const FH = {
  bg:        'var(--fh-bg)',
  bg2:       'var(--fh-bg2)',
  bg3:       'var(--fh-bg3)',
  border:    'var(--fh-border)',
  borderHi:  'var(--fh-border-hi)',
  ink:       'var(--fh-ink)',
  ink2:      'var(--fh-ink-2)',
  ink3:      'var(--fh-ink-3)',
  accent:    'var(--fh-accent)',
  accentDim: 'var(--fh-accent-dim)',
  accentSoft:'var(--fh-accent-soft)',
  red:       'var(--fh-red)',
};

// Hound mark — geometric greyhound silhouette in profile.
// Sighthound proportions: small head, very long arched neck, deep narrow chest,
// dramatic belly tuck, long stilt legs (~half total height), low-hanging whip tail.
// Faceted polygonal outline. viewBox 120x70, oriented left→right.
const Hound = ({ size = 28, color }) => {
  const c = color || FH.ink;
  const w = size * (120 / 70);
  const h = size;
  return (
    <svg width={w} height={h} viewBox="0 0 120 70" fill="none" style={{ display: 'block' }}>
      <path
        d={[
          'M 2 16',            // nose tip
          'L 14 14',           // top of muzzle
          'L 16 9',            // forehead stop
          'L 21 6',            // top of head
          'L 22 1',            // ear tip swept back
          'L 27 8',            // back of ear / skull
          'L 26 14',           // nape
          'L 34 10',           // arched neck cresting
          'L 48 8',            // withers (high shoulder)
          'L 70 12',           // long back, slight dip
          'L 84 6',            // hip rise (peak haunch)
          'L 92 10',           // tail base
          // Tail — drops low and back
          'L 100 18',
          'L 108 30',
          'L 116 42',          // tail tip — well below body
          'L 112 44',
          'L 104 34',
          'L 96 24',
          'L 90 18',           // back to rump
          'L 88 22',           // top of rear haunch
          // Rear leg — long, with hock kink
          'L 92 36',           // thigh outer
          'L 88 50',           // stifle / knee
          'L 90 64',           // hock
          'L 94 68',           // rear paw heel
          'L 86 68',           // rear paw toe
          'L 84 52',           // rear leg inner up
          'L 80 38',
          // Belly tuck
          'L 70 36',
          'L 60 40',           // deepest tuck-up
          'L 52 36',
          'L 46 32',           // belly meets chest
          // Front leg — long, straight
          'L 44 68',           // front paw heel
          'L 36 68',           // front paw toe
          'L 38 32',           // front leg up
          // Deep chest → throat → underjaw → nose
          'L 32 26',           // deep brisket
          'L 24 22',
          'L 16 20',           // throat
          'L 10 18',           // underjaw
          'Z',
        ].join(' ')}
        fill={c}
        fillRule="evenodd"
      />
      {/* eye — tiny knockout */}
      <rect x="18" y="11" width="1.6" height="1.6" fill="var(--fh-bg)" />
    </svg>
  );
};

// HoundLockup is defined in chrome.jsx (canonical version with HoundIcon SVG)

// Animated ticker — pure CSS marquee
const FH_TICKER_ITEMS = [
  ['AAPL', '8-K', 'earnings', '2m'],
  ['MSFT', '8-K', 'material_agmt', '6m'],
  ['EPA', 'propRule', '40 CFR 60', '12m'],
  ['NVDA', '10-Q', 'filed', '18m'],
  ['FDA', 'notice', '21 CFR 314', '24m'],
  ['GS', '8-K', 'leadership', '31m'],
  ['BLS', 'release', 'CPI-U +0.3%', '45m'],
  ['TSLA', '8-K', 'earnings', '52m'],
  ['META', '8-K', 'restatement', '1h'],
  ['SBIR', 'grant', 'Phase II $1.2M', '1h'],
  ['SAM', 'contract', 'DoD $4.8M', '2h'],
  ['IRS', '990', 'Gates Foundation', '3h'],
];

const FHTicker = ({ speed = 60 }) => (
  <div style={{
    display: 'flex',
    gap: 0,
    overflow: 'hidden',
    fontFamily: '"JetBrains Mono", monospace',
    fontSize: 12,
    color: FH.ink2,
    letterSpacing: '0.02em',
    maskImage: 'linear-gradient(90deg, transparent, black 4%, black 96%, transparent)',
    WebkitMaskImage: 'linear-gradient(90deg, transparent, black 4%, black 96%, transparent)',
  }}>
    <div style={{
      display: 'flex', gap: 36, whiteSpace: 'nowrap',
      animation: `fh-marquee ${speed}s linear infinite`,
      paddingLeft: 36,
    }}>
      {[...FH_TICKER_ITEMS, ...FH_TICKER_ITEMS, ...FH_TICKER_ITEMS].map((it, i) => (
        <span key={i} style={{ display: 'inline-flex', gap: 10 }}>
          <span style={{ color: FH.accent }}>●</span>
          <span style={{ color: FH.ink, fontWeight: 500 }}>{it[0]}</span>
          <span style={{ color: FH.ink3 }}>{it[1]}</span>
          <span>{it[2]}</span>
          <span style={{ color: FH.ink3 }}>{it[3]}</span>
        </span>
      ))}
    </div>
  </div>
);

// Typed code block with cursor
const TypedCode = ({ active }) => {
  const fullCode = [
    '// agent calls firmhound',
    'await mcp.call("search_8k_events", {',
    '  query: "CFO departure",',
    '  item_type: "5.02",',
    '  since: "2026-03-25"',
    '})',
  ];
  const fullResp = [
    '{',
    '  total: 47,',
    '  classified: [',
    '    { ticker: "AAPL", event: "leadership_change", filed: "2m" },',
    '    { ticker: "PFE",  event: "leadership_change", filed: "14m" },',
    '    { ticker: "GS",   event: "leadership_change", filed: "31m" }',
    '  ]',
    '}',
  ];
  const [step, setStep] = React.useState(0);
  React.useEffect(() => {
    if (!active) return;
    let i = 0;
    const t = setInterval(() => {
      i++;
      setStep(i);
      if (i >= fullCode.length + fullResp.length + 2) clearInterval(t);
    }, 280);
    return () => clearInterval(t);
  }, [active]);

  const codeShown = fullCode.slice(0, Math.min(step, fullCode.length));
  const respDelay = fullCode.length + 1;
  const respShown = step > respDelay ? fullResp.slice(0, step - respDelay) : [];
  const showCaret = step < fullCode.length + fullResp.length + 1;

  return (
    <div style={{ fontFamily: '"JetBrains Mono", monospace', fontSize: 12.5, lineHeight: 1.6 }}>
      <div style={{ color: FH.ink3, fontSize: 10, letterSpacing: '0.16em', marginBottom: 10 }}>
        ◆ AGENT CALL
      </div>
      <div style={{ minHeight: 110, color: FH.ink }}>
        {codeShown.map((line, i) => (
          <div key={i} style={{ color: i === 0 ? FH.ink3 : FH.ink }}>
            {colorizeCode(line)}
          </div>
        ))}
        {step < fullCode.length && showCaret && (
          <span style={{ display: 'inline-block', width: 8, height: 14, background: FH.accent, verticalAlign: 'text-bottom', animation: 'fh-blink 1s steps(2) infinite' }} />
        )}
      </div>
      {respShown.length > 0 && (
        <>
          <div style={{ color: FH.ink3, fontSize: 10, letterSpacing: '0.16em', margin: '14px 0 8px' }}>
            ◆ RESPONSE · 187ms
          </div>
          <div style={{ padding: 12, background: FH.bg, border: `1px solid ${FH.border}`, color: FH.ink2 }}>
            {respShown.map((line, i) => (
              <div key={i}>{colorizeJson(line)}</div>
            ))}
          </div>
        </>
      )}
    </div>
  );
};

function colorizeCode(line) {
  // Simple syntax: highlight strings green, await magenta-ish
  const parts = line.split(/(".*?"|\bawait\b|\bmcp\b|\bcall\b)/g);
  return parts.map((p, i) => {
    if (/^".*"$/.test(p)) return <span key={i} style={{ color: FH.accent }}>{p}</span>;
    if (p === 'await') return <span key={i} style={{ color: FH.red }}>{p}</span>;
    if (p === 'mcp' || p === 'call') return <span key={i} style={{ color: FH.ink }}>{p}</span>;
    return <span key={i}>{p}</span>;
  });
}
function colorizeJson(line) {
  const parts = line.split(/(".*?"|\b\d+\b|\btrue\b|\bfalse\b)/g);
  return parts.map((p, i) => {
    if (/^".*"$/.test(p)) return <span key={i} style={{ color: FH.accent }}>{p}</span>;
    if (/^\d+$/.test(p)) return <span key={i} style={{ color: FH.red }}>{p}</span>;
    return <span key={i}>{p}</span>;
  });
}

// Watchlist row with hover state
// Map product id → detail page
const PRODUCT_HREFS = {
  edgarwatch:     'product-edgarwatch.html',
  fedregwatch:    'product-fedregwatch.html',
  irswatch:       'product-irswatch.html',
  lobbyfilings:   'product-lobbywatch.html',
  secnumbers:     'product-fedregwatch.html',   // no dedicated page yet — closest match
  boardscan:      'product-edgarwatch.html',    // no dedicated page yet
  blsdigest:      'product-fedregwatch.html',   // no dedicated page yet
  senatortrades:  'product-fedregwatch.html',   // no dedicated page yet
  grantfiles:     'product-fedregwatch.html',   // no dedicated page yet
  fedbidwatch:    'product-fedregwatch.html',   // no dedicated page yet
  nonprofwatch:   'product-irswatch.html',      // no dedicated page yet
  planefiles:     'product-fedregwatch.html',   // no dedicated page yet
  clinicalfilings:'product-fedregwatch.html',   // no dedicated page yet
  fintrakker:     'product-fedregwatch.html',   // no dedicated page yet
  listmyproduct:  'product-fedregwatch.html',   // no dedicated page yet
};

const WatchRow = ({ p, i }) => {
  const [hover, setHover] = React.useState(false);
  const href = PRODUCT_HREFS[p.id] || 'index.html#portfolio';
  return (
    <a
      href={href}
      style={{ textDecoration: 'none', color: 'inherit', display: 'block' }}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
    >
    <div
      style={{
        display: 'grid',
        gridTemplateColumns: '32px 70px minmax(180px, 1.4fr) minmax(220px, 1.6fr) 1fr 1.1fr 100px 32px',
        columnGap: 24,
        padding: '14px 0',
        borderBottom: `1px solid ${FH.border}`,
        fontSize: 13,
        alignItems: 'center',
        background: hover ? FH.bg2 : 'transparent',
        cursor: 'pointer',
        transition: 'background 0.12s',
      }}>
      {/* index */}
      <div style={{ color: FH.ink3, fontFamily: '"JetBrains Mono", monospace', fontSize: 11, fontVariantNumeric: 'tabular-nums' }}>
        {String(i + 1).padStart(2, '0')}
      </div>
      {/* live status */}
      <div style={{ color: FH.accent, fontSize: 10, fontFamily: '"JetBrains Mono", monospace', letterSpacing: '0.14em' }}>
        ● LIVE
      </div>
      {/* product name */}
      <div style={{ color: FH.ink, fontWeight: 500, fontFamily: '"Instrument Serif", Georgia, serif', fontSize: 20, lineHeight: 1.1 }}>
        {p.name}
      </div>
      {/* source (primary metadata) */}
      <div style={{ color: FH.ink2, fontFamily: '"JetBrains Mono", monospace', fontSize: 12, letterSpacing: '0.02em' }}>
        {p.src}
      </div>
      {/* tools — compact pill */}
      <div style={{ color: FH.ink3, fontFamily: '"JetBrains Mono", monospace', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase' }}>
        {p.tools || (Math.floor(Math.random() * 3) + 2) + ' tools'}
      </div>
      {/* url */}
      <div style={{ color: hover ? FH.accent : FH.ink3, fontFamily: '"JetBrains Mono", monospace', fontSize: 11, transition: 'color 0.12s' }}>
        {p.id}.com<span style={{ color: FH.ink3, marginLeft: 4 }}>↗</span>
      </div>
      {/* price */}
      <div style={{
        textAlign: 'right', color: FH.ink, fontVariantNumeric: 'tabular-nums',
        fontFamily: '"JetBrains Mono", monospace', fontSize: 14, fontWeight: 500,
      }}>
        {p.price ? `$${p.price}` : '—'}
        <span style={{ color: FH.ink3, fontSize: 10, marginLeft: 2 }}>{p.price ? '/mo' : ''}</span>
      </div>
      {/* arrow */}
      <div style={{ textAlign: 'right', color: hover ? FH.accent : FH.ink3, fontFamily: '"JetBrains Mono", monospace', fontSize: 14, transition: 'all 0.12s', transform: hover ? 'translateX(4px)' : 'none' }}>
        →
      </div>
    </div>
    </a>
  );
};

Object.assign(window, { FH, Hound, FHTicker, TypedCode, WatchRow });
