/* global React */
const { useState, useEffect, useRef } = React;

// ============ Starfield (shared background) ============
function Starfield() {
  const ref = useRef(null);
  useEffect(() => {
    const canvas = ref.current;
    const ctx = canvas.getContext('2d');
    let w, h, stars = [];
    const count = 260;
    const colors = ['#00F0FF', '#FF51FA', '#ffffff'];
    const mouse = { x: -9999, y: -9999 };
    const AVOID = 150;
    class Star {
      constructor() { this.init(); }
      init() {
        this.bx = Math.random() * w; this.by = Math.random() * h;
        this.x = this.bx; this.y = this.by;
        this.size = Math.random() * 2 + 0.5;
        this.c = colors[Math.floor(Math.random() * 3)];
        this.vx = (Math.random() - 0.5) * 0.2; this.vy = (Math.random() - 0.5) * 0.2;
        this.op = Math.random() * 0.5 + 0.2;
        this.pd = Math.random() > 0.5 ? 1 : -1;
        this.ps = Math.random() * 0.01 + 0.005;
      }
      upd() {
        this.bx += this.vx; this.by += this.vy;
        if (this.bx < 0) this.bx = w; if (this.bx > w) this.bx = 0;
        if (this.by < 0) this.by = h; if (this.by > h) this.by = 0;
        const dx = this.bx - mouse.x, dy = this.by - mouse.y;
        const d = Math.hypot(dx, dy);
        let tx = this.bx, ty = this.by;
        if (d < AVOID) {
          const a = Math.atan2(dy, dx), f = (AVOID - d) / AVOID;
          tx += Math.cos(a) * f * 100; ty += Math.sin(a) * f * 100;
        }
        this.x += (tx - this.x) * 0.15; this.y += (ty - this.y) * 0.15;
        this.op += this.ps * this.pd;
        if (this.op > 0.8 || this.op < 0.1) this.pd *= -1;
      }
      draw() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fillStyle = this.c; ctx.globalAlpha = this.op;
        if (this.c !== '#ffffff') { ctx.shadowBlur = 10; ctx.shadowColor = this.c; } else { ctx.shadowBlur = 0; }
        ctx.fill();
      }
    }
    function resize() {
      w = window.innerWidth; h = window.innerHeight;
      canvas.width = w; canvas.height = h;
      stars.forEach(s => s.init());
    }
    w = window.innerWidth; h = window.innerHeight;
    canvas.width = w; canvas.height = h;
    for (let i = 0; i < count; i++) stars.push(new Star());
    let raf;
    function loop() { ctx.clearRect(0, 0, w, h); stars.forEach(s => { s.upd(); s.draw(); }); raf = requestAnimationFrame(loop); }
    loop();
    const mm = (e) => { mouse.x = e.clientX; mouse.y = e.clientY; };
    const mo = () => { mouse.x = -9999; mouse.y = -9999; };
    window.addEventListener('resize', resize);
    window.addEventListener('mousemove', mm);
    window.addEventListener('mouseout', mo);
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', resize); window.removeEventListener('mousemove', mm); window.removeEventListener('mouseout', mo); };
  }, []);
  return React.createElement('canvas', { ref, style: { position: 'fixed', inset: 0, width: '100vw', height: '100vh', zIndex: -1, pointerEvents: 'none', background: 'radial-gradient(circle at center, #121820 0%, #0a0e14 100%)' } });
}

