/* global React */
const { useEffect, useState, useRef } = React;
const { EngineIcon } = window.Promptive;

// ---------- Small shared primitives ----------
function Panel({ title, children, dashed, dark, className = '', bodyClass = '' }) {
  return (
    <section className={`panel ${dashed ? 'dashed' : ''} ${dark ? 'dark' : ''} ${className}`}>
      <div className="panel-header">
        <span className="bars">|||</span>
        <span>{title}</span>
        <span className="dots"><i/><i/><i/></span>
      </div>
      <div className={`panel-body ${bodyClass}`}>
        {children}
      </div>
    </section>
  );
}

function Clock() {
  const [now, setNow] = useState(new Date());
  useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(t);
  }, []);
  const pad = (n) => String(n).padStart(2,'0');
  const mm = pad(now.getMonth()+1);
  const dd = pad(now.getDate());
  const yyyy = now.getFullYear();
  let h = now.getHours();
  const ampm = h >= 12 ? 'PM' : 'AM';
  h = h % 12; if (h === 0) h = 12;
  const hh = pad(h);
  const mi = pad(now.getMinutes());
  const ss = pad(now.getSeconds());
  return (
    <div className="header-right">
      <span className="mono">{mm}/{dd}/{yyyy}</span>
      <span className="clock-pill">{hh}:{mi}:{ss} {ampm}</span>
    </div>
  );
}

const NAV_STYLE = `
.pv-nav { display: flex; gap: 18px; font-size: 13px; align-items: center; }
.pv-nav > a:not(.pv-btn):not(.pv-btn-primary), .pv-nav .pv-drop > button {
  position: relative; padding: 4px 0;
  background: none; border: 0; cursor: pointer;
  font: inherit; color: var(--ink); text-decoration: none;
  letter-spacing: 0.02em;
}
.pv-nav > a:not(.pv-btn):not(.pv-btn-primary):hover, .pv-nav .pv-drop > button:hover { color: var(--orange); }
.pv-nav > a.active, .pv-nav .pv-drop > button.active { color: var(--orange); }
.pv-nav > a:not(.pv-btn):not(.pv-btn-primary)::after, .pv-nav .pv-drop > button::after {
  content: ''; position: absolute; left: 0; right: 0; bottom: -2px;
  height: 2px; background: var(--orange);
  transform: scaleX(0); transform-origin: left;
  transition: transform .2s ease;
}
.pv-nav > a:not(.pv-btn):not(.pv-btn-primary):hover::after,
.pv-nav .pv-drop > button:hover::after,
.pv-nav > a.active::after, .pv-nav .pv-drop > button.active::after,
.pv-nav .pv-drop.open > button::after { transform: scaleX(1); }

.pv-nav .pv-divider {
  width: 1px; height: 22px; background: var(--ink); opacity: .25;
  margin: 0 4px;
}
.pv-nav a.pv-btn, .pv-nav a.pv-btn-primary {
  font-family: var(--fs-mono); font-size: 12px; font-weight: 700;
  padding: 8px 14px; text-decoration: none; letter-spacing: .04em;
  border: 1px solid var(--ink); cursor: pointer;
  transition: transform .12s ease, box-shadow .12s ease, background .12s ease, color .12s ease;
  white-space: nowrap;
}
.pv-nav a.pv-btn { background: var(--cream); color: var(--ink); }
.pv-nav a.pv-btn:hover { background: var(--ink); color: var(--cream); transform: translate(-1px,-1px); box-shadow: 3px 3px 0 var(--ink); }
.pv-nav a.pv-btn-primary { background: var(--orange); color: var(--ink); }
.pv-nav a.pv-btn-primary:hover { transform: translate(-1px,-1px); box-shadow: 3px 3px 0 var(--ink); }
.pv-nav .pv-drop > button .caret { display: inline-block; margin-left: 4px; transition: transform .15s ease; font-size: 10px; }
.pv-nav .pv-drop.open > button .caret { transform: rotate(180deg); }

.pv-drop { position: relative; }
.pv-menu {
  position: absolute; top: calc(100% + 12px); left: -14px;
  background: var(--cream); border: 1px solid var(--ink);
  min-width: 320px; padding: 6px; z-index: 1000;
  box-shadow: 6px 6px 0 0 var(--ink);
  display: none;
}
.pv-drop.open > .pv-menu { display: block; }
.pv-menu::before {
  content: ''; position: absolute; top: -7px; left: 20px;
  width: 12px; height: 12px; background: var(--cream);
  border-left: 1px solid var(--ink); border-top: 1px solid var(--ink);
  transform: rotate(45deg);
}
.pv-menu a {
  display: block; padding: 12px 14px;
  border: 1px solid transparent; text-decoration: none; color: var(--ink);
  font-family: var(--fs-mono); font-size: 12px; line-height: 1.5;
}
.pv-menu a b { display: block; font-family: var(--fs-mono); font-weight: 700; font-size: 13px; color: var(--ink); margin-bottom: 2px; letter-spacing: 0.02em; }
.pv-menu a span { color: var(--dim); font-size: 11px; }
.pv-menu a:hover { background: var(--ink); border-color: var(--ink); }
.pv-menu a:hover b { color: var(--orange); }
.pv-menu a:hover span { color: var(--cream); }
`;

