'use client'

import { useRef, useMemo, useEffect } from 'react'
import { useFrame } from '@react-three/fiber'
import * as THREE from 'three'

function createPitchTexture(): THREE.CanvasTexture {
  const canvas = document.createElement('canvas')
  canvas.width = 1024
  canvas.height = 680
  const ctx = canvas.getContext('2d')!

  // Grass alternating stripes
  for (let i = 0; i < 10; i++) {
    ctx.fillStyle = i % 2 === 0 ? '#0d2e0d' : '#102e10'
    ctx.fillRect(i * 102.4, 0, 102.4, 680)
  }

  ctx.strokeStyle = 'rgba(255,255,255,0.7)'
  ctx.lineWidth = 3
  ctx.lineCap = 'round'

  // Outer boundary
  ctx.strokeRect(50, 50, 924, 580)

  // Center line
  ctx.beginPath()
  ctx.moveTo(512, 50)
  ctx.lineTo(512, 630)
  ctx.stroke()

  // Center circle
  ctx.beginPath()
  ctx.arc(512, 340, 80, 0, Math.PI * 2)
  ctx.stroke()

  // Center dot
  ctx.fillStyle = 'rgba(255,255,255,0.9)'
  ctx.beginPath()
  ctx.arc(512, 340, 5, 0, Math.PI * 2)
  ctx.fill()

  // Penalty areas
  const penaltyAreas: [number,number,number,number][] = [[50, 200, 160, 280], [814, 200, 160, 280]]
  penaltyAreas.forEach(([x, y, w, h]) => ctx.strokeRect(x, y, w, h))

  // Goal areas
  const goalAreas: [number,number,number,number][] = [[50, 270, 60, 140], [914, 270, 60, 140]]
  goalAreas.forEach(([x, y, w, h]) => ctx.strokeRect(x, y, w, h))

  // Penalty spots
  const penaltySpots: [number,number][] = [[210, 340], [814, 340]]
  penaltySpots.forEach(([x, y]) => {
    ctx.beginPath()
    ctx.arc(x, y, 5, 0, Math.PI * 2)
    ctx.fillStyle = 'rgba(255,255,255,0.9)'
    ctx.fill()
  })

  // Penalty arcs
  ctx.beginPath()
  ctx.arc(210, 340, 80, -0.9, 0.9)
  ctx.stroke()
  ctx.beginPath()
  ctx.arc(814, 340, 80, Math.PI - 0.9, Math.PI + 0.9)
  ctx.stroke()

  return new THREE.CanvasTexture(canvas)
}

function createHeatmapTexture(): THREE.CanvasTexture {
  const canvas = document.createElement('canvas')
  canvas.width = 512
  canvas.height = 340
  const ctx = canvas.getContext('2d')!

  // Baturina's heatmap zones: left wing, attacking mid, edge of box
  const hotspots = [
    { x: 360, y: 120, r: 80, intensity: 0.7 },   // Left wing attacking third
    { x: 320, y: 170, r: 70, intensity: 0.9 },   // Attacking midfield center
    { x: 380, y: 200, r: 60, intensity: 0.8 },   // Edge of right penalty area
    { x: 290, y: 150, r: 50, intensity: 0.6 },   // Left half-space
    { x: 420, y: 160, r: 40, intensity: 0.5 },   // Right wing entry
  ]

  hotspots.forEach(({ x, y, r, intensity }) => {
    const grad = ctx.createRadialGradient(x, y, 0, x, y, r)
    grad.addColorStop(0, `rgba(0, 229, 255, ${intensity})`)
    grad.addColorStop(0.4, `rgba(0, 68, 255, ${intensity * 0.5})`)
    grad.addColorStop(1, 'rgba(0, 0, 255, 0)')
    ctx.fillStyle = grad
    ctx.fillRect(0, 0, 512, 340)
  })

  return new THREE.CanvasTexture(canvas)
}

export function StatsField() {
  const heatmapRef = useRef<THREE.Mesh>(null)
  const pitchTexture = useMemo(() => createPitchTexture(), [])
  const heatmapTexture = useMemo(() => createHeatmapTexture(), [])
  const heatOpacityRef = useRef(0)

  useEffect(() => {
    let t = 0
    const interval = setInterval(() => {
      t += 0.03
      heatOpacityRef.current = Math.min(t, 0.7)
      if (t >= 0.7) clearInterval(interval)
    }, 50)
    return () => clearInterval(interval)
  }, [])

  useFrame((state) => {
    if (heatmapRef.current) {
      const mat = heatmapRef.current.material as THREE.MeshBasicMaterial
      mat.opacity = heatOpacityRef.current
    }

    // Camera slowly zooms in
    const cam = state.camera
    const targetY = 6 - Math.min(state.clock.elapsedTime * 0.15, 2)
    cam.position.y += (targetY - cam.position.y) * 0.02
    cam.lookAt(0, 0, 0)
  })

  return (
    <>
      <color attach="background" args={['#020209']} />
      <ambientLight intensity={0.4} />
      <directionalLight position={[3, 8, 2]} intensity={1} color="#ffffff" castShadow />
      <pointLight position={[0, 3, 0]} intensity={0.5} color="#0044FF" />

      {/* Pitch */}
      <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0, 0]} receiveShadow>
        <planeGeometry args={[12, 8]} />
        <meshStandardMaterial map={pitchTexture} roughness={0.9} metalness={0} />
      </mesh>

      {/* Heatmap overlay */}
      <mesh ref={heatmapRef} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.01, 0]}>
        <planeGeometry args={[12, 8]} />
        <meshBasicMaterial
          map={heatmapTexture}
          transparent
          opacity={0}
          blending={THREE.AdditiveBlending}
          depthWrite={false}
        />
      </mesh>

      {/* Ball marker at Baturina's position */}
      <mesh position={[1.5, 0.05, -0.5]}>
        <sphereGeometry args={[0.12, 8, 8]} />
        <meshStandardMaterial color="#00E5FF" emissive="#00E5FF" emissiveIntensity={1} />
      </mesh>
    </>
  )
}
