import React, { useEffect, useRef, useState } from 'react';
import './HeroVideo.css';

export default function HeroVideo() {
  const canvasRef = useRef(null);
  const [isPlaying, setIsPlaying] = useState(true);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    let animationId;
    let particles = [];
    let connections = [];
    let time = 0;

    const resize = () => {
      canvas.width = canvas.offsetWidth * window.devicePixelRatio;
      canvas.height = canvas.offsetHeight * window.devicePixelRatio;
      ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
    };

    const colors = {
      foundation: '#ff0000',
      corporation: '#0066ff',
      labs: '#ffa500'
    };

    class Particle {
      constructor() {
        this.reset();
      }

      reset() {
        this.x = Math.random() * canvas.offsetWidth;
        this.y = Math.random() * canvas.offsetHeight;
        this.vx = (Math.random() - 0.5) * 0.5;
        this.vy = (Math.random() - 0.5) * 0.5;
        this.radius = Math.random() * 2 + 1;
        this.color = Object.values(colors)[Math.floor(Math.random() * 3)];
        this.alpha = Math.random() * 0.5 + 0.3;
        this.pulse = Math.random() * Math.PI * 2;
      }

      update() {
        this.x += this.vx;
        this.y += this.vy;
        this.pulse += 0.02;

        if (this.x < 0 || this.x > canvas.offsetWidth) this.vx *= -1;
        if (this.y < 0 || this.y > canvas.offsetHeight) this.vy *= -1;
      }

      draw() {
        const pulseRadius = this.radius + Math.sin(this.pulse) * 0.5;
        ctx.beginPath();
        ctx.arc(this.x, this.y, pulseRadius, 0, Math.PI * 2);
        ctx.fillStyle = this.color;
        ctx.globalAlpha = this.alpha;
        ctx.fill();
        
        // Glow effect
        ctx.beginPath();
        ctx.arc(this.x, this.y, pulseRadius * 3, 0, Math.PI * 2);
        const gradient = ctx.createRadialGradient(
          this.x, this.y, 0,
          this.x, this.y, pulseRadius * 3
        );
        gradient.addColorStop(0, this.color + '40');
        gradient.addColorStop(1, 'transparent');
        ctx.fillStyle = gradient;
        ctx.fill();
        ctx.globalAlpha = 1;
      }
    }

    class Diamond {
      constructor(x, y, size) {
        this.x = x;
        this.y = y;
        this.size = size;
        this.rotation = 0;
        this.pulsePhase = 0;
      }

      update() {
        this.rotation += 0.005;
        this.pulsePhase += 0.03;
      }

      draw() {
        const pulse = 1 + Math.sin(this.pulsePhase) * 0.05;
        const s = this.size * pulse;
        
        ctx.save();
        ctx.translate(this.x, this.y);
        ctx.rotate(this.rotation);

        // Outer diamond
        ctx.beginPath();
        ctx.moveTo(0, -s);
        ctx.lineTo(s, 0);
        ctx.lineTo(0, s);
        ctx.lineTo(-s, 0);
        ctx.closePath();

        const gradient = ctx.createLinearGradient(-s, -s, s, s);
        gradient.addColorStop(0, colors.foundation);
        gradient.addColorStop(0.5, colors.corporation);
        gradient.addColorStop(1, colors.labs);

        ctx.strokeStyle = gradient;
        ctx.lineWidth = 2;
        ctx.stroke();

        // Inner glow
        ctx.beginPath();
        ctx.arc(0, 0, s * 0.3, 0, Math.PI * 2);
        const coreGradient = ctx.createRadialGradient(0, 0, 0, 0, 0, s * 0.3);
        coreGradient.addColorStop(0, 'rgba(255, 255, 255, 0.8)');
        coreGradient.addColorStop(0.5, 'rgba(255, 100, 50, 0.3)');
        coreGradient.addColorStop(1, 'transparent');
        ctx.fillStyle = coreGradient;
        ctx.fill();

        ctx.restore();
      }
    }

    const init = () => {
      resize();
      particles = [];
      const particleCount = Math.min(80, Math.floor((canvas.offsetWidth * canvas.offsetHeight) / 10000));
      
      for (let i = 0; i < particleCount; i++) {
        particles.push(new Particle());
      }
    };

    const drawConnections = () => {
      const maxDist = 150;
      
      for (let i = 0; i < particles.length; i++) {
        for (let j = i + 1; j < particles.length; j++) {
          const dx = particles[i].x - particles[j].x;
          const dy = particles[i].y - particles[j].y;
          const dist = Math.sqrt(dx * dx + dy * dy);

          if (dist < maxDist) {
            const alpha = (1 - dist / maxDist) * 0.2;
            ctx.beginPath();
            ctx.moveTo(particles[i].x, particles[i].y);
            ctx.lineTo(particles[j].x, particles[j].y);
            ctx.strokeStyle = `rgba(255, 255, 255, ${alpha})`;
            ctx.lineWidth = 0.5;
            ctx.stroke();
          }
        }
      }
    };

    const drawGrid = () => {
      const gridSize = 60;
      ctx.strokeStyle = 'rgba(255, 255, 255, 0.02)';
      ctx.lineWidth = 1;

      for (let x = 0; x < canvas.offsetWidth; x += gridSize) {
        ctx.beginPath();
        ctx.moveTo(x, 0);
        ctx.lineTo(x, canvas.offsetHeight);
        ctx.stroke();
      }

      for (let y = 0; y < canvas.offsetHeight; y += gridSize) {
        ctx.beginPath();
        ctx.moveTo(0, y);
        ctx.lineTo(canvas.offsetWidth, y);
        ctx.stroke();
      }
    };

    const drawScanline = () => {
      const y = (time * 50) % (canvas.offsetHeight + 100) - 50;
      const gradient = ctx.createLinearGradient(0, y - 50, 0, y + 50);
      gradient.addColorStop(0, 'transparent');
      gradient.addColorStop(0.5, 'rgba(255, 100, 50, 0.1)');
      gradient.addColorStop(1, 'transparent');
      
      ctx.fillStyle = gradient;
      ctx.fillRect(0, y - 50, canvas.offsetWidth, 100);
    };

    const centralDiamond = new Diamond(
      canvas.offsetWidth / 2,
      canvas.offsetHeight / 2,
      80
    );

    const animate = () => {
      if (!isPlaying) return;
      
      ctx.fillStyle = 'rgba(10, 10, 10, 0.1)';
      ctx.fillRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);

      drawGrid();
      drawScanline();

      particles.forEach(p => {
        p.update();
        p.draw();
      });

      drawConnections();
      
      centralDiamond.x = canvas.offsetWidth / 2;
      centralDiamond.y = canvas.offsetHeight / 2;
      centralDiamond.update();
      centralDiamond.draw();

      time += 0.016;
      animationId = requestAnimationFrame(animate);
    };

    init();
    animate();

    window.addEventListener('resize', () => {
      init();
    });

    return () => {
      cancelAnimationFrame(animationId);
      window.removeEventListener('resize', init);
    };
  }, [isPlaying]);

  return (
    <div className="hero-video-container">
      <canvas ref={canvasRef} className="hero-video-canvas" />
      <div className="hero-video-overlay" />
      <button 
        className="hero-video-toggle"
        onClick={() => setIsPlaying(!isPlaying)}
        aria-label={isPlaying ? 'Pause animation' : 'Play animation'}
      >
        {isPlaying ? '⏸' : '▶'}
      </button>
    </div>
  );
}
