import { useState } from 'react';
import { Marker, Popup } from 'react-map-gl/maplibre';
import { CN_POWER_PLANTS, CN_MILITARY_FACILITIES, type CnFacility } from '../../data/cnFacilities';

interface Props {
  type: 'power' | 'military';
}

const SUBTYPE_META: Record<CnFacility['subType'], { color: string; icon: string; label: string }> = {
  nuclear:  { color: '#a855f7', icon: '☢', label: '핵발전' },
  thermal:  { color: '#f97316', icon: '⚡', label: '화력발전' },
  naval:    { color: '#3b82f6', icon: '⚓', label: '해군기지' },
  airbase:  { color: '#22d3ee', icon: '✈', label: '공군기지' },
  army:     { color: '#ef4444', icon: '★', label: '육군/사령부' },
  shipyard: { color: '#f59e0b', icon: '⚙', label: '조선소' },
};

export function CnFacilityLayer({ type }: Props) {
  const [popup, setPopup] = useState<CnFacility | null>(null);
  const facilities = type === 'power' ? CN_POWER_PLANTS : CN_MILITARY_FACILITIES;

  return (
    <>
      {facilities.map(f => {
        const meta = SUBTYPE_META[f.subType];
        return (
          <Marker
            key={f.id}
            longitude={f.lng}
            latitude={f.lat}
            anchor="center"
            onClick={e => { e.originalEvent.stopPropagation(); setPopup(f); }}
          >
            <div
              title={f.name}
              style={{
                width: 18,
                height: 18,
                borderRadius: '50%',
                background: meta.color,
                border: '2px solid rgba(255,255,255,0.7)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: 9,
                color: '#fff',
                cursor: 'pointer',
                boxShadow: `0 0 6px ${meta.color}88`,
              }}
            >
              {meta.icon}
            </div>
          </Marker>
        );
      })}

      {popup && (
        <Popup
          longitude={popup.lng}
          latitude={popup.lat}
          anchor="bottom"
          onClose={() => setPopup(null)}
          closeOnClick={false}
          maxWidth="220px"
        >
          <div style={{ fontSize: 11, lineHeight: 1.6, padding: '2px 4px' }}>
            <div style={{ fontWeight: 700, marginBottom: 4 }}>{popup.name}</div>
            <div style={{ color: SUBTYPE_META[popup.subType].color, marginBottom: 4 }}>
              {SUBTYPE_META[popup.subType].label}
            </div>
            {popup.operator && (
              <div><span style={{ opacity: 0.6 }}>운영:</span> {popup.operator}</div>
            )}
            {popup.description && (
              <div style={{ marginTop: 4, opacity: 0.85 }}>{popup.description}</div>
            )}
          </div>
        </Popup>
      )}
    </>
  );
}
