const { useEffect, useState, useRef } = React;

// 1. Global Reveal Hook
function useRevealObserver() {
  useEffect(() => {
    const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          entry.target.classList.add('is-visible');
          if (!prefersReducedMotion) {
            // Once revealed, don't hide it again to prevent jittering, 
            // unless specific replay behavior is wanted.
            observer.unobserve(entry.target);
          }
        }
      });
    }, { threshold: 0.12, rootMargin: '-80px' });

    // Initial query
    const elements = document.querySelectorAll('[data-reveal], .graph-container, .section-title-wrap');
    elements.forEach(el => observer.observe(el));

    // Cleanup
    return () => observer.disconnect();
  }, []);
}

// 2. Cinematic Hero
function CinematicHero({ config }) {
  const bgRef = useRef(null);
  const [text, setText] = useState('');
  const fullText = "Provenance for AI-generated code.";
  
  // Typing effect
  useEffect(() => {
    let i = 0;
    const interval = setInterval(() => {
      setText(fullText.slice(0, i));
      i++;
      if (i > fullText.length) clearInterval(interval);
    }, 60);
    return () => clearInterval(interval);
  }, []);

  // Parallax
  useEffect(() => {
    let rafId;
    let lastScrollY = window.scrollY;
    
    const tick = () => {
      if (lastScrollY !== window.scrollY) {
        lastScrollY = window.scrollY;
        if (bgRef.current) {
          // Translate bg layers at 0.2x and 0.4x
          const layers = bgRef.current.children;
          if (layers[0]) layers[0].style.transform = `translateY(${lastScrollY * 0.2}px)`;
          if (layers[1]) layers[1].style.transform = `translateY(${lastScrollY * 0.4}px)`;
        }
      }
      rafId = requestAnimationFrame(tick);
    };
    rafId = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafId);
  }, []);

  // Generate particles
  const particles = useRef([...Array(25)].map((_, i) => ({
    id: i,
    left: Math.random() * 100 + '%',
    color: ['var(--solo)', 'var(--team)', 'var(--ent)'][Math.floor(Math.random() * 3)],
    delay: Math.random() * 10 + 's',
    duration: (10 + Math.random() * 8) + 's'
  }))).current;

  return (
    <section className="hero-cinematic reveal is-visible" style={{ borderTop: 'none' }}>
      {/* Parallax Background Wrapper */}
      <div ref={bgRef} style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
        <div className="hero-bg-layer" style={{ willChange: 'transform' }}>
          <div className="hero-pulse-1" style={{ position: 'absolute', inset: 0 }} />
          <div className="hero-pulse-2" style={{ position: 'absolute', inset: 0 }} />
          <div className="hero-pulse-3" style={{ position: 'absolute', inset: 0 }} />
        </div>
        <div className="hero-grid" style={{ willChange: 'transform' }} />
      </div>

      {particles.map(p => (
        <div key={p.id} className="particle" style={{
          left: p.left,
          background: p.color,
          boxShadow: `0 0 10px ${p.color}, 0 0 20px ${p.color}`,
          animation: `floatParticle ${p.duration} ${p.delay} infinite linear`
        }} />
      ))}

      <div className="container" style={{ position: 'relative', zIndex: 10, textAlign: 'center' }}>
        <div className="eyebrow lift" style={{ '--accent': 'var(--solo)', marginBottom: 24, padding: '6px 16px', background: 'rgba(255,255,255,0.03)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.1)' }}>
          <span className="dot" />
          LINEAGELENS 2.0 IS LIVE
        </div>
        
        <h1 style={{ fontSize: 'clamp(40px, 6vw, 72px)', maxWidth: 900, margin: '0 auto 24px', lineHeight: 1.1, letterSpacing: '-0.04em', textAlign: 'center', display: 'flex', justifyContent: 'center', flexWrap: 'wrap', alignItems: 'center' }}>
          <span className="headline-gradient">{text}</span>
          <span className="typing-caret" />
        </h1>
        
        <p className="lead" style={{ margin: '0 auto 40px', maxWidth: 640, fontSize: 20, color: 'var(--text-muted)' }} data-reveal="fade" style={{'--reveal-delay': '1s'}}>
          Track, govern, and secure every line of code written by AI across your entire organization.
        </p>

        <div className="row" style={{ justifyContent: 'center', gap: 16 }} data-reveal="scale" style={{'--reveal-delay': '1.2s'}}>
          <a href="demo.html" className="btn btn-lg btn-glow" style={{ background: 'var(--text)', color: 'var(--bg-1)' }}>
            Try the Playground
          </a>
          <a href="enterprise.html" className="btn btn-lg btn-ghost lift">
            Enterprise Readiness
          </a>
        </div>
      </div>

      <div className="scroll-hint">
        <span className="mono dim" style={{ fontSize: 10, letterSpacing: '0.1em' }}>SCROLL</span>
        <div className="scroll-line" />
      </div>
    </section>
  );
}

