// Shared components for LineageLens website

const { useState, useEffect, useRef } = React;

// ---------- Nav ----------
function Nav({ current = 'home' }) {
  return (
    <nav className="nav">
      <div className="nav-inner">
        <a href="index.html" className="brand">
          <div className="brand-mark" />
          <span>LineageLens</span>
          <span className="tag" style={{ marginLeft: 6 }}>Upgrade to Pro</span>
        </a>
        <div className="nav-links">
          <a href="solo.html" className={current === 'solo' ? 'active' : ''}>Solo</a>
          <a href="team.html" className={current === 'team' ? 'active' : ''}>Team</a>
          <a href="enterprise.html" className={current === 'enterprise' ? 'active' : ''}>Enterprise</a>
          <a href="demo.html" className={current === 'demo' ? 'active' : ''} style={current === 'demo' ? { color: 'var(--solo)' } : {}}>Playground</a>
          <a href="index.html#pricing">Pricing</a>
          <a href="index.html#faq">FAQ</a>
        </div>
        <div className="nav-cta">
          <a href="https://marketplace.visualstudio.com/items?itemName=karnatipraveen.lineagelens" target="_blank" className="btn btn-ghost">Install free</a>
          <a href="team.html" className="btn btn-primary">Start trial →</a>
        </div>
      </div>
    </nav>
  );
}

// ---------- Footer ----------
function Footer() {
  return (
    <footer>
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="brand" style={{ marginBottom: 12 }}>
              <div className="brand-mark" />
              <span>LineageLens</span>
            </div>
            <p style={{ fontSize: 14, maxWidth: 320 }}>
              Automatic provenance for AI-generated code. Know which prompt wrote which line —
              from your laptop to your production deployment.
            </p>
            <div className="row" style={{ marginTop: 20, gap: 10 }}>
              <a href="#" className="tag">GitHub</a>
              <a href="#" className="tag">X / Twitter</a>
              <a href="#" className="tag">LinkedIn</a>
              <a href="#" className="tag">Discord</a>
            </div>
          </div>
          <div className="footer-links">
            <div className="footer-heading">Product</div>
            <a href="https://marketplace.visualstudio.com/items?itemName=karnatipraveen.lineagelens" target="_blank">Solo (VS Code)</a>
            <a href="team.html">Team</a>
            <a href="enterprise.html">Enterprise</a>
            <a href="index.html#pricing">Pricing</a>
            <a href="#">Changelog</a>
            <a href="#">Status</a>
          </div>
          <div className="footer-links">
            <div className="footer-heading">Resources</div>
            <a href="#">Documentation</a>
            <a href="#">API reference</a>
            <a href="#">Proxy setup</a>
            <a href="#">Compliance brief</a>
            <a href="#">Blog</a>
          </div>
          <div className="footer-links">
            <div className="footer-heading">Company</div>
            <a href="#">About</a>
            <a href="#">Careers</a>
            <a href="#">Security</a>
            <a href="#">Privacy</a>
            <a href="#">Terms</a>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 LineageLens, Inc. · Built for engineers who ship.</span>
          <span className="mono">v1.0.0 · Upgrade to Pro</span>
        </div>
      </div>
    </footer>
  );
}

// ---------- Mode pill ----------
function ModePill({ mode, active, onClick, children }) {
  const colors = { solo: '--solo', team: '--team', enterprise: '--ent' };
  const varName = colors[mode];
  return (
    <button
      onClick={onClick}
      className="mode-pill"
      style={{
        padding: '10px 18px',
        borderRadius: 100,
        fontSize: 14,
        fontWeight: 500,
        border: '1px solid',
        borderColor: active ? `var(${varName})` : 'var(--border)',
        background: active ? `color-mix(in oklab, var(${varName}) 14%, var(--bg-2))` : 'var(--bg-2)',
        color: active ? `var(${varName})` : 'var(--text-muted)',
        display: 'inline-flex',
        alignItems: 'center',
        gap: 8,
        transition: 'all 160ms ease',
      }}
    >
      <span style={{
        width: 8, height: 8, borderRadius: '50%',
        background: `var(${varName})`,
        boxShadow: active ? `0 0 12px var(${varName})` : 'none',
      }} />
      {children}
    </button>
  );
}