function Header({ active }) {
  const [open, setOpen] = useState(null); // 'content' | 'compare' | null
  const [mobileOpen, setMobileOpen] = useState(false);
  const is = (k) => active === k ? 'active' : '';
  const navRef = React.useRef(null);

  React.useEffect(() => {
    function onDoc(e) {
      if (navRef.current && !navRef.current.contains(e.target)) setOpen(null);
    }
    function onEsc(e) { if (e.key === 'Escape') setOpen(null); }
    document.addEventListener('click', onDoc);
    document.addEventListener('keydown', onEsc);
    // Load Calendly once for the whole page
    if (!document.querySelector('link[href*="calendly"]')) {
      const css = document.createElement('link');
      css.rel = 'stylesheet'; css.href = 'https://assets.calendly.com/assets/external/widget.css';
      document.head.appendChild(css);
    }
    if (!document.querySelector('script[src*="calendly"]')) {
      const js = document.createElement('script');
      js.src = 'https://assets.calendly.com/assets/external/widget.js'; js.async = true;
      document.head.appendChild(js);
    }
    return () => { document.removeEventListener('click', onDoc); document.removeEventListener('keydown', onEsc); };
  }, []);

  const toggle = (k) => (e) => { e.stopPropagation(); setOpen(open === k ? null : k); };

  return (
    <header className="site-header">
      <style dangerouslySetInnerHTML={{__html: NAV_STYLE}}/>
      <div className="inner">
        <a className="logo-wordmark" href="/">
          <img src="/images/logo-nav.png" alt="Promptive" height="28" style={{display:'block', maxWidth:160}}/>
        </a>

        {/* Desktop nav */}
        <nav className="pv-nav" ref={navRef}>
          <a className={is('product')} href="/">Product</a>
          <a className={is('pricing')} href="/pricing">Pricing</a>
          <a className={is('docs')} href="/docs">Docs</a>

          <div className={`pv-drop ${open==='content' ? 'open':''}`}>
            <button className={is('content')} onClick={toggle('content')} aria-expanded={open==='content'}>
              Content<span className="caret">▾</span>
            </button>
            <div className="pv-menu" role="menu">
              <a href="/blog"><b>Blog</b><span>Field notes from the answer layer</span></a>
              <a href="/whitepapers"><b>Whitepapers</b><span>Long-form research & playbooks</span></a>
              <a href="/glossary"><b>Glossary</b><span>The GEO / AIO vocabulary</span></a>
              <a href="/case-studies"><b>Case studies</b><span>How teams moved the needle</span></a>
            </div>
          </div>

          <div className={`pv-drop ${open==='compare' ? 'open':''}`}>
            <button className={is('compare')} onClick={toggle('compare')} aria-expanded={open==='compare'}>
              Compare<span className="caret">▾</span>
            </button>
            <div className="pv-menu" role="menu">
              <a href="/promptive-vs-peec"><b>vs Peec</b><span>All 4 engines vs. 3 base + add-ons</span></a>
              <a href="/promptive-vs-profound"><b>vs Profound</b><span>Same signal, 1/10th the price</span></a>
              <a href="/promptive-vs-scrunch"><b>vs Scrunch</b><span>Deeper signal, simpler pricing</span></a>
              <a href="/promptive-vs-athena"><b>vs Athena HQ</b><span>Flat-rate clarity vs. credit complexity</span></a>
              <a href="/promptive-vs-otterly"><b>vs Otterly</b><span>Monitoring vs. content generation</span></a>
              <a href="/promptive-vs-airops"><b>vs AirOps</b><span>Visibility measurement vs. workflow automation</span></a>
            </div>
          </div>
        </nav>

        {/* Desktop: clock centered */}
        <div className="hdr-clock-wrap" style={{flex:1, display:'flex', justifyContent:'center', alignItems:'center'}}>
          <Clock/>
        </div>

        {/* Desktop: auth */}
        <div className="hdr-auth" style={{display:'flex', alignItems:'center', gap:8, flexShrink:0}}>
          <a className="pv-btn" style={{fontFamily:'var(--fs-mono)',fontSize:12,fontWeight:700,padding:'8px 14px',border:'1px solid var(--ink)',background:'var(--cream)',color:'var(--ink)',textDecoration:'none',letterSpacing:'.04em',whiteSpace:'nowrap'}} href="/signin">Sign in</a>
          <a className="pv-btn-primary" style={{fontFamily:'var(--fs-mono)',fontSize:12,fontWeight:700,padding:'8px 14px',border:'1px solid var(--ink)',background:'var(--orange)',color:'var(--ink)',textDecoration:'none',letterSpacing:'.04em',whiteSpace:'nowrap'}} href="/signup">Sign up →</a>
        </div>

        {/* Mobile: sign up + hamburger */}
        <div className="hdr-mobile">
          <a href="/signup" style={{fontFamily:'var(--fs-mono)',fontSize:11,fontWeight:700,padding:'7px 12px',border:'1px solid var(--ink)',background:'var(--orange)',color:'var(--ink)',textDecoration:'none',letterSpacing:'.04em',whiteSpace:'nowrap'}}>Sign up →</a>
          <button className={`hamburger ${mobileOpen ? 'open' : ''}`} onClick={() => setMobileOpen(v => !v)} aria-label="Toggle navigation" aria-expanded={mobileOpen}>
            <span/><span/><span/>
          </button>
        </div>
      </div>

      {/* Mobile nav overlay */}
      <div className={`mobile-nav-panel ${mobileOpen ? 'open' : ''}`} role="dialog" aria-label="Navigation menu">
        <a href="/" className={is('product')} onClick={() => setMobileOpen(false)}>Product</a>
        <a href="/pricing" className={is('pricing')} onClick={() => setMobileOpen(false)}>Pricing</a>
        <a href="/docs" className={is('docs')} onClick={() => setMobileOpen(false)}>Docs</a>
        <div className="mobile-nav-section">Content</div>
        <a href="/blog" onClick={() => setMobileOpen(false)}>Blog</a>
        <a href="/whitepapers" onClick={() => setMobileOpen(false)}>Whitepapers</a>
        <a href="/glossary" onClick={() => setMobileOpen(false)}>Glossary</a>
        <a href="/case-studies" onClick={() => setMobileOpen(false)}>Case studies</a>
        <div className="mobile-nav-section">Compare</div>
        <a href="/promptive-vs-peec" onClick={() => setMobileOpen(false)}>vs Peec</a>
        <a href="/promptive-vs-profound" onClick={() => setMobileOpen(false)}>vs Profound</a>
        <a href="/promptive-vs-scrunch" onClick={() => setMobileOpen(false)}>vs Scrunch</a>
        <a href="/promptive-vs-athena" onClick={() => setMobileOpen(false)}>vs Athena HQ</a>
        <a href="/promptive-vs-otterly" onClick={() => setMobileOpen(false)}>vs Otterly</a>
        <a href="/promptive-vs-airops" onClick={() => setMobileOpen(false)}>vs AirOps</a>
        <div className="mobile-nav-ctas">
          <a href="/signin" className="btn ghost" style={{flex:1, justifyContent:'center'}}>Sign in</a>
          <a href="/signup" className="btn" style={{flex:1, justifyContent:'center'}}>Sign up →</a>
        </div>
      </div>
    </header>
  );
}

