'use client'

import { useEffect, useRef } from 'react'

export default function SnowEffect() {
  const canvasRef = useRef(null)

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

    const ctx = canvas.getContext('2d')
    let animationFrameId
    let snowflakes = []

    // resizeCanvas
    const resizeCanvas = () => {
      canvas.width = window.innerWidth
      canvas.height = window.innerHeight
    }

    // createSnowflakes
    const createSnowflakes = () => {
      const count = Math.floor((canvas.width * canvas.height) / 15000)
      snowflakes = []
      
      for (let i = 0; i < count; i++) {
        snowflakes.push({
          x: Math.random() * canvas.width,
          y: Math.random() * canvas.height,
          radius: Math.random() * 2 + 1,
          speed: Math.random() * 0.5 + 0.2,
          drift: Math.random() * 0.5 - 0.25,
        })
      }
    }

    // animate
    const animate = () => {
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.fillStyle = 'rgba(255, 255, 255, 0.25)'
      ctx.beginPath()

      for (let flake of snowflakes) {
        ctx.moveTo(flake.x, flake.y)
        ctx.arc(flake.x, flake.y, flake.radius, 0, Math.PI * 2)
        
        flake.y += flake.speed
        flake.x += flake.drift
        
        if (flake.y > canvas.height) {
          flake.y = 0
          flake.x = Math.random() * canvas.width
        }
        
        if (flake.x > canvas.width) {
          flake.x = 0
        } else if (flake.x < 0) {
          flake.x = canvas.width
        }
      }

      ctx.fill()
      animationFrameId = requestAnimationFrame(animate)
    }

    resizeCanvas()
    createSnowflakes()
    animate()

    window.addEventListener('resize', () => {
      resizeCanvas()
      createSnowflakes()
    })

    return () => {
      cancelAnimationFrame(animationFrameId)
      window.removeEventListener('resize', resizeCanvas)
    }
  }, [])

  return (
    <canvas
      ref={canvasRef}
      className="fixed inset-0 pointer-events-none"
      style={{ zIndex: 1 }}
    />
  )
}