// ---------- Feature grid card ----------
function FeatureCard({ icon, title, children, accent }) {
  const [hover, setHover] = useState(false);
  return (
    <div 
      className="card" 
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{ 
        position: 'relative',
        transform: hover ? 'translateY(-4px)' : 'translateY(0)',
        transition: 'all 0.3s ease',
        boxShadow: hover ? `0 12px 30px ${accent ? `color-mix(in oklab, ${accent} 15%, transparent)` : 'rgba(0,0,0,0.2)'}` : 'none',
        borderColor: hover && accent ? `color-mix(in oklab, ${accent} 40%, transparent)` : 'var(--border)'
      }}>
      <div style={{
        width: 36, height: 36, borderRadius: 8,
        background: accent ? `color-mix(in oklab, ${accent} 16%, transparent)` : 'var(--bg-3)',
        color: accent || 'var(--text)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 16, fontFamily: 'var(--mono)', fontSize: 14, fontWeight: 600,
        border: `1px solid ${accent ? `color-mix(in oklab, ${accent} 35%, transparent)` : 'var(--border-muted)'}`,
      }}>{icon}</div>
      <h4 style={{ fontSize: 15, marginBottom: 6 }}>{title}</h4>
      <p style={{ fontSize: 14, lineHeight: 1.5 }}>{children}</p>
    </div>
  );
}

// ---------- Placeholder image ----------
function Placeholder({ label, aspect = '16 / 10', accent }) {
  return (
    <div style={{
      aspectRatio: aspect,
      borderRadius: 10,
      border: '1px solid var(--border)',
      background: `repeating-linear-gradient(135deg, var(--bg-2) 0 10px, var(--bg-3) 10px 20px)`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: 'var(--text-muted)', fontFamily: 'var(--mono)', fontSize: 12,
    }}>
      [ {label} ]
    </div>
  );
}

// ---------- Tweaks panel ----------
function Tweaks({ config, onChange }) {
  const [active, setActive] = useState(false);
  useEffect(() => {
    const onMsg = (e) => {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setActive(true);
      if (e.data.type === '__deactivate_edit_mode') setActive(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);
  if (!active) return null;

  const setKey = (key, val) => {
    onChange({ ...config, [key]: val });
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: val } }, '*');
  };

  return (
    <div className="tweaks-panel">
      <h4>Tweaks</h4>
      <div className="tweak-group">
        <label>Accent palette</label>
        <div className="tweak-opts">
          {['github', 'cyber', 'warm'].map(v => (
            <button key={v}
              className={`tweak-opt ${config.palette === v ? 'active' : ''}`}
              onClick={() => setKey('palette', v)}>{v}</button>
          ))}
        </div>
      </div>
      <div className="tweak-group">
        <label>Hero density</label>
        <div className="tweak-opts">
          {['spacious', 'dense'].map(v => (
            <button key={v}
              className={`tweak-opt ${config.density === v ? 'active' : ''}`}
              onClick={() => setKey('density', v)}>{v}</button>
          ))}
        </div>
      </div>
      <div className="tweak-group">
        <label>Grid background</label>
        <div className="tweak-opts">
          {['on', 'off'].map(v => (
            <button key={v}
              className={`tweak-opt ${config.grid === v ? 'active' : ''}`}
              onClick={() => setKey('grid', v)}>{v}</button>
          ))}
        </div>
      </div>
    </div>
  );
}

// Apply palette at root
function applyPalette(palette) {
  const root = document.documentElement;
  if (palette === 'cyber') {
    root.style.setProperty('--solo', '#22D3EE');
    root.style.setProperty('--team', '#A3E635');
    root.style.setProperty('--ent',  '#F0ABFC');
  } else if (palette === 'warm') {
    root.style.setProperty('--solo', '#FDBA74');
    root.style.setProperty('--team', '#FB7185');
    root.style.setProperty('--ent',  '#C084FC');
  } else {
    root.style.setProperty('--solo', '#58A6FF');
    root.style.setProperty('--team', '#3FB950');
    root.style.setProperty('--ent',  '#A371F7');
  }
}

// ---------- Scroll reveal observer ----------
function initScrollReveal() {
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('is-visible');
      }
    });
  }, { threshold: 0.08, rootMargin: '0px 0px -40px 0px' });

  document.querySelectorAll('.reveal, .reveal-stagger').forEach(el => observer.observe(el));

  // Re-observe on DOM changes (for React re-renders)
  const mo = new MutationObserver(() => {
    document.querySelectorAll('.reveal:not(.is-visible), .reveal-stagger:not(.is-visible)').forEach(el => observer.observe(el));
  });
  mo.observe(document.getElementById('app'), { childList: true, subtree: true });
}

// Auto-init after first paint
if (typeof window !== 'undefined') {
  const _raf = () => requestAnimationFrame(() => setTimeout(initScrollReveal, 100));
  if (document.readyState === 'complete') _raf();
  else window.addEventListener('load', _raf);
}