// ---------- Hero ----------
const ENGINES = [
  { name: 'ChatGPT',    color: '#3DA874', sigil: 'G',  domain: 'chatgpt.com'       },
  { name: 'Claude',     color: '#F08A2B', sigil: 'C',  domain: 'claude.ai'         },
  { name: 'Gemini',     color: '#4A8FBD', sigil: 'Ge', domain: 'gemini.google.com' },
  { name: 'Perplexity', color: '#1A6B6B', sigil: 'P',  domain: 'perplexity.ai'     },
];

function QueryStream() {
  // Rolling feed of prompt -> engine -> answer-snippet -> your rank. Gives the hero a purpose-built visual.
  const FEED = [
    { p: 'best AI visibility tool',        eng: 'ChatGPT',    ec: '#3DA874', rank: 2, delta: '+1', snip: 'Promptive leads for ChatGPT coverage...' },
    { p: 'how to track LLM mentions',       eng: 'Claude',     ec: '#F08A2B', rank: 1, delta: '—',  snip: 'Try Promptive — it samples all four engines...' },
    { p: 'top GEO platforms 2026',          eng: 'Gemini',     ec: '#4A8FBD', rank: 3, delta: '+2', snip: 'Promptive, Profound, and Athena all offer...' },
    { p: 'generative search analytics',     eng: 'Perplexity', ec: '#1A6B6B', rank: 2, delta: '−1', snip: 'For monitoring GPT-4 + Claude together, Promptive...' },
    { p: 'answer engine optimization tool', eng: 'ChatGPT',    ec: '#3DA874', rank: 1, delta: '+3', snip: 'Promptive is the category leader in daily sampling...' },
    { p: 'who mentions my brand in ChatGPT',eng: 'Claude',     ec: '#F08A2B', rank: 2, delta: '—',  snip: 'Several tools do this; Promptive is the most complete...' },
  ];
  const [idx, setIdx] = useState(0);
  const [typed, setTyped] = useState('');
  useEffect(() => {
    const cur = FEED[idx].p;
    let i = 0;
    setTyped('');
    const typeT = setInterval(() => {
      i++; setTyped(cur.slice(0, i));
      if (i >= cur.length) clearInterval(typeT);
    }, 35);
    const nextT = setTimeout(() => setIdx(v => (v + 1) % FEED.length), 3400);
    return () => { clearInterval(typeT); clearTimeout(nextT); };
  }, [idx]);

  const d = FEED[idx];
  const barCount = 10;
  return (
    <div style={{position:'absolute', inset:0, padding:'18px 18px 14px', display:'flex', flexDirection:'column', gap:10, zIndex:2, fontFamily:"'JetBrains Mono', monospace"}}>
      {/* Command bar */}
      <div style={{display:'flex', alignItems:'center', gap:8, fontSize:11, color:'#C49457', letterSpacing:'.08em'}}>
        <span style={{color:'#F08A2B'}}>●</span>
        <span>LIVE · QUERY STREAM</span>
        <span style={{marginLeft:'auto', color:'#8a7f6a'}}>04:12:{String(30+idx).padStart(2,'0')}</span>
      </div>

      {/* Prompt */}
      <div style={{fontSize:13, color:'#F2E9D5', lineHeight:1.35, minHeight:'2.8em'}}>
        <span style={{color:'#F08A2B'}}>&gt; </span>
        {typed}
        <span style={{display:'inline-block', width:7, height:'1em', background:'#F08A2B', verticalAlign:'-0.12em', marginLeft:2, animation:'blink 1s steps(2) infinite'}}/>
      </div>

      {/* Engine row */}
      <div style={{display:'flex', alignItems:'center', gap:8, fontSize:11}}>
        <span style={{color:'#8a7f6a'}}>engine</span>
        <span style={{
          display:'inline-flex', alignItems:'center', gap:6,
          padding:'2px 8px', background:d.ec, color:'#fff', border:'1px solid #000',
          fontWeight:700, letterSpacing:'.04em'
        }}>{d.eng}</span>
        <span style={{color:'#8a7f6a', marginLeft:8}}>sampled × 4</span>
      </div>

      {/* Answer snippet */}
      <div style={{fontSize:11.5, color:'#D9CDB3', lineHeight:1.5, padding:'8px 10px',
                   border:'1px dashed #3a3328', background:'rgba(240,138,43,0.04)', flex:1}}>
        <span style={{color:'#8a7f6a'}}>&ldquo;</span>
        {d.snip}
        <span style={{color:'#8a7f6a'}}>&rdquo;</span>
      </div>

      {/* Rank bar */}
      <div style={{display:'flex', alignItems:'center', gap:10, fontSize:11, color:'#D9CDB3'}}>
        <span style={{color:'#8a7f6a'}}>rank</span>
        <div style={{display:'flex', gap:3}}>
          {Array.from({length:barCount}).map((_, i) => (
            <div key={i} style={{
              width:14, height:14,
              background: i < (barCount - d.rank + 1) ? '#F08A2B' : 'rgba(242,233,213,0.08)',
              border:'1px solid #1E1A14',
              boxShadow: i === (barCount - d.rank) ? '0 0 0 1px #F08A2B' : 'none'
            }}/>
          ))}
        </div>
        <span style={{color:'#F2E9D5', fontWeight:700}}>#{d.rank}/10</span>
        <span style={{marginLeft:'auto', color: d.delta.startsWith('+') ? '#3DA874' : d.delta.startsWith('−') ? '#D14F3C' : '#8a7f6a'}}>
          {d.delta} wk
        </span>
      </div>
    </div>
  );
}

