const { useRef, useEffect, useState } = React;

// ── HERO SECTION ──────────────────────────────────────────────────────────────
const HeroSection = () => {
  const canvasRef = useRef(null);
  const [wordIdx, setWordIdx] = useState(0);
  const cycleWords = ['Software', 'Ecommerce', 'AI', 'Automation', 'Growth'];

  // Cycling word swap
  useEffect(() => {
    const id = setInterval(() => setWordIdx(i => (i + 1) % cycleWords.length), 1500);
    return () => clearInterval(id);
  }, []);

  // Word reveal stagger
  useEffect(() => {
    const els = document.querySelectorAll('.hero-word');
    els.forEach((el, i) => setTimeout(() => el.classList.add('revealed'), 300 + i * 90));
  }, []);

  // Fade up elements
  useEffect(() => {
    const els = document.querySelectorAll('.hero-fu');
    els.forEach((el, i) => setTimeout(() => el.classList.add('vis'), 1200 + i * 150));
  }, []);

  // Three.js — TorusKnot wireframe hero
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || !window.THREE) return;
    const T = window.THREE;

    const scene = new T.Scene();
    const camera = new T.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100);
    camera.position.z = 4.5;

    const renderer = new T.WebGLRenderer({ canvas, alpha: true, antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));

    // Primary torusknot — jaali/lattice feel
    const geo = new T.TorusKnotGeometry(1.3, 0.38, 180, 20);
    const mat = new T.MeshBasicMaterial({ color: 0xF5F1EA, wireframe: true, transparent: true, opacity: 0.18 });
    const mesh = new T.Mesh(geo, mat);
    scene.add(mesh);

    // Gold accent ring
    const rGeo = new T.TorusGeometry(2.5, 0.006, 6, 120);
    const rMat = new T.MeshBasicMaterial({ color: 0xD4AF37, transparent: true, opacity: 0.35 });
    const ring = new T.Mesh(rGeo, rMat);
    ring.rotation.x = Math.PI * 0.5;
    scene.add(ring);

    // Second thinner ring
    const r2Geo = new T.TorusGeometry(1.9, 0.004, 6, 120);
    const r2Mat = new T.MeshBasicMaterial({ color: 0xE25822, transparent: true, opacity: 0.25 });
    const ring2 = new T.Mesh(r2Geo, r2Mat);
    ring2.rotation.x = Math.PI * 0.35;
    ring2.rotation.y = Math.PI * 0.2;
    scene.add(ring2);

    let mx = 0, my = 0, tx = 0, ty = 0;
    const onMouse = e => {
      mx = (e.clientX / window.innerWidth - 0.5);
      my = (e.clientY / window.innerHeight - 0.5);
    };
    window.addEventListener('mousemove', onMouse);

    let scrollY = 0;
    const onScroll = () => { scrollY = window.scrollY; };
    window.addEventListener('scroll', onScroll, { passive: true });

    const clock = new T.Clock();
    let raf;
    const tick = () => {
      raf = requestAnimationFrame(tick);
      const t = clock.getElapsedTime();
      tx += (mx - tx) * 0.04;
      ty += (my - ty) * 0.04;

      mesh.rotation.x = t * 0.10 + ty * 0.35;
      mesh.rotation.y = t * 0.16 + tx * 0.35;
      ring.rotation.z = t * 0.04;
      ring.rotation.x = Math.PI * 0.5 + ty * 0.15;
      ring2.rotation.z = -t * 0.07;
      ring2.rotation.y = t * 0.03 + tx * 0.1;

      const prog = Math.min(scrollY / window.innerHeight, 1);
      camera.position.z = 4.5 - prog * 2.0;
      mat.opacity = Math.max(0, 0.18 - prog * 0.25);
      rMat.opacity = Math.max(0, 0.35 - prog * 0.5);
      r2Mat.opacity = Math.max(0, 0.25 - prog * 0.4);

      renderer.render(scene, camera);
    };
    tick();

    const onResize = () => {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    };
    window.addEventListener('resize', onResize);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('mousemove', onMouse);
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onResize);
      geo.dispose(); mat.dispose();
      rGeo.dispose(); rMat.dispose();
      r2Geo.dispose(); r2Mat.dispose();
      renderer.dispose();
    };
  }, []);

  const lines = [
    ['We', 'build,', 'grow', '&'],
    ['automate', '—', 'for', 'brands'],
    ['that', 'refuse', 'to', 'be'],
    ['ordinary.'],
  ];
  const allWords = lines.flat();
  let wi = 0;

  return (
    <section id="hero" style={{ position: 'relative', height: '100vh', overflow: 'hidden', background: '#0A0A0A' }}>
      <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', zIndex: 1 }} />

      {/* Radial vignette */}
      <div style={{ position: 'absolute', inset: 0, zIndex: 2, background: 'radial-gradient(ellipse 80% 80% at 50% 50%, transparent 30%, #0A0A0A 85%)' }} />

      {/* Nav */}
      <nav style={{ position: 'absolute', top: 32, right: 48, display: 'flex', gap: 36, zIndex: 10 }}>
        {[['Work','#work'],['Services','services.html'],['Process','#process'],['About','#about'],['Contact','#contact']].map(([n, href]) => (
          <a key={n} href={href} className="ul-link"
            style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: 'var(--cream)', textTransform: 'uppercase', opacity: 0.75 }}>
            {n}
          </a>
        ))}
      </nav>

      {/* Top-left label */}
      <div style={{ position: 'absolute', top: 32, left: 48, zIndex: 10 }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.22em', color: 'var(--gold)', opacity: 0.85 }}>
          [ JAIPUR · EST 2020 ]
        </span>
      </div>

      {/* Logo center-top */}
      <div style={{ position: 'absolute', top: 28, left: '50%', transform: 'translateX(-50%)', zIndex: 10 }}>
        <span style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 900, letterSpacing: '0.45em', color: 'var(--cream)', textTransform: 'uppercase' }}>
          ERIONT
        </span>
      </div>

      {/* Hero text */}
      <div style={{ position: 'absolute', inset: 0, zIndex: 10, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 5vw', textAlign: 'center' }}>
        <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(2.8rem, 6.5vw, 8.5rem)', lineHeight: 1.04, letterSpacing: '-0.025em', maxWidth: '1100px', marginBottom: 36 }}>
          {lines.map((line, li) => (
            <div key={li} style={{ display: 'block' }}>
              {line.map((word) => {
                const idx = wi++;
                const isAutomate = word === 'automate';
                return (
                  <span key={idx} className="word-wrapper" style={{ marginRight: '0.22em' }}>
                    <span className="word-inner hero-word" style={{ animationDelay: `${idx * 0.09}s` }}>
                      {isAutomate ? <span className="grad">{word}</span> : word}
                    </span>
                  </span>
                );
              })}
            </div>
          ))}
        </h1>

        {/* Cycling word */}
        <div className="hero-fu fu" style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 20 }}>
          <div style={{ width: 36, height: 1, background: 'var(--gold)', opacity: 0.55 }} />
          <span key={wordIdx} style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.24em', color: 'var(--cream)', opacity: 0.7, textTransform: 'uppercase', transition: 'opacity 0.3s' }}>
            {cycleWords[wordIdx]}
          </span>
          <div style={{ width: 36, height: 1, background: 'var(--gold)', opacity: 0.55 }} />
        </div>
      </div>

      {/* Scroll indicator */}
      <div className="hero-fu fu" style={{ position: 'absolute', bottom: 68, left: '50%', transform: 'translateX(-50%)', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, zIndex: 10 }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 8, letterSpacing: '0.25em', color: 'var(--cream)', opacity: 0.35 }}>SCROLL</span>
        <div style={{ width: 1, height: 44, background: 'linear-gradient(to bottom, var(--terra), transparent)', animation: 'scrollPulse 2s ease-in-out infinite' }} />
      </div>

      {/* Bottom marquee */}
      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, overflow: 'hidden', borderTop: '1px solid rgba(245,241,234,0.07)', zIndex: 10 }}>
        <div className="marquee-left" style={{ padding: '8px 0' }}>
          {Array(8).fill(null).map((_, i) => (
            <span key={i} style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.22em', color: 'var(--cream)', opacity: 0.3, whiteSpace: 'nowrap', paddingRight: 60 }}>
              Available for new projects · Q2 2026 ·
            </span>
          ))}
        </div>
      </div>
    </section>
  );
};