// ============ Top Nav ============
function TopNav({ active = 'services', onNav }) {
  const items = [['services', 'Services'], ['portfolio', 'Portfolio'], ['contact', 'Contact']];
  return (
    <nav style={{ position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50, background: 'rgba(10,14,20,0.8)', backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)', boxShadow: '0 8px 32px rgba(0,0,0,0.36)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 32px', maxWidth: 1280, margin: '0 auto' }}>
        <a href="#" onClick={(e) => { e.preventDefault(); onNav && onNav('home'); }} style={{ display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none' }}>
          <img src="assets/logo-raccoon.jpg" alt="ClawdWorks" style={{ width: 40, height: 40, borderRadius: 10, objectFit: 'cover', boxShadow: '0 0 16px rgba(255,81,250,0.45)' }} />
          <span style={{ fontSize: 22, fontWeight: 900, letterSpacing: '-0.04em', color: '#FF51FA', textShadow: '0 0 10px rgba(255,81,250,0.55)' }}>CLAWDWORKS</span>
        </a>
        <div style={{ display: 'flex', gap: 32, fontSize: 14, fontWeight: 500 }}>
          {items.map(([k, label]) => (
            <a key={k} href={`#${k}`} onClick={(e) => { e.preventDefault(); onNav && onNav(k); }}
              style={{ color: active === k ? '#FF51FA' : '#a8abb3', borderBottom: active === k ? '2px solid #FF51FA' : 'none', paddingBottom: 4, textDecoration: 'none', transition: 'color 200ms' }}>
              {label}
            </a>
          ))}
        </div>
        <a href="#contact" onClick={(e) => { e.preventDefault(); onNav && onNav('contact'); }}
          style={{ background: 'linear-gradient(to right, #FF51FA, #e645e0)', color: '#fff', padding: '8px 22px', borderRadius: 999, fontWeight: 800, fontSize: 13, textDecoration: 'none', whiteSpace: 'nowrap', transition: 'transform 200ms, box-shadow 200ms', boxShadow: '0 0 20px rgba(255,81,250,0.35)' }}
          onMouseOver={e => { e.currentTarget.style.transform = 'scale(1.05)'; e.currentTarget.style.boxShadow = '0 0 28px rgba(255,81,250,0.55)'; }}
          onMouseOut={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = '0 0 20px rgba(255,81,250,0.35)'; }}>
          Get Started
        </a>
      </div>
    </nav>
  );
}

// ============ Button ============
function Btn({ variant = 'primary', icon, children, onClick, href }) {
  const base = { display: 'inline-flex', alignItems: 'center', gap: 8, padding: '14px 28px', borderRadius: 999, fontWeight: 700, fontSize: 17, textDecoration: 'none', border: 0, cursor: 'pointer', transition: 'all 300ms ease', fontFamily: 'Plus Jakarta Sans, sans-serif' };
  const styles = {
    primary: { ...base, background: '#FF51FA', color: '#fff', boxShadow: '0 0 20px rgba(255,81,250,0.3)' },
    secondary: { ...base, background: '#00F0FF', color: '#0a0e14' },
    gradient: { ...base, background: 'linear-gradient(to right,#FF51FA,#00F0FF)', color: '#0a0e14' },
    outline: { ...base, background: 'rgba(32,38,47,0.4)', backdropFilter: 'blur(12px)', color: '#f1f3fc', border: '1px solid rgba(68,72,79,0.4)' }
  };
  const hoverGlow = {
    primary: '0 0 40px rgba(255,81,250,0.6)',
    secondary: '0 0 30px rgba(143,245,255,0.4)',
    gradient: '0 0 30px rgba(255,81,250,0.5)',
    outline: '0 0 30px rgba(255,81,250,0.4)'
  };
  const restShadow = { primary: '0 0 20px rgba(255,81,250,0.3)', secondary: 'none', gradient: 'none', outline: 'none' };
  const Tag = href ? 'a' : 'button';
  return (
    <Tag href={href} onClick={onClick} style={styles[variant]}
      onMouseOver={e => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = hoverGlow[variant]; if (variant === 'outline') e.currentTarget.style.borderColor = '#FF51FA'; }}
      onMouseOut={e => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = restShadow[variant]; if (variant === 'outline') e.currentTarget.style.borderColor = 'rgba(68,72,79,0.4)'; }}
      onMouseDown={e => e.currentTarget.style.transform = 'scale(0.95)'}
      onMouseUp={e => e.currentTarget.style.transform = 'translateY(-2px)'}>
      {children}
      {icon && <span className="material-symbols-outlined" style={{ fontSize: 20 }}>{icon}</span>}
    </Tag>
  );
}

// ============ Glass Card ============
function GlassCard({ children, style, glow = 'magenta', hover = true, ...rest }) {
  const [h, setH] = useState(false);
  const glowColor = glow === 'cyan' ? 'rgba(0,240,255,0.3)' : 'rgba(255,81,250,0.35)';
  const borderHover = glow === 'cyan' ? 'rgba(0,240,255,0.3)' : 'rgba(255,81,250,0.4)';
  return (
    <div {...rest}
      style={{
        background: 'rgba(32,38,47,0.4)', backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)',
        border: `1px solid ${h && hover ? borderHover : 'rgba(68,72,79,0.15)'}`,
        borderRadius: 16, padding: 32, transition: 'all 300ms ease',
        transform: h && hover ? 'translateY(-8px)' : 'translateY(0)',
        boxShadow: h && hover ? `0 0 30px ${glowColor}` : 'none',
        ...style
      }}
      onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}>
      {children}
    </div>
  );
}

Object.assign(window, { Starfield, TopNav, Btn, GlassCard });