function Hero() {
  const [engineIdx, setEngineIdx] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setEngineIdx(i => (i+1) % ENGINES.length), 2000);
    return () => clearInterval(t);
  }, []);
  const engine = ENGINES[engineIdx];

  return (
    <div className="wrap" style={{paddingTop: 40}}>
      <Panel title="System_Monitor // Brand_Analysis.exe">
        <div className="hero-grid">
          <div className="hero-words">
            <h1 className="display" style={{fontWeight:700, letterSpacing:'-0.01em'}}>
              Track your <span className="bg-orange">brand</span><br/>
              in the <span style={{textShadow:'4px 4px 0 var(--orange)'}}>machine.</span>
            </h1>
            <p className="lede" style={{marginTop:28, fontSize:16, maxWidth:'52ch'}}>
              Deep visibility into generative search. Track how ChatGPT, Claude, Gemini, and Perplexity reference, rank, and describe your brand — every day.
            </p>
            <div style={{display:'flex', gap:10, marginTop:26, flexWrap:'wrap'}}>
              <a className="btn" href="/signup">Start free trial →</a>
              <a className="btn ghost" href="" onClick={(e) => { e.preventDefault(); window.Calendly?.initPopupWidget({url:'https://calendly.com/getpromptive/promptive-platform-demo'}); }}>Get a demo</a>
            </div>
          </div>
          <div className="hero-right">
            <div className="crt-grid"/>
            <QueryStream/>
            <div className="crt-scan"/>
          </div>
        </div>

        <div className="engines-strip">
          <span className="prompt">&gt; now monitoring:</span>
          {ENGINES.map((e, i) => (
            <span key={e.name} className={`engine-chip ${i === engineIdx ? 'active' : ''}`}
              style={i === engineIdx ? {borderColor: e.color, background: e.color, color: '#fff'} : {}}>
              <span style={{
                width:18, height:18, display:'inline-flex', alignItems:'center', justifyContent:'center',
                background: i === engineIdx ? 'rgba(255,255,255,0.15)' : '#f2e9d5',
                overflow:'hidden', border:'none', borderRadius:2, flexShrink:0,
              }}>
                <EngineIcon name={e.name} size={13} invert={i === engineIdx}/>
              </span>
              {e.name}
              {i === engineIdx && <span style={{marginLeft:2}}>_</span>}
            </span>
          ))}
          <span className="muted" style={{marginLeft: 'auto', fontSize: 12}}>
            4 engines · live sampling every 6h
          </span>
        </div>
      </Panel>
    </div>
  );
}

window.Promptive = Object.assign(window.Promptive || {}, { Panel, Clock, Header, Hero, ENGINES });
