// Hero with shader-style canvas backdrop + STUND wave + magnetic nav

const { useEffect, useRef, useState } = React;

// ─────────────────────────── Shader-ish canvas ────────────────────────────
function HeroShader() {
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    let raf, t = 0;
    let w, h, dpr;

    const resize = () => {
      dpr = Math.min(window.devicePixelRatio || 1, 2);
      w = canvas.clientWidth;
      h = canvas.clientHeight;
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    window.addEventListener('resize', resize);

    // Pseudo-shader: layered radial gradients + flow field of dots/lines
    const N = 140;
    const particles = Array.from({ length: N }, () => ({
      x: Math.random(),
      y: Math.random(),
      r: 0.3 + Math.random() * 1.6,
      s: 0.2 + Math.random() * 0.8,
      a: Math.random() * Math.PI * 2,
    }));

    const draw = () => {
      t += 0.005;
      // Base gradient backdrop - deep black with orange glow
      const cx = w / 2 + Math.sin(t * 0.5) * w * 0.08;
      const cy = h * 0.55 + Math.cos(t * 0.4) * h * 0.05;
      const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, Math.max(w, h) * 0.7);
      g.addColorStop(0, 'rgba(240,85,3,0.18)');
      g.addColorStop(0.35, 'rgba(40,12,4,0.6)');
      g.addColorStop(1, 'rgba(5,5,5,1)');
      ctx.fillStyle = g;
      ctx.fillRect(0, 0, w, h);

      // Secondary cool glow
      const g2 = ctx.createRadialGradient(w * 0.85, h * 0.15, 0, w * 0.85, h * 0.15, w * 0.5);
      g2.addColorStop(0, 'rgba(80, 40, 120, 0.18)');
      g2.addColorStop(1, 'rgba(0,0,0,0)');
      ctx.fillStyle = g2;
      ctx.fillRect(0, 0, w, h);

      // Flowing curves — wireframe mesh feel
      ctx.strokeStyle = 'rgba(240,85,3,0.06)';
      ctx.lineWidth = 1;
      for (let i = 0; i < 24; i++) {
        ctx.beginPath();
        const off = i / 24;
        for (let x = 0; x <= w; x += 12) {
          const nx = x / w;
          const y = h * 0.5 +
            Math.sin(nx * 6 + t * 1.2 + off * 6) * 80 * Math.sin(t * 0.3 + off * 3) +
            Math.cos(nx * 3 + t * 0.7) * 40 +
            (off - 0.5) * h * 1.4;
          if (x === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
        }
        ctx.stroke();
      }

      // Particles
      particles.forEach((p) => {
        p.a += 0.005 * p.s;
        p.x += Math.cos(p.a) * 0.0007 * p.s;
        p.y += Math.sin(p.a) * 0.0007 * p.s;
        if (p.x < 0) p.x = 1; if (p.x > 1) p.x = 0;
        if (p.y < 0) p.y = 1; if (p.y > 1) p.y = 0;
        ctx.fillStyle = `rgba(255,255,255,${0.15 + Math.sin(t + p.a) * 0.1})`;
        ctx.beginPath();
        ctx.arc(p.x * w, p.y * h, p.r, 0, Math.PI * 2);
        ctx.fill();
      });

      // Sweep line
      const sweepX = ((Math.sin(t * 0.4) + 1) / 2) * w;
      const lg = ctx.createLinearGradient(sweepX - 200, 0, sweepX + 200, 0);
      lg.addColorStop(0, 'rgba(240,85,3,0)');
      lg.addColorStop(0.5, 'rgba(240,85,3,0.08)');
      lg.addColorStop(1, 'rgba(240,85,3,0)');
      ctx.fillStyle = lg;
      ctx.fillRect(0, 0, w, h);

      raf = requestAnimationFrame(draw);
    };
    draw();
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', resize); };
  }, []);

  return (
    <canvas
      ref={canvasRef}
      style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%',
        display: 'block',
      }}
    />
  );
}

