import { useEffect, useState } from 'react'
import { Source, Layer } from '@vis.gl/react-maplibre'
import type { OceanForecastData } from '../services/khoaApi'

interface OceanForecastOverlayProps {
  forecast: OceanForecastData | null
  opacity?: number
  visible?: boolean
}

// 한국 해역 범위 (MapLibre image source용 좌표 배열)
// [left, bottom, right, top] → MapLibre coordinates 순서: [sw, nw, ne, se]
// [lon, lat] 순서
const KOREA_IMAGE_COORDINATES: [[number, number], [number, number], [number, number], [number, number]] = [
  [124.5, 33.0],  // 남서 (제주 남쪽)
  [124.5, 38.5],  // 북서
  [132.0, 38.5],  // 북동 (동해 북쪽)
  [132.0, 33.0],  // 남동
]

/**
 * OceanForecastOverlay
 *
 * 기존: react-leaflet ImageOverlay + LatLngBounds
 * 전환: @vis.gl/react-maplibre Source(type=image) + Layer(type=raster)
 *
 * MapLibre image source는 Map 컴포넌트 자식으로 직접 렌더링 가능
 */
export function OceanForecastOverlay({
  forecast,
  opacity = 0.6,
  visible = true,
}: OceanForecastOverlayProps) {
  const [loadedUrl, setLoadedUrl] = useState<string | null>(null)

  useEffect(() => {
    if (!forecast?.filePath) return
    let cancelled = false
    const img = new Image()
    img.onload = () => { if (!cancelled) setLoadedUrl(forecast.filePath) }
    img.onerror = () => { if (!cancelled) setLoadedUrl(null) }
    img.src = forecast.filePath
    return () => { cancelled = true }
  }, [forecast?.filePath])

  const imageLoaded = !!loadedUrl && loadedUrl === forecast?.filePath

  if (!visible || !forecast || !imageLoaded) {
    return null
  }

  return (
    <Source
      id="ocean-forecast-image"
      type="image"
      url={forecast.filePath}
      coordinates={KOREA_IMAGE_COORDINATES}
    >
      <Layer
        id="ocean-forecast-raster"
        type="raster"
        paint={{
          'raster-opacity': opacity,
          'raster-resampling': 'linear',
        }}
      />
    </Source>
  )
}
