'use client'

import { useState } from 'react'
import { Wind, X } from 'lucide-react'

interface MapCompassProps {
  /** Karten-Bearing in Grad (0 = Norden oben) */
  bearing: number
  /** Windrichtung meteorologisch „Wind aus" in Grad, oder null */
  windDirection: number | null | undefined
  canEdit: boolean
  onWindChange: (dir: number | null) => void
}

const DIRS = ['N', 'NO', 'O', 'SO', 'S', 'SW', 'W', 'NW']

export function degToCompass(deg: number): string {
  return DIRS[Math.round(((deg % 360) + 360) % 360 / 45) % 8]
}

// 8-Richtungs-Auswahl (Grad, meteorologisch „aus")
const WIND_OPTIONS: { label: string; deg: number }[] = [
  { label: 'N', deg: 0 }, { label: 'NO', deg: 45 }, { label: 'O', deg: 90 }, { label: 'SO', deg: 135 },
  { label: 'S', deg: 180 }, { label: 'SW', deg: 225 }, { label: 'W', deg: 270 }, { label: 'NW', deg: 315 },
]

export function MapCompass({ bearing, windDirection, canEdit, onWindChange }: MapCompassProps) {
  const [open, setOpen] = useState(false)
  const hasWind = typeof windDirection === 'number'

  return (
    <div className="absolute top-3 left-[60px] md:left-3 z-10 flex flex-col items-center gap-1.5">
      {/* Kompass mit Nordpfeil (dreht mit dem Karten-Bearing) */}
      <button
        type="button"
        onClick={() => canEdit && setOpen((o) => !o)}
        className="w-12 h-12 rounded-full bg-white/95 dark:bg-gray-900/95 shadow-md border border-black/10 dark:border-white/10 flex items-center justify-center relative"
        title={canEdit ? 'Wind einstellen' : 'Nordpfeil'}
        style={{ cursor: canEdit ? 'pointer' : 'default' }}
      >
        <svg viewBox="0 0 40 40" className="w-10 h-10" style={{ transform: `rotate(${-bearing}deg)` }}>
          {/* Nordnadel (rot) */}
          <polygon points="20,5 24,21 20,18 16,21" fill="#dc2626" />
          {/* Südnadel (grau) */}
          <polygon points="20,35 24,19 20,22 16,19" fill="#9ca3af" />
          <text x="20" y="12" textAnchor="middle" fontSize="7" fontWeight="700" fill="#dc2626" transform="rotate(0 20 20)">N</text>
        </svg>
      </button>

      {/* Wind-Anzeige */}
      {hasWind && (
        <div className="flex items-center gap-1 rounded-full bg-blue-600 text-white text-[11px] font-semibold pl-1.5 pr-2 py-0.5 shadow">
          <svg viewBox="0 0 24 24" className="w-3.5 h-3.5" style={{ transform: `rotate(${(windDirection as number) + 180 - bearing}deg)` }}>
            {/* Pfeil zeigt in die Drift-/Ausbreitungsrichtung (wohin es weht) */}
            <path d="M12 3 L18 15 L12 12 L6 15 Z" fill="currentColor" />
          </svg>
          <span>aus {degToCompass(windDirection as number)}</span>
        </div>
      )}
      {!hasWind && canEdit && (
        <button
          type="button"
          onClick={() => setOpen((o) => !o)}
          className="flex items-center gap-1 rounded-full bg-white/95 dark:bg-gray-900/95 text-[11px] font-medium text-muted-foreground pl-1.5 pr-2 py-0.5 shadow border border-black/10 dark:border-white/10"
          title="Windrichtung einstellen"
        >
          <Wind className="w-3.5 h-3.5" /> Wind
        </button>
      )}

      {/* Wind-Auswahl */}
      {open && canEdit && (
        <div className="absolute top-0 left-14 w-40 rounded-xl bg-white dark:bg-gray-900 shadow-xl border border-border p-2 z-20">
          <div className="flex items-center justify-between mb-1.5 px-1">
            <span className="text-xs font-semibold flex items-center gap-1"><Wind className="w-3.5 h-3.5" /> Wind aus</span>
            <button onClick={() => setOpen(false)} className="text-muted-foreground hover:text-foreground"><X className="w-3.5 h-3.5" /></button>
          </div>
          <div className="grid grid-cols-4 gap-1">
            {WIND_OPTIONS.map((w) => (
              <button
                key={w.deg}
                onClick={() => { onWindChange(w.deg); setOpen(false) }}
                className={`h-8 rounded-md text-xs font-semibold transition-colors ${
                  windDirection === w.deg ? 'bg-blue-600 text-white' : 'bg-muted hover:bg-accent text-foreground'
                }`}
              >
                {w.label}
              </button>
            ))}
          </div>
          {hasWind && (
            <button
              onClick={() => { onWindChange(null); setOpen(false) }}
              className="mt-1.5 w-full text-xs text-muted-foreground hover:text-destructive py-1"
            >
              Wind entfernen
            </button>
          )}
        </div>
      )}
    </div>
  )
}
