// Hi-fi Terminal homepage — main component

const FH_PRODUCTS = [
  { id: 'edgarwatch',     name: 'Edgar Watch',           src: 'SEC EDGAR · 8-K filings',        price: 29,  group: 'sec',  tools: '3 tools' },
  { id: 'secnumbers',     name: 'SEC Numbers',           src: 'EDGAR XBRL · normalized',         price: 99,  group: 'sec',  tools: '3 tools' },
  { id: 'boardscan',      name: 'Board Scan',            src: 'SEC proxy · DEF 14A',             price: 99,  group: 'sec',  tools: '2 tools' },
  { id: 'fedregwatch',    name: 'Federal Register Watch',src: 'Federal Register API',            price: 415, group: 'fed',  tools: '3 tools' },
  { id: 'blsdigest',      name: 'BLS Digest',            src: 'Bureau of Labor Stats',           price: 199, group: 'fed',  tools: '2 tools' },
  { id: 'senatortrades',  name: 'Senator Trades',        src: 'STOCK Act · disclosures',         price: 499, group: 'fed',  tools: '4 tools' },
  { id: 'lobbyfilings',   name: 'Lobby Filings',         src: 'LDA disclosures',                 price: 99,  group: 'fed',  tools: '3 tools' },
  { id: 'grantfiles',     name: 'Grant Files',           src: 'SBIR/STTR awards',                price: 49,  group: 'fed',  tools: '2 tools' },
  { id: 'fedbidwatch',    name: 'Fed Bid Watch',         src: 'SAM.gov · contracts',             price: 149, group: 'fed',  tools: '3 tools' },
  { id: 'nonprofwatch',   name: 'Nonprofit Watch',       src: 'IRS Form 990',                    price: 99,  group: 'fed',  tools: '2 tools' },
  { id: 'planefiles',     name: 'Plane Files',           src: 'FAA aircraft registry',           price: 99,  group: 'comm', tools: '2 tools' },
  { id: 'clinicalfilings',name: 'Clinical Filings',      src: 'ClinicalTrials.gov',              price: 99,  group: 'comm', tools: '3 tools' },
];

const FH_GROUPS = {
  sec:  { label: 'I · SECURITIES & EXCHANGE',  count: FH_PRODUCTS.filter(p => p.group === 'sec').length },
  fed:  { label: 'II · FEDERAL GOVERNMENT',    count: FH_PRODUCTS.filter(p => p.group === 'fed').length },
  comm: { label: 'III · COMMERCIAL & MISC',    count: FH_PRODUCTS.filter(p => p.group === 'comm').length },
};