// ---------- Scroll Background (ambient gradient per section) ----------
function ScrollBackground() {
  const bgRef = useRef(null);

  useEffect(() => {
    const bg = bgRef.current;
    if (!bg) return;

    // Each zone = [spot0, spot1, spot2], all zones have 3 spots (some transparent)
    // spot = { r, g, b, a, x, y, w, h } — radial ellipse % params
    const ZONES = [
      [// 0 Hero — blue
        { r:88,  g:166, b:255, a:0.22, x:65, y:15, w:80, h:55 },
        { r:163, g:113, b:247, a:0.08, x:10, y:80, w:50, h:40 },
        { r:0,   g:0,   b:0,   a:0,   x:50, y:50, w:30, h:30 },
      ],
      [// 1 Problems — red/amber
        { r:248, g:81,  b:73,  a:0.14, x:25, y:35, w:65, h:55 },
        { r:210, g:153, b:34,  a:0.07, x:75, y:70, w:45, h:40 },
        { r:88,  g:166, b:255, a:0.04, x:80, y:15, w:30, h:25 },
      ],
      [// 2 ModeDeepDive — green
        { r:63,  g:185, b:80,  a:0.16, x:70, y:25, w:70, h:55 },
        { r:88,  g:166, b:255, a:0.07, x:15, y:65, w:45, h:40 },
        { r:163, g:113, b:247, a:0.04, x:50, y:85, w:30, h:25 },
      ],
      [// 3 HowItWorks — blue-teal
        { r:88,  g:166, b:255, a:0.16, x:40, y:45, w:75, h:60 },
        { r:63,  g:185, b:80,  a:0.07, x:82, y:15, w:40, h:35 },
        { r:0,   g:0,   b:0,   a:0,   x:50, y:50, w:30, h:30 },
      ],
      [// 4 Security — green/purple
        { r:63,  g:185, b:80,  a:0.12, x:20, y:30, w:55, h:50 },
        { r:163, g:113, b:247, a:0.11, x:78, y:65, w:50, h:45 },
        { r:0,   g:0,   b:0,   a:0,   x:50, y:50, w:30, h:30 },
      ],
      [// 5 Comparison — purple
        { r:163, g:113, b:247, a:0.18, x:62, y:38, w:70, h:55 },
        { r:88,  g:166, b:255, a:0.06, x:18, y:72, w:45, h:40 },
        { r:0,   g:0,   b:0,   a:0,   x:50, y:50, w:30, h:30 },
      ],
      [// 6 Pricing — triple
        { r:88,  g:166, b:255, a:0.11, x:25, y:25, w:55, h:45 },
        { r:63,  g:185, b:80,  a:0.11, x:72, y:55, w:55, h:45 },
        { r:163, g:113, b:247, a:0.09, x:50, y:85, w:40, h:35 },
      ],
      [// 7 Testimonials — balanced triple
        { r:88,  g:166, b:255, a:0.09, x:15, y:35, w:50, h:45 },
        { r:63,  g:185, b:80,  a:0.09, x:50, y:20, w:50, h:45 },
        { r:163, g:113, b:247, a:0.09, x:82, y:60, w:50, h:45 },
      ],
      [// 8 FAQ — subtle blue
        { r:88,  g:166, b:255, a:0.06, x:50, y:45, w:40, h:35 },
        { r:163, g:113, b:247, a:0.05, x:80, y:30, w:35, h:30 },
        { r:0,   g:0,   b:0,   a:0,   x:50, y:50, w:30, h:30 },
      ],
      [// 9 CTA — all three vivid
        { r:88,  g:166, b:255, a:0.18, x:18, y:18, w:60, h:55 },
        { r:63,  g:185, b:80,  a:0.15, x:82, y:28, w:55, h:50 },
        { r:163, g:113, b:247, a:0.15, x:50, y:85, w:60, h:55 },
      ],
    ];

    const lerp = (a, b, t) => a + (b - a) * t;
    const ease = t => t < 0.5 ? 2*t*t : -1 + (4 - 2*t) * t;

    const lerpZones = (A, B, t) => {
      const e = ease(Math.max(0, Math.min(1, t)));
      return A.map((s, i) => ({
        r: lerp(s.r, B[i].r, e), g: lerp(s.g, B[i].g, e), b: lerp(s.b, B[i].b, e),
        a: lerp(s.a, B[i].a, e), x: lerp(s.x, B[i].x, e), y: lerp(s.y, B[i].y, e),
        w: lerp(s.w, B[i].w, e), h: lerp(s.h, B[i].h, e),
      }));
    };

    const buildGrad = spots => {
      const layers = spots
        .filter(s => s.a > 0.001)
        .map(s =>
          `radial-gradient(ellipse ${s.w.toFixed(1)}% ${s.h.toFixed(1)}% at ${s.x.toFixed(1)}% ${s.y.toFixed(1)}%, rgba(${Math.round(s.r)},${Math.round(s.g)},${Math.round(s.b)},${s.a.toFixed(3)}) 0%, transparent 100%)`
        );
      return (layers.length ? layers.join(', ') + ', ' : '') + '#0D1117';
    };

    let secs = [];
    let ticking = false;

    const collectSections = () => { secs = Array.from(document.querySelectorAll('section')); };

    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        ticking = false;
        if (!secs.length) collectSections();
        const sy = window.scrollY;
        const vh = window.innerHeight;
        const trigger = sy + vh * 0.4;

        let zi = 0, t = 0;
        for (let i = 0; i < secs.length; i++) {
          const top  = secs[i].offsetTop;
          const bot  = secs[i + 1] ? secs[i + 1].offsetTop : top + secs[i].offsetHeight;
          if (trigger >= top && trigger < bot) {
            zi = Math.min(i, ZONES.length - 2);
            t  = (trigger - top) / (bot - top);
            break;
          }
          if (i === secs.length - 1 && trigger >= bot) { zi = ZONES.length - 2; t = 1; }
        }

        const from = ZONES[Math.min(zi,   ZONES.length - 1)];
        const to   = ZONES[Math.min(zi+1, ZONES.length - 1)];
        bg.style.background = buildGrad(lerpZones(from, to, t));
      });
    };

    setTimeout(() => { collectSections(); onScroll(); }, 250);
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', () => { collectSections(); onScroll(); });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return <div ref={bgRef} id="scroll-bg" />;
}