// 3. Interactive Lineage / Flow Graph
function InteractiveGraph() {
  const [isVisible, setIsVisible] = useState(false);
  const containerRef = useRef(null);

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

  const nodes = [
    { id: 1, cx: 100, cy: 150, label: "Cursor AI", color: "var(--solo)", delay: 100 },
    { id: 2, cx: 300, cy: 150, label: "VS Code Ext", color: "var(--team)", delay: 200 },
    { id: 3, cx: 500, cy: 80, label: "Correlator", color: "var(--ent)", delay: 300 },
    { id: 4, cx: 500, cy: 220, label: "Risk Engine", color: "var(--red)", delay: 400 },
    { id: 5, cx: 700, cy: 150, label: "Neo4j Graph", color: "var(--text)", delay: 500 },
  ];

  const edges = [
    { id: 'e1', d: "M 120 150 L 280 150", delay: 600 },
    { id: 'e2', d: "M 320 140 L 480 90", delay: 700 },
    { id: 'e3', d: "M 320 160 L 480 210", delay: 800 },
    { id: 'e4', d: "M 520 80 L 680 140", delay: 900 },
    { id: 'e5', d: "M 520 220 L 680 160", delay: 1000 },
  ];

  return (
    <section className="container graph-container" ref={containerRef} style={{ padding: '96px 32px' }}>
      <div className="section-title-wrap" style={{ marginBottom: 48 }}>
        <div className="eyebrow lift" style={{ '--accent': 'var(--ent)' }}><span className="dot" />LINEAGE</div>
        <h2 style={{ marginTop: 16 }}>From prompt to production.</h2>
      </div>

      <div style={{ background: 'var(--bg-2)', borderRadius: 16, border: '1px solid var(--border)', padding: 40, overflow: 'hidden' }} className="lift">
        <svg viewBox="0 0 800 300" style={{ width: '100%', height: 'auto', display: 'block', overflow: 'visible' }}>
          <defs>
            <marker id="arrowhead" markerWidth="6" markerHeight="6" refX="5" refY="3" orient="auto">
              <path d="M0,0 L6,3 L0,6 Z" fill="var(--text-muted)" />
            </marker>
          </defs>
          
          {/* Edges */}
          {edges.map(e => (
            <path key={e.id} d={e.d} 
              className={`graph-edge ${isVisible ? 'is-active' : ''}`}
              style={{ transitionDelay: `${e.delay}ms` }}
              stroke="var(--border)" strokeWidth="2" fill="none" markerEnd="url(#arrowhead)" />
          ))}

          {/* Nodes */}
          {nodes.map(n => (
            <g key={n.id} className={`graph-node ${isVisible ? 'is-active' : ''}`} style={{ transitionDelay: `${n.delay}ms`, transformOrigin: `${n.cx}px ${n.cy}px` }}>
              <circle cx={n.cx} cy={n.cy} r="24" className="graph-halo" fill={n.color} />
              <circle cx={n.cx} cy={n.cy} r="20" fill="var(--bg-1)" stroke={n.color} strokeWidth="2" />
              <text x={n.cx} y={n.cy + 40} fill="var(--text-muted)" fontSize="12" fontFamily="var(--mono)" textAnchor="middle">{n.label}</text>
            </g>
          ))}
        </svg>
      </div>
    </section>
  );
}