// ───────────────────────── Magnetic CTA button ────────────────────────
function NavCTA({ href, children }) {
  const ref = useRef(null);
  const onMove = (e) => {
    if (!ref.current) return;
    const r = ref.current.getBoundingClientRect();
    const x = e.clientX - r.left - r.width / 2;
    const y = e.clientY - r.top - r.height / 2;
    ref.current.style.transform = `translate(${x * 0.25}px, ${y * 0.4}px)`;
  };
  const onLeave = () => {
    if (ref.current) ref.current.style.transform = 'translate(0,0)';
  };
  return (
    <a ref={ref} href={href} data-cursor="link"
       onMouseMove={onMove} onMouseLeave={onLeave}
       className="mono uppercase tracked nav-desktop nav-cta">
      <span className="nav-cta-fill" aria-hidden="true" />
      <span className="nav-cta-label">
        {children}
        <span className="nav-cta-arrow">→</span>
      </span>
    </a>
  );
}

// ─────────────────────────────── Nav ─────────────────────────────────────
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const links = [
    { label: 'Serviços', href: '#servicos' },
    { label: 'Trabalhos', href: '#trabalhos' },
    { label: 'Sobre', href: '#sobre' },
    { label: 'Contato', href: '#contato' },
  ];

  return (
    <>
      <nav style={{
        position: 'fixed', top: 0, left: 0, right: 0,
        zIndex: 100,
        padding: '20px 6vw',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: scrolled ? 'rgba(5,5,5,0.6)' : 'transparent',
        backdropFilter: scrolled ? 'blur(18px) saturate(180%)' : 'none',
        WebkitBackdropFilter: scrolled ? 'blur(18px) saturate(180%)' : 'none',
        borderBottom: scrolled ? '1px solid var(--line)' : '1px solid transparent',
        transition: 'all 0.4s cubic-bezier(.2,.8,.2,1)',
      }}>
        <a href="#hero" data-cursor="link" style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <img src="assets/logo-stund.png" alt="Stund" style={{ width: 28, height: 28, objectFit: 'contain' }} />
          <span className="mono uppercase tracked" style={{ fontSize: 11, color: 'var(--fg)' }}>STUND</span>
        </a>

        <div style={{ display: 'flex', alignItems: 'center', gap: 36 }} className="nav-desktop">
          {links.map((l, i) => (
            <a key={l.label} href={l.href} data-cursor="link"
               className="ulink mono uppercase tracked"
               style={{ fontSize: 11, color: 'var(--fg-dim)' }}>
              <span style={{ color: 'var(--accent)', marginRight: 6 }}>0{i+1}</span>
              {l.label}
            </a>
          ))}
        </div>

        <NavCTA href="#contato">Iniciar projeto</NavCTA>

        <button
          className="nav-mobile"
          data-cursor="link"
          onClick={() => setOpen(!open)}
          aria-label="Menu"
          style={{
            display: 'none',
            width: 44, height: 44,
            position: 'relative',
            zIndex: 102,
          }}>
          <span style={{
            position: 'absolute', left: 10, right: 10, top: open ? 21 : 16,
            height: 1, background: 'var(--fg)',
            transform: open ? 'rotate(45deg)' : 'none',
            transition: 'all .35s cubic-bezier(.2,.8,.2,1)',
          }}></span>
          <span style={{
            position: 'absolute', left: 10, right: 10, bottom: open ? 21 : 16,
            height: 1, background: 'var(--fg)',
            transform: open ? 'rotate(-45deg)' : 'none',
            transition: 'all .35s cubic-bezier(.2,.8,.2,1)',
          }}></span>
        </button>
      </nav>

      {/* Mobile menu */}
      <div className="mobile-menu" style={{
        position: 'fixed', inset: 0, zIndex: 101,
        background: '#050505',
        transform: open ? 'translateY(0)' : 'translateY(-100%)',
        transition: 'transform 0.6s cubic-bezier(.7,0,.3,1)',
        padding: '120px 6vw 60px',
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          {links.map((l, i) => (
            <a key={l.label} href={l.href} onClick={() => setOpen(false)}
               className="display"
               style={{ fontSize: 'clamp(48px, 12vw, 96px)', color: 'var(--fg)' }}>
              <span className="mono" style={{ fontSize: 14, color: 'var(--accent)', marginRight: 16, verticalAlign: 'top' }}>0{i+1}</span>
              {l.label}
            </a>
          ))}
        </div>
        <div className="mono uppercase tracked" style={{ fontSize: 10, color: 'var(--fg-dim)' }}>
          contato@stund.com.br · +55 11 91563-6178
        </div>
      </div>

      <style>{`
        @media (max-width: 900px) {
          .nav-desktop { display: none !important; }
          .nav-mobile { display: block !important; }
        }
      `}</style>
    </>
  );
}

// ─────────────────────────────── Hero ─────────────────────────────────────
function Hero({ heroSize, waveOn }) {
  const word = 'STUND';
  return (
    <section id="hero" className="section" style={{
      position: 'relative',
      minHeight: '100vh',
      padding: 0,
      overflow: 'hidden',
    }}>
      <HeroShader />

      {/* Vignette */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse at center, transparent 30%, rgba(5,5,5,0.7) 100%)',
        pointerEvents: 'none',
      }} />

      {/* Top label */}
      <div className="hero-top-label" style={{
        position: 'absolute', top: 110, left: '6vw',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <span className="line" style={{ width: 40, height: 1, background: 'var(--accent)' }} />
        <span className="mono uppercase tracked" style={{ fontSize: 11, color: 'var(--fg-dim)' }}>
          <span style={{ color: 'var(--accent)' }}>ESTÚDIO</span> CRIATIVO · SP / 2026
        </span>
      </div>

      {/* Center wordmark */}
      <div style={{
        position: 'absolute', inset: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexDirection: 'column',
      }}>
        <h1
          className={`display ${waveOn ? 'wave-text rgb-split' : ''}`}
          data-cursor="cross"
          style={{
            fontSize: `clamp(80px, ${heroSize/14.4}vw, ${heroSize}px)`,
            fontWeight: 600,
            letterSpacing: '-0.06em',
            color: 'var(--fg)',
            textAlign: 'center',
            lineHeight: 0.85,
            cursor: 'none',
          }}>
          {waveOn
            ? word.split('').map((c, i) => <span key={i} className="ch">{c}</span>)
            : word}
        </h1>
        <div className="hero-tags" style={{
          marginTop: 28,
          display: 'flex', gap: 24, alignItems: 'center',
        }}>
          {['FILMMAKER', 'SOCIAL', 'CRIAÇÃO'].map((w, i) => (
            <React.Fragment key={w}>
              <span className="mono uppercase tracked txt" style={{
                fontSize: 12, color: 'var(--fg)',
              }}>{w}</span>
              {i < 2 && <span style={{ width: 4, height: 4, background: 'var(--accent)', borderRadius: '50%' }} />}
            </React.Fragment>
          ))}
        </div>
      </div>

      {/* Lower-left tagline */}
      <div className="hero-bottom-tagline" style={{
        position: 'absolute', bottom: 80, left: '6vw',
        maxWidth: 320,
      }}>
        <div className="mono uppercase tracked" style={{
          fontSize: 10, color: 'var(--accent)', marginBottom: 12,
        }}>↳ MANIFESTO</div>
        <p style={{ fontSize: 16, lineHeight: 1.4, color: 'var(--fg)', fontWeight: 300 }}>
          Transformamos atenção <br />
          em resultado.
        </p>
      </div>

      {/* Scroll indicator */}
      <div className="hero-scroll-indic" style={{
        position: 'absolute', bottom: 60, right: '6vw',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12,
      }}>
        <span className="mono uppercase tracked" style={{
          fontSize: 10, color: 'var(--fg-dim)',
          writingMode: 'vertical-rl',
          transform: 'rotate(180deg)',
        }}>SCROLL</span>
        <div style={{
          width: 1, height: 60,
          background: 'linear-gradient(to bottom, var(--fg-dim) 0%, transparent 50%, var(--accent) 100%)',
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            position: 'absolute', top: 0, left: 0, right: 0, height: 20,
            background: 'var(--accent)',
            animation: 'scrollIndic 2s ease-in-out infinite',
          }} />
        </div>
      </div>
      <style>{`
        @keyframes scrollIndic {
          0% { top: -20px; opacity: 0; }
          50% { opacity: 1; }
          100% { top: 60px; opacity: 0; }
        }
      `}</style>

      {/* Time/coords corner */}
      <div className="hero-top-right" style={{
        position: 'absolute', top: 110, right: '6vw',
        textAlign: 'right',
      }}>
        <div className="mono uppercase tracked" style={{ fontSize: 10, color: 'var(--fg-dim)' }}>
          23°33′S 46°38′W
        </div>
        <div className="mono uppercase tracked" style={{ fontSize: 10, color: 'var(--accent)', marginTop: 4 }}>
          ● LIVE
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, Hero, HeroShader });
