import { useState } from 'react';
import { Marker, Popup } from 'react-map-gl/maplibre';
import { EAST_ASIA_PORTS } from '../../data/ports';
import type { Port } from '../../data/ports';

const COUNTRY_STYLE: Record<string, { color: string; flag: string; label: string }> = {
  KR: { color: '#3b82f6', flag: '🇰🇷', label: '한국' },
  CN: { color: '#ef4444', flag: '🇨🇳', label: '중국' },
  JP: { color: '#f472b6', flag: '🇯🇵', label: '일본' },
  KP: { color: '#f97316', flag: '🇰🇵', label: '북한' },
  TW: { color: '#10b981', flag: '🇹🇼', label: '대만' },
};

function getStyle(p: Port) {
  return COUNTRY_STYLE[p.country] || COUNTRY_STYLE.KR;
}

function AnchorIcon({ color, size = 14 }: { color: string; size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="5" r="2.5" stroke={color} strokeWidth="1.5" fill="none" />
      <line x1="12" y1="7.5" x2="12" y2="21" stroke={color} strokeWidth="1.5" />
      <line x1="7" y1="12" x2="17" y2="12" stroke={color} strokeWidth="1.5" />
      <path d="M5 18 Q8 21 12 21 Q16 21 19 18" stroke={color} strokeWidth="1.5" fill="none" />
    </svg>
  );
}

export function PortLayer() {
  const [selected, setSelected] = useState<Port | null>(null);

  return (
    <>
      {EAST_ASIA_PORTS.map(p => {
        const s = getStyle(p);
        const size = p.type === 'major' ? 16 : 12;
        return (
          <Marker key={p.id} longitude={p.lng} latitude={p.lat} anchor="center"
            onClick={(e) => { e.originalEvent.stopPropagation(); setSelected(p); }}>
            <div
              className="flex flex-col items-center cursor-pointer"
              style={{ filter: `drop-shadow(0 0 2px ${s.color}88)` }}
            >
              <AnchorIcon color={s.color} size={size} />
              <div style={{
                fontSize: 5, color: s.color, marginTop: 0,
                textShadow: '0 0 3px #000, 0 0 3px #000',
                whiteSpace: 'nowrap', fontWeight: 700,
              }}>
                {p.nameKo.replace('항', '')}
              </div>
            </div>
          </Marker>
        );
      })}

      {selected && (() => {
        const s = getStyle(selected);
        return (
          <Popup longitude={selected.lng} latitude={selected.lat}
            onClose={() => setSelected(null)} closeOnClick={false}
            anchor="bottom" maxWidth="280px" className="gl-popup">
            <div className="popup-body-sm" style={{ minWidth: 200 }}>
              <div className="popup-header" style={{ background: s.color, color: '#fff', gap: 6, padding: '6px 10px' }}>
                <span style={{ fontSize: 16 }}>{s.flag}</span>
                <strong style={{ fontSize: 13 }}>⚓ {selected.nameKo}</strong>
              </div>
              <div style={{ display: 'flex', gap: 4, marginBottom: 6 }}>
                <span style={{
                  background: s.color, color: '#fff',
                  padding: '2px 8px', borderRadius: 3, fontSize: 10, fontWeight: 700,
                }}>
                  {selected.type === 'major' ? '주요항만' : '항만'}
                </span>
                <span style={{
                  background: '#333', color: '#ccc',
                  padding: '2px 8px', borderRadius: 3, fontSize: 10,
                }}>
                  {s.label}
                </span>
              </div>
              <div className="popup-grid" style={{ gap: '2px 12px' }}>
                <div><span className="popup-label">항구 : </span><strong>{selected.nameKo}</strong></div>
                <div><span className="popup-label">영문 : </span>{selected.name}</div>
              </div>
              <div style={{ marginTop: 6, fontSize: 10, color: '#999' }}>
                {selected.lat.toFixed(4)}°N, {selected.lng.toFixed(4)}°E
              </div>
              <div style={{ marginTop: 4, fontSize: 10, textAlign: 'right' }}>
                <a href={`https://www.marinetraffic.com/en/ais/details/ports/${selected.id}`}
                  target="_blank" rel="noopener noreferrer" style={{ color: '#60a5fa' }}>
                  MarineTraffic &rarr;
                </a>
              </div>
            </div>
          </Popup>
        );
      })()}
    </>
  );
}