// 4. Scroll-Scrubbed Code Demo
function CodeScrubber() {
  const [activeStep, setActiveStep] = useState(0);
  const stepsRef = useRef([]);

  useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          const idx = parseInt(e.target.dataset.idx, 10);
          setActiveStep(idx);
        }
      });
    }, { threshold: 0.6, rootMargin: '-10% 0px -40% 0px' });

    stepsRef.current.forEach(el => {
      if (el) obs.observe(el);
    });
    return () => obs.disconnect();
  }, []);

  const steps = [
    { title: "AI writes the code", desc: "A developer asks Copilot to generate a payment integration. The AI returns a complete block, including hardcoded secrets.", lines: [1, 5] },
    { title: "Proxy captures provenance", desc: "LineageLens local proxy silently grabs the prompt and the exact AST of the insertion.", lines: [2, 3] },
    { title: "Risk engine flags vulnerability", desc: "The backend spots the hardcoded secret and immediately tags the insertion with HIGH risk.", lines: [3, 4] },
  ];

  return (
    <section className="container" style={{ padding: '96px 32px' }} data-reveal="fade">
      <div className="section-title-wrap" style={{ marginBottom: 48 }}>
        <div className="eyebrow lift" style={{ '--accent': 'var(--team)' }}><span className="dot" />TRACKING</div>
        <h2 style={{ marginTop: 16 }}>Every insertion, analyzed.</h2>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64, alignItems: 'flex-start' }}>
        
        {/* Left: Sticky Code Window */}
        <div style={{ position: 'sticky', top: 120 }}>
          <div className="code-window lift" style={{ background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 12 }}>
            <div className="code-header" style={{ borderBottom: '1px solid var(--border-muted)', padding: '12px 16px', display: 'flex', justifyContent: 'space-between' }}>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <div className="code-dots"><span/><span/><span/></div>
                <span className="mono dim" style={{ fontSize: 12 }}>payments.ts</span>
              </div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--solo)' }}>Step {activeStep + 1} of 3</div>
            </div>
            <div style={{ padding: '24px 16px', fontFamily: 'var(--mono)', fontSize: 13, lineHeight: 1.6 }}>
              <div className={`scrubber-code-line ${activeStep === 0 ? 'is-active' : ''}`}><span className="dim">1</span> <span className="tok-kw">async function</span> <span className="tok-fn">processPayment</span>() {'{'}</div>
              <div className={`scrubber-code-line ${activeStep === 1 ? 'is-active' : ''} scrubber-code-ai`}><span className="dim">2</span>   <span className="tok-com">// Generated by Copilot</span></div>
              <div className={`scrubber-code-line ${activeStep === 1 || activeStep === 2 ? 'is-active' : ''} scrubber-code-ai`}><span className="dim">3</span>   <span className="tok-kw">const</span> <span className="tok-var">API_KEY</span> = <span className="tok-str">"sk_live_123456789"</span>;</div>
              <div className={`scrubber-code-line ${activeStep === 2 ? 'is-active' : ''} scrubber-code-ai`}><span className="dim">4</span>   <span className="tok-kw">await</span> <span className="tok-fn">fetch</span>(<span className="tok-str">"https://api.stripe.com/v1/charges"</span>, {'{'}</div>
              <div className={`scrubber-code-line ${activeStep === 0 ? 'is-active' : ''} scrubber-code-ai`}><span className="dim">5</span>     headers: {'{'} <span className="tok-str">"Authorization"</span>: <span className="tok-str">{"`Bearer ${API_KEY}`"}</span> {'}'}</div>
              <div className={`scrubber-code-line`}><span className="dim">6</span>   {'}'});</div>
              <div className={`scrubber-code-line`}><span className="dim">7</span> {'}'}</div>
            </div>
          </div>
        </div>

        {/* Right: Narrative Steps */}
        <div style={{ paddingTop: '20vh', paddingBottom: '30vh' }}>
          {steps.map((s, i) => (
            <div 
              key={i} 
              data-idx={i}
              ref={el => stepsRef.current[i] = el}
              className={`scrubber-step ${activeStep === i ? 'is-active' : ''}`}
              style={{ marginBottom: '40vh', borderLeft: activeStep === i ? '2px solid var(--solo)' : '2px solid var(--border-muted)', paddingLeft: 32 }}
            >
              <div className="mono" style={{ fontSize: 12, color: activeStep === i ? 'var(--solo)' : 'var(--text-muted)', marginBottom: 12 }}>STEP 0{i + 1}</div>
              <h3 style={{ fontSize: 24, marginBottom: 16, color: activeStep === i ? 'var(--text)' : 'var(--text-muted)', transition: 'color 400ms ease' }}>{s.title}</h3>
              <p style={{ fontSize: 16, color: 'var(--text-muted)', lineHeight: 1.6 }}>{s.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// 5. Mode-Specific Motion Backgrounds
function SoloMotionBg() {
  return <div className="motion-bg-solo" />;
}

function TeamMotionBg() {
  return (
    <div className="motion-bg-team">
      <div className="team-sonar-ring" />
      <div className="team-sonar-ring" />
      <div className="team-sonar-ring" />
      <div className="team-sonar-ring" />
    </div>
  );
}

function EntMotionBg() {
  return <div className="motion-bg-ent" />;
}

// Export to global scope for Babel
Object.assign(window, { 
  useRevealObserver, CinematicHero, InteractiveGraph, CodeScrubber,
  SoloMotionBg, TeamMotionBg, EntMotionBg 
});