// ── WOW SECTION — Point cloud sphere ─────────────────────────────────────────
const WowSection = () => {
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || !window.THREE) return;
    const T = window.THREE;

    const scene = new T.Scene();
    const w = canvas.clientWidth || window.innerWidth;
    const h = canvas.clientHeight || window.innerHeight;
    const camera = new T.PerspectiveCamera(70, w / h, 0.1, 100);
    camera.position.z = 5;

    const renderer = new T.WebGLRenderer({ canvas, alpha: true, antialias: true });
    renderer.setSize(w, h);
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));

    // Fibonacci sphere distribution
    const count = 1200;
    const pos = new Float32Array(count * 3);
    const orig = new Float32Array(count * 3);
    const golden = Math.PI * (3 - Math.sqrt(5));
    for (let i = 0; i < count; i++) {
      const y = 1 - (i / (count - 1)) * 2;
      const r = Math.sqrt(1 - y * y) * 2.2;
      const theta = golden * i;
      pos[i*3]   = r * Math.cos(theta);
      pos[i*3+1] = y * 2.2;
      pos[i*3+2] = r * Math.sin(theta);
      orig[i*3] = pos[i*3]; orig[i*3+1] = pos[i*3+1]; orig[i*3+2] = pos[i*3+2];
    }
    const geo = new T.BufferGeometry();
    geo.setAttribute('position', new T.BufferAttribute(pos, 3));
    const mat = new T.PointsMaterial({ color: 0xE25822, size: 0.038, transparent: true, opacity: 0.85 });
    const pts = new T.Points(geo, mat);
    scene.add(pts);

    // Gold accent pts
    const gCount = 300;
    const gPos = new Float32Array(gCount * 3);
    for (let i = 0; i < gCount; i++) {
      const phi = Math.acos(-1 + (2 * i) / gCount);
      const th = Math.sqrt(gCount * Math.PI) * phi;
      gPos[i*3] = 2.8 * Math.sin(phi) * Math.cos(th);
      gPos[i*3+1] = 2.8 * Math.sin(phi) * Math.sin(th);
      gPos[i*3+2] = 2.8 * Math.cos(phi);
    }
    const gGeo = new T.BufferGeometry();
    gGeo.setAttribute('position', new T.BufferAttribute(gPos, 3));
    const gMat = new T.PointsMaterial({ color: 0xD4AF37, size: 0.022, transparent: true, opacity: 0.4 });
    const gPts = new T.Points(gGeo, gMat);
    scene.add(gPts);

    let mxW = 0, myW = 0;
    const onMouse = e => {
      mxW = (e.clientX / window.innerWidth - 0.5) * 2;
      myW = (e.clientY / window.innerHeight - 0.5) * 2;
    };
    window.addEventListener('mousemove', onMouse);

    const clock = new T.Clock();
    let raf;
    const tick = () => {
      raf = requestAnimationFrame(tick);
      const t = clock.getElapsedTime();
      const breathe = 1 + Math.sin(t * 0.7) * 0.07;
      const pArr = geo.attributes.position.array;
      for (let i = 0; i < count; i++) {
        const d = 1 + mxW * 0.08 * Math.sin(i * 0.07 + t) + myW * 0.08 * Math.cos(i * 0.07 + t);
        pArr[i*3]   = orig[i*3]   * breathe * d;
        pArr[i*3+1] = orig[i*3+1] * breathe;
        pArr[i*3+2] = orig[i*3+2] * breathe;
      }
      geo.attributes.position.needsUpdate = true;
      pts.rotation.y = t * 0.10;
      pts.rotation.x = t * 0.04;
      gPts.rotation.y = -t * 0.06;
      renderer.render(scene, camera);
    };
    tick();

    const onResize = () => {
      const nw = window.innerWidth, nh = window.innerHeight;
      camera.aspect = nw / nh;
      camera.updateProjectionMatrix();
      renderer.setSize(nw, nh);
    };
    window.addEventListener('resize', onResize);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('mousemove', onMouse);
      window.removeEventListener('resize', onResize);
      geo.dispose(); mat.dispose();
      gGeo.dispose(); gMat.dispose();
      renderer.dispose();
    };
  }, []);

  return (
    <section style={{ position: 'relative', height: '100vh', background: '#060606', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
      <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', zIndex: 1 }} />
      <div style={{ position: 'absolute', inset: 0, zIndex: 2, background: 'radial-gradient(ellipse 60% 60% at 50% 50%, transparent 20%, rgba(6,6,6,0.7) 75%)' }} />
      <div style={{ position: 'relative', zIndex: 10, textAlign: 'center', padding: '0 6vw', maxWidth: 900 }}>
        <p style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontWeight: 700, fontSize: 'clamp(2rem, 4.5vw, 6rem)', lineHeight: 1.18, color: 'var(--cream)', letterSpacing: '-0.02em', textWrap: 'pretty' }}>
          "The web is no longer<br />a brochure.<br />
          <span className="grad">It's an experience."</span>
        </p>
        <div style={{ marginTop: 40, display: 'flex', justifyContent: 'center' }}>
          <div className="gold-rule" style={{ width: 120 }} />
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { HeroSection, WowSection });