// ---------- Scroll Progress Bar ----------
function ScrollProgress() {
  const barRef = useRef(null);
  useEffect(() => {
    const bar = barRef.current;
    if (!bar) return;
    let ticking = false;
    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        ticking = false;
        const h = document.documentElement.scrollHeight - window.innerHeight;
        bar.style.width = (h > 0 ? (window.scrollY / h) * 100 : 0) + '%';
      });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return <div ref={barRef} id="scroll-progress" />;
}

// ---------- Cursor Spotlight ----------
function CursorSpotlight() {
  const spotRef = useRef(null);
  useEffect(() => {
    const el = spotRef.current;
    if (!el) return;
    let ax = -9999, ay = -9999, cx = -9999, cy = -9999, raf;
    const onMove = e => { ax = e.clientX; ay = e.clientY; };
    const tick = () => {
      cx += (ax - cx) * 0.12;
      cy += (ay - cy) * 0.12;
      el.style.left = cx + 'px';
      el.style.top  = cy + 'px';
      raf = requestAnimationFrame(tick);
    };
    window.addEventListener('mousemove', onMove);
    raf = requestAnimationFrame(tick);
    return () => { window.removeEventListener('mousemove', onMove); cancelAnimationFrame(raf); };
  }, []);
  return <div ref={spotRef} id="cursor-spot" />;
}

// ---------- Section Nav Dots ----------
function SectionNav() {
  const [active, setActive] = useState(0);
  const ITEMS = [
    { label: 'Hero',     href: '#' },
    { label: 'Problem',  href: '#problem' },
    { label: 'Modes',    href: '#modes' },
    { label: 'How',      href: '#how' },
    { label: 'Security', href: '#security' },
    { label: 'Compare',  href: '#compare' },
    { label: 'Pricing',  href: '#pricing' },
    { label: 'Stories',  href: '#stories' },
    { label: 'FAQ',      href: '#faq' },
  ];

  useEffect(() => {
    const secs = Array.from(document.querySelectorAll('section'));
    if (!secs.length) return;
    const obs = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          const i = secs.indexOf(e.target);
          if (i >= 0 && i < ITEMS.length) setActive(i);
        }
      });
    }, { threshold: 0.35 });
    secs.slice(0, ITEMS.length).forEach(s => obs.observe(s));
    return () => obs.disconnect();
  }, []);

  return (
    <div id="section-nav">
      {ITEMS.map((item, i) => (
        <a key={i} href={item.href} title={item.label} className={active === i ? 'active' : ''} />
      ))}
    </div>
  );
}

Object.assign(window, {
  Nav, Footer, ModePill, FeatureCard, Placeholder, Tweaks, applyPalette, initScrollReveal,
  ScrollBackground, ScrollProgress, CursorSpotlight, SectionNav,
});