const TerminalHiFi = ({ tickerSpeed = 60, showTicker = true, showStats = true, accent }) => {
  const [demoActive, setDemoActive] = React.useState(false);
  const demoRef = React.useRef(null);
  // Allow tweak panel to override accent via CSS var
  const ACCENT = accent || `var(--fh-accent, ${FH.accent})`;

  // Live API data with graceful fallback to hardcoded defaults
  const [liveStats, setLiveStats] = React.useState(null);
  const [liveProducts, setLiveProducts] = React.useState(null);

  React.useEffect(() => {
    if (typeof FH_API === 'undefined') return;
    // Fetch product list
    fetch(FH_API + '/products').then(r => r.ok ? r.json() : null).then(data => {
      if (data && Array.isArray(data) && data.length > 0) setLiveProducts(data);
    }).catch(() => {});
    // Fetch status for hero stats
    fetch(FH_API + '/status').then(r => r.ok ? r.json() : null).then(data => {
      if (data) setLiveStats(data);
    }).catch(() => {});
  }, []);

  React.useEffect(() => {
    if (!demoRef.current) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) setDemoActive(true);
    }, { threshold: 0.3 });
    obs.observe(demoRef.current);
    return () => obs.disconnect();
  }, []);

  return (
    <div style={{
      minHeight: '100vh', background: FH.bg, color: FH.ink,
      fontFamily: '"JetBrains Mono", monospace',
    }}>
      {/* Top status strip */}
      <FHHeader active="Portfolio" />

      {/* Live ticker */}
      {showTicker && (
        <div style={{ padding: '10px 0', borderBottom: `1px solid ${FH.border}`, background: FH.bg2 }}>
          <FHTicker speed={tickerSpeed} />
        </div>
      )}

      {/* HERO */}
      <div style={{
        padding: '64px 32px 56px',
        display: 'grid', gridTemplateColumns: '1.7fr 1fr', gap: 40, alignItems: 'stretch',
      }}>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <div style={{ fontSize: 11, color: FH.ink3, letterSpacing: '0.18em', marginBottom: 22 }}>
            ◆ THESIS
          </div>
          <div style={{
            fontFamily: '"Instrument Serif", Georgia, serif',
            fontSize: 96, lineHeight: 0.96, letterSpacing: '-0.025em',
            fontWeight: 400, color: FH.ink,
            marginBottom: 28,
          }}>
            Government data,<br/>
            <em style={{ color: FH.accent, fontStyle: 'italic' }}>structured</em> for agents.
          </div>
          <div style={{
            fontSize: 15, lineHeight: 1.55, color: FH.ink2,
            maxWidth: 580, marginBottom: 28,
          }}>
            Twelve MCP-native data products over SEC EDGAR, the Federal Register, BLS releases,
            STOCK Act disclosures, FAA registries — normalized, classified, agent-callable.
            One key, every source.
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 28 }}>
            {['12 PRODUCTS', '38 TOOLS', 'MCP-NATIVE', 'JSON-RPC 2.0', 'STDIO'].map((t, i) => (
              <span key={t} style={{
                padding: '5px 10px',
                border: `1px solid ${i === 0 ? FH.accent : FH.border}`,
                color: i === 0 ? FH.accent : FH.ink2,
                fontSize: 10, letterSpacing: '0.1em',
              }}>{t}</span>
            ))}
          </div>
          {/* Stats strip */}
          {showStats && <div style={{
            marginTop: 'auto',
            display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
            border: `1px solid ${FH.border}`,
          }}>
            {(liveStats ? [
              [String(liveStats.products || 15), 'PRODUCTS'],
              [String(liveStats.tools || 47), 'TOOLS'],
              ['2×', 'DAILY'],
              [liveStats.uptime || '99.97', 'UPTIME %'],
            ] : [
              ['8.4K', 'PUBLIC COS'],
              ['200', 'AGENCIES'],
              ['2×', 'DAILY'],
              ['99.97', 'UPTIME %'],
            ]).map(([n, l], i) => (
              <div key={l} style={{
                padding: '18px 20px',
                borderRight: i < 3 ? `1px solid ${FH.border}` : 'none',
                background: FH.bg2,
              }}>
                <div style={{
                  fontSize: 32, color: FH.accent, fontWeight: 400,
                  fontFamily: '"Instrument Serif", Georgia, serif',
                  fontVariantNumeric: 'tabular-nums', lineHeight: 1,
                }}>{n}</div>
                <div style={{ fontSize: 9, color: FH.ink3, marginTop: 8, letterSpacing: '0.18em' }}>{l}</div>
              </div>
            ))}
          </div>}
        </div>

        {/* Right — REPL panel */}
        <div ref={demoRef} style={{
          border: `1px solid ${FH.border}`, background: FH.bg2,
          padding: 22, display: 'flex', flexDirection: 'column',
        }}>
          <div style={{
            display: 'flex', justifyContent: 'space-between',
            fontSize: 10, color: FH.ink3, letterSpacing: '0.14em',
            paddingBottom: 14, borderBottom: `1px solid ${FH.border}`, marginBottom: 16,
          }}>
            <span style={{ color: FH.accent }}>● LIVE REPL</span>
            <span>haiku-4-5</span>
          </div>
          <TypedCode active={demoActive} />
          <div style={{
            marginTop: 'auto', paddingTop: 14, borderTop: `1px solid ${FH.border}`,
            display: 'flex', justifyContent: 'space-between',
            fontSize: 10, color: FH.ink3,
          }}>
            <span>↳ try it: agent calls one of 47 tools</span>
            <span style={{ color: FH.accent, cursor: 'pointer' }}>RUN AGAIN ↗</span>
          </div>
        </div>
      </div>

      {/* PORTFOLIO */}
      <div style={{ padding: '40px 32px 56px', borderTop: `1px solid ${FH.border}` }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          marginBottom: 32,
        }}>
          <div>
            <div style={{ fontSize: 11, color: FH.ink3, letterSpacing: '0.18em', marginBottom: 8 }}>
              ◆ PORTFOLIO
            </div>
            <div style={{
              fontFamily: '"Instrument Serif", Georgia, serif',
              fontSize: 56, lineHeight: 1, letterSpacing: '-0.02em',
            }}>
              Twelve products. <em style={{ color: FH.accent }}>Three categories.</em>
            </div>
          </div>
          <div style={{ fontSize: 11, color: FH.ink3, textAlign: 'right' }}>
            <div>SEC · FEDERAL · COMMERCIAL</div>
            <div style={{ marginTop: 4 }}>↳ click any product to inspect tools</div>
          </div>
        </div>

        {['sec', 'fed', 'comm'].map(g => {
          // Use live product data if available, mapping API fields to display fields
          const displayProducts = liveProducts
            ? liveProducts.filter(p => {
                const gMap = { edgarwatch:'sec', secnumbers:'sec', boardscan:'sec',
                  fedregwatch:'fed', blsdigest:'fed', senatortrades:'fed', lobbyfilings:'fed',
                  grantfiles:'fed', fedbidwatch:'fed', nonprofwatch:'fed',
                  planefiles:'comm', clinicalfilings:'comm', fintrakker:'comm', listmyproduct:'comm' };
                return gMap[p.id] === g;
              }).map(p => ({
                id: p.id, name: p.name,
                src: p.tagline || p.data_source || '',
                price: p.price_monthly || 0,
                group: g,
                tools: (p.tools_count || 0) + ' tools',
              }))
            : FH_PRODUCTS.filter(p => p.group === g);
          return (
          <div key={g} style={{ marginBottom: 36 }}>
            <div style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
              padding: '10px 0', borderBottom: `1.5px solid ${FH.borderHi}`,
              marginBottom: 4,
            }}>
              <div style={{ fontSize: 12, color: FH.ink, letterSpacing: '0.14em', fontWeight: 600 }}>
                {FH_GROUPS[g].label}
              </div>
              <div style={{ fontSize: 10, color: FH.ink3, letterSpacing: '0.1em' }}>
                {displayProducts.length} PRODUCTS
              </div>
            </div>
            {displayProducts.map((p, i) => (
              <WatchRow key={p.id} p={p} i={i} />
            ))}
          </div>
          );
        })}
      </div>

      {/* BUNDLE */}
      <div style={{
        padding: '64px 32px',
        borderTop: `1px solid ${FH.border}`,
        background: FH.bg2,
        display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 50, alignItems: 'center',
      }}>
        <div>
          <div style={{ fontSize: 11, color: FH.ink3, letterSpacing: '0.18em', marginBottom: 18 }}>
            ◆ BUNDLE
          </div>
          <div style={{
            fontFamily: '"Instrument Serif", Georgia, serif',
            fontSize: 84, lineHeight: 0.98, letterSpacing: '-0.025em',
            marginBottom: 16,
          }}>
            All twelve.<br/>
            <span style={{ color: FH.accent, fontFamily: '"JetBrains Mono", monospace', fontSize: 64, fontWeight: 500 }}>$299</span>
            <span style={{ fontSize: 28, color: FH.ink3 }}> /month.</span>
          </div>
          <div style={{ fontSize: 14, color: FH.ink2, lineHeight: 1.55, maxWidth: 480, marginBottom: 24 }}>
            One API key unlocks every tool set. Annual billing saves 17%.
            14-day trial, no card.
          </div>
          <div style={{ display: 'flex', gap: 12 }}>
            <span
              onClick={(e) => typeof fhCheckout !== 'undefined' ? fhCheckout('bundle', e.currentTarget) : (window.location.href = 'pricing.html')}
              style={{
              padding: '14px 24px', background: FH.accent, color: FH.bg,
              fontSize: 12, letterSpacing: '0.1em', fontWeight: 600, cursor: 'pointer',
            }}>START FREE TRIAL ↗</span>
            <a href="docs.html" style={{
              padding: '14px 24px', border: `1px solid ${FH.border}`, color: FH.ink,
              fontSize: 12, letterSpacing: '0.1em', cursor: 'pointer', textDecoration: 'none',
            }}>VIEW DOCS</a>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1, background: FH.border, border: `1px solid ${FH.border}` }}>
          {FH_PRODUCTS.map(p => (
            <div key={p.id} style={{
              padding: '10px 12px', background: FH.bg2,
              fontSize: 11, color: FH.ink2, fontFamily: '"JetBrains Mono", monospace',
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            }}>
              <span style={{ display: 'flex', gap: 8 }}>
                <span style={{ color: FH.accent }}>✓</span>
                <span>{p.name}</span>
              </span>
              <span style={{ color: FH.ink3, fontSize: 10 }}>${p.price}/mo</span>
            </div>
          ))}
        </div>
      </div>

      {/* FOOTER */}
      <FHFooter />

      {/* Animations */}
      <style>{`
        @keyframes fh-marquee {
          from { transform: translateX(0); }
          to   { transform: translateX(-33.333%); }
        }
        @keyframes fh-blink {
          50% { opacity: 0; }
        }
      `}</style>
    </div>
  );
};

window.TerminalHiFi = TerminalHiFi;
