import { useMemo, useState, useEffect } from 'react'
import {
  PINCER_AXES,
  ISRAEL_LEBANON_AXIS,
  KURDISH_ATTACK_DEFENSE_LINE,
} from '@/data/extendedWarData'
import { createTacticalPincerAtProgress } from '@/utils/tacticalPincerArrow'
import { createCurvedDefensePath, createDefenseLine } from '@/utils/defenseLine'

export type PincerAxis = { start: [number, number]; end: [number, number]; name: string }
export type IsraelLebanonAxis = { start: [number, number]; end: [number, number]; name: string }

export type WarMapConfig = {
  pincerAxes: PincerAxis[]
  israelLebanonAxis: IsraelLebanonAxis
  defenseLinePath: [number, number][]
}

const DEFAULT_CONFIG: WarMapConfig = {
  pincerAxes: [...PINCER_AXES],
  israelLebanonAxis: { ...ISRAEL_LEBANON_AXIS },
  defenseLinePath: KURDISH_ATTACK_DEFENSE_LINE.geometry.coordinates as [number, number][],
}

export type WarMapData = WarMapConfig & {
  kurdishPincerGrowthInitial: GeoJSON.FeatureCollection
  israelLebanonArrowInitial: GeoJSON.FeatureCollection
  kurdishDefenseLineGeoJson: GeoJSON.FeatureCollection
}

function buildGeoJsonFromConfig(config: WarMapConfig): Omit<WarMapData, keyof WarMapConfig> {
  const kurdishPincerGrowthInitial: GeoJSON.FeatureCollection = {
    type: 'FeatureCollection',
    features: config.pincerAxes.map((axis) => ({
      type: 'Feature',
      properties: { name: axis.name },
      geometry: {
        type: 'Polygon',
        coordinates: [createTacticalPincerAtProgress(axis.start, axis.end, 0)],
      },
    })),
  }
  const israelLebanonArrowInitial: GeoJSON.FeatureCollection = {
    type: 'FeatureCollection',
    features: [{
      type: 'Feature',
      properties: { name: config.israelLebanonAxis.name },
      geometry: {
        type: 'Polygon',
        coordinates: [createTacticalPincerAtProgress(
          config.israelLebanonAxis.start,
          config.israelLebanonAxis.end,
          0
        )],
      },
    }],
  }
  const curvedPath = createCurvedDefensePath(config.defenseLinePath, 0.35, 24)
  const lineCoords = createDefenseLine(curvedPath, 0.18, 0.08)
  // 整体防御线方向：用锯齿线起点与终点的连线方向
  const startPoint = lineCoords[0]
  const endPoint = lineCoords[lineCoords.length - 1]
  const dx = endPoint[0] - startPoint[0]
  const dy = endPoint[1] - startPoint[1]
  const tangentAngle = Math.atan2(dy, dx)
  const normalAngle = tangentAngle + Math.PI / 2
  let angleDeg = (normalAngle * 180) / Math.PI
  angleDeg = ((angleDeg + 540) % 360) - 180 // 归一到 [-180, 180]
  // 标注点放在整条防御线（锯齿线）中点
  const labelIndex = Math.floor(lineCoords.length / 2)
  const labelPoint = lineCoords[labelIndex]
  const name = '伊朗西部防御线'
  const kurdishDefenseLineGeoJson: GeoJSON.FeatureCollection = {
    type: 'FeatureCollection',
    features: [
      { type: 'Feature', properties: { name }, geometry: { type: 'LineString', coordinates: lineCoords } },
      { type: 'Feature', properties: { name, angle: angleDeg }, geometry: { type: 'Point', coordinates: labelPoint } },
    ],
  }
  return { kurdishPincerGrowthInitial, israelLebanonArrowInitial, kurdishDefenseLineGeoJson }
}

/** 封装地图轴线、防御线及派生 GeoJSON，可从 API 加载后落库，方便后续直接调用 */
export function useWarMapData(): WarMapData {
  const [config, setConfig] = useState<WarMapConfig>(DEFAULT_CONFIG)

  useEffect(() => {
    let cancelled = false
    fetch('/api/war-map-config', { cache: 'no-store' })
      .then((res) => (res.ok ? res.json() : null))
      .then((data: WarMapConfig | null) => {
        if (cancelled || !data) return
        if (Array.isArray(data.pincerAxes) && data.pincerAxes.length > 0 && data.israelLebanonAxis && Array.isArray(data.defenseLinePath)) {
          setConfig({
            pincerAxes: data.pincerAxes,
            israelLebanonAxis: data.israelLebanonAxis,
            defenseLinePath: data.defenseLinePath,
          })
        }
      })
      .catch(() => {})
    return () => { cancelled = true }
  }, [])

  return useMemo(() => {
    const built = buildGeoJsonFromConfig(config)
    return { ...config, ...built }
  }, [config])
}
