"use client";

import React, { useEffect, useRef } from 'react';

const Snowflakes = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    // Definir tamanho do canvas
    const resizeCanvas = () => {
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
    };

    window.addEventListener('resize', resizeCanvas);
    resizeCanvas();

    class Snowflake {
      x: number;
      y: number;
      radius: number;
      speed: number;
      wind: number;
      opacity: number;

      constructor() {
        this.x = Math.random() * canvas.width;
        this.y = Math.random() * -canvas.height;
        this.radius = Math.random() * 3 + 1;
        this.speed = Math.random() * 3 + 1;
        this.wind = Math.random() * 0.5 - 0.25;
        this.opacity = Math.random() * 0.5 + 0.5;
      }

      update() {
        this.y += this.speed;
        this.x += this.wind;

        // Adicionar um movimento oscilante
        this.x += Math.sin(this.y * 0.01) * 0.5;

        // Reiniciar quando sair da tela
        if (this.y > canvas.height) {
          this.y = Math.random() * -100;
          this.x = Math.random() * canvas.width;
        }

        // Se sair da tela lateralmente, trazer de volta
        if (this.x < 0) this.x = canvas.width;
        if (this.x > canvas.width) this.x = 0;
      }

      draw(ctx: CanvasRenderingContext2D) {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(255, 255, 255, ${this.opacity})`;
        ctx.fill();
      }
    }

    // Criar um número razoável de flocos de neve
    const snowflakes: Snowflake[] = [];
    const snowflakeCount = Math.min(100, Math.floor(window.innerWidth / 15));

    for (let i = 0; i < snowflakeCount; i++) {
      snowflakes.push(new Snowflake());
    }

    const update = () => {
      if (!canvas) return;

      // Limpar o canvas
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // Atualizar e desenhar flocos de neve
      snowflakes.forEach(snowflake => {
        snowflake.update();
        snowflake.draw(ctx);
      });

      // Continuar animação
      requestAnimationFrame(update);
    };

    // Iniciar animação
    requestAnimationFrame(update);

    // Limpeza ao desmontar
    return () => window.removeEventListener('resize', resizeCanvas);
  }, []);

  return (
    <canvas
      ref={canvasRef}
      className="fixed top-0 left-0 w-full h-full pointer-events-none z-10"
    />
  );
};

export default Snowflakes;
