'use client'
import { useThemeMode } from '@/hooks/useThemeMode'
import { useEffect, useRef } from 'react'

const PARTICLE_COUNT = 120

interface Particle {
  x: number
  y: number
  r: number
  vx: number
  vy: number
  alpha: number
  phase: number
  twinkleSpeed: number
}

function initParticles(W: number, H: number): Particle[] {
  return Array.from({ length: PARTICLE_COUNT }, () => ({
    x: Math.random() * W,
    y: Math.random() * H,
    r: 0.5 + Math.random() * 2.0,
    vx: (Math.random() - 0.5) * 0.25,
    vy: (Math.random() - 0.5) * 0.15,
    alpha: 0.15 + Math.random() * 0.35,
    phase: Math.random() * Math.PI * 2,
    twinkleSpeed: 0.4 + Math.random() * 1.2,
  }))
}

function drawParticles(
  ctx: CanvasRenderingContext2D,
  particles: Particle[],
  W: number,
  H: number,
  isDark: boolean,
) {
  const now = Date.now() / 1000
  const tone = isDark ? 220 : 140

  for (const p of particles) {
    p.x += p.vx
    p.y += p.vy
    if (p.x < 0) p.x = W
    if (p.x > W) p.x = 0
    if (p.y < 0) p.y = H
    if (p.y > H) p.y = 0

    const twinkle = 0.4 + 0.6 * ((Math.sin(now * p.twinkleSpeed + p.phase) + 1) / 2)
    ctx.beginPath()
    ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2)
    ctx.fillStyle = `rgba(${tone},${tone},${tone},${p.alpha * twinkle})`
    ctx.fill()
  }
}

interface HeroBackgroundProps {
  isDark?: boolean
  onToggle?: (isDark: boolean) => void
  showToggle?: boolean
}

export default function HeroBackground({
  isDark: externalIsDark,
  onToggle,
  showToggle = true,
}: HeroBackgroundProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const { isDark: hookDark, toggle } = useThemeMode()
  const isDark = externalIsDark !== undefined ? externalIsDark : hookDark

  function handleToggle() {
    toggle()
    onToggle?.(!isDark)
  }

  const darkRef = useRef(isDark)
  useEffect(() => {
    darkRef.current = isDark
  }, [isDark])

  useEffect(() => {
    const canvas = canvasRef.current
    if (!canvas) return
    const ctx = canvas.getContext('2d')
    if (!ctx) return

    let W = 0,
      H = 0
    let particles: Particle[] = []
    let rafId: number
    let bgR = 0

    function resize() {
      W = canvas!.width = canvas!.offsetWidth
      H = canvas!.height = canvas!.offsetHeight
      particles = initParticles(W, H)
    }

    function loop() {
      const dark = darkRef.current
      const targetBg = dark ? 0 : 255
      bgR += (targetBg - bgR) * 0.04

      const bg = Math.round(bgR)
      ctx!.fillStyle = `rgb(${bg},${bg},${bg})`
      ctx!.fillRect(0, 0, W, H)

      drawParticles(ctx!, particles, W, H, dark)

      rafId = requestAnimationFrame(loop)
    }

    const ro = new ResizeObserver(resize)
    ro.observe(canvas)
    resize()
    rafId = requestAnimationFrame(loop)

    return () => {
      cancelAnimationFrame(rafId)
      ro.disconnect()
    }
  }, [])

  // grid line color: light grey at 50% opacity in dark, dark grey at 50% opacity in light
  const gridColor = isDark ? 'rgba(200,200,200,0.07)' : 'rgba(60,60,60,0.07)'

  return (
    <div style={{ position: 'relative', width: '100%', height: '100%' }}>
      <canvas ref={canvasRef} style={{ display: 'block', width: '100%', height: '100%' }} />

      {/* Grid overlay */}
      <div
        aria-hidden="true"
        style={{
          position: 'absolute',
          inset: 0,
          backgroundImage: `linear-gradient(to right, ${gridColor} 1px, transparent 1px),
                            linear-gradient(to bottom, ${gridColor} 1px, transparent 1px)`,
          backgroundSize: '100px 100px',
          pointerEvents: 'none',
        }}
      />

      {showToggle && (
        <button
          onClick={handleToggle}
          style={{
            position: 'absolute',
            top: 20,
            right: 20,
            display: 'flex',
            alignItems: 'center',
            gap: 8,
            padding: '8px 16px',
            fontSize: 13,
            cursor: 'pointer',
            borderRadius: 999,
            border: `1px solid ${isDark ? 'rgba(255,255,255,0.2)' : 'rgba(0,0,0,0.18)'}`,
            background: isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.07)',
            color: isDark ? '#fff' : '#111',
            transition: 'background 0.4s, color 0.4s, border-color 0.4s',
          }}
        >
          {isDark ? '☀' : '☾'} {isDark ? 'Light mode' : 'Dark mode'}
        </button>
      )}
    </div>
  )
}
