import React, { useState, useCallback, useMemo } from 'react';
import { MapContainer, TileLayer, GeoJSON, CircleMarker, Tooltip, useMap } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import { useIsMobile } from '../../hooks/useIsMobile';
import './MiniMap.css';

/* ─────────────────────────────────────────────
   Region accent palette
───────────────────────────────────────────── */
export const REGION_PALETTE = {
  japan:     '#e05c4b',
  korea:     '#d64f6e',
  china:     '#c84b3a',
  europe:    '#5b8fc4',
  france:    '#6f8fc4',
  italy:     '#78a46e',
  spain:     '#c4844a',
  sea:       '#4aad8b',
  thailand:  '#4aad8b',
  vietnam:   '#5faa78',
  bali:      '#7aac5a',
  indonesia: '#8aaa4a',
  america:   '#b4885c',
  usa:       '#b4885c',
  canada:    '#6a9890',
  africa:    '#c47c3c',
  middle:    '#c4a24a',
  dubai:     '#c4a24a',
  default:   '#c8905e',
};

export function getRegionAccent(regionId = '') {
  const id = regionId.toLowerCase();
  for (const [key, color] of Object.entries(REGION_PALETTE)) {
    if (key !== 'default' && id.includes(key)) return color;
  }
  return REGION_PALETTE.default;
}

/* ─────────────────────────────────────────────
   MapLayer — internal component
───────────────────────────────────────────── */
function MapLayer({ geojson, selectedRegionId, onSelectRegion }) {
  const map = useMap();

  /* Split features: polygons (for GeoJSON) vs points (for CircleMarker) */
  const { polygonGeoJson, pointFeatures } = useMemo(() => {
    if (!geojson?.features) return { polygonGeoJson: geojson, pointFeatures: [] };
    const polys = [];
    const points = [];
    for (const f of geojson.features) {
      if (f.geometry?.type === 'Point') {
        points.push(f);
      } else if (f.geometry) {
        polys.push(f);
      }
      // null geometry → skip (no location yet)
    }
    return {
      polygonGeoJson: { ...geojson, features: polys },
      pointFeatures: points,
    };
  }, [geojson]);

  const style = useCallback(
    (feature) => {
      const rid = feature.properties?.id || feature.properties?.name || '';
      const isSelected =
        selectedRegionId && rid.toLowerCase() === selectedRegionId.toLowerCase();
      const accent = getRegionAccent(rid);
      return {
        fillColor: isSelected ? accent : 'rgba(232,221,208,0.12)',
        fillOpacity: isSelected ? 0.45 : 0.18,
        color: isSelected ? accent : 'rgba(232,221,208,0.25)',
        weight: isSelected ? 2.5 : 1,
      };
    },
    [selectedRegionId],
  );

  const onEachFeature = useCallback(
    (feature, layer) => {
      const name =
        feature.properties?.name_ko ||
        feature.properties?.name ||
        feature.properties?.id ||
        '';
      if (name) {
        layer.bindTooltip(name, {
          className: 'minimap-tooltip',
          sticky: true,
        });
      }
      layer.on('click', () => {
        const rid = feature.properties?.id || feature.properties?.name || '';
        onSelectRegion(rid);
        const bounds = layer.getBounds();
        if (bounds.isValid()) {
          map.fitBounds(bounds, { padding: [30, 30], maxZoom: 6 });
        }
      });
    },
    [map, onSelectRegion],
  );

  const handlePinClick = useCallback(
    (feature) => {
      const rid = feature.properties?.id || feature.properties?.name || '';
      onSelectRegion(rid);
      const [lng, lat] = feature.geometry.coordinates;
      map.setView([lat, lng], 5, { animate: true });
    },
    [map, onSelectRegion],
  );

  if (!geojson) return null;

  return (
    <>
      {polygonGeoJson.features.length > 0 && (
        <GeoJSON
          key={selectedRegionId || '__all__'}
          data={polygonGeoJson}
          style={style}
          onEachFeature={onEachFeature}
        />
      )}

      {pointFeatures.map((feature) => {
        const rid = feature.properties?.id || feature.properties?.name || '';
        const name = feature.properties?.name || rid;
        const [lng, lat] = feature.geometry.coordinates;
        const isSelected =
          selectedRegionId && rid.toLowerCase() === selectedRegionId.toLowerCase();
        const accent = getRegionAccent(rid);
        return (
          <CircleMarker
            key={`pin-${rid}`}
            center={[lat, lng]}
            radius={isSelected ? 8 : 5}
            pathOptions={{
              fillColor: accent,
              fillOpacity: isSelected ? 0.9 : 0.7,
              color: isSelected ? '#fff' : accent,
              weight: isSelected ? 2 : 1,
            }}
            eventHandlers={{ click: () => handlePinClick(feature) }}
          >
            <Tooltip className="minimap-tooltip">{name}</Tooltip>
          </CircleMarker>
        );
      })}
    </>
  );
}

/* ─────────────────────────────────────────────
   MiniMap
───────────────────────────────────────────── */
export default function MiniMap({
  geojson,
  selectedRegionId,
  onSelectRegion,
  onClearRegion,
}) {
  const [expanded, setExpanded] = useState(true);
  const isMobile = useIsMobile();

  const toggleExpanded = () => setExpanded((v) => !v);

  return (
    <div className="minimap-wrapper">
      {/* toolbar */}
      <div className="minimap-toolbar">
        <button
          className="minimap-toggle-btn"
          onClick={toggleExpanded}
          aria-label={expanded ? '지도 접기' : '지도 펼치기'}
        >
          {expanded ? '▲ 지도 접기' : '▼ 지도 펼치기'}
        </button>

        {selectedRegionId && (
          <button className="minimap-clear-btn" onClick={onClearRegion}>
            전체 보기
          </button>
        )}
      </div>

      {/* map container */}
      <div
        className={`minimap-container${expanded ? '' : ' minimap-collapsed'}`}
        style={{
          '--minimap-h': isMobile ? '150px' : '200px',
        }}
      >
        <MapContainer
          center={[30, 125]}
          zoom={2}
          minZoom={2}
          maxZoom={7}
          zoomControl={false}
          attributionControl={false}
          className="minimap-leaflet"
          style={{ width: '100%', height: '100%' }}
        >
          <TileLayer
            url="https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png"
            attribution=""
          />
          <MapLayer
            geojson={geojson}
            selectedRegionId={selectedRegionId}
            onSelectRegion={onSelectRegion}
          />
        </MapContainer>

        {!selectedRegionId && expanded && (
          <div className="minimap-hint">CLICK A REGION</div>
        )}
      </div>
    </div>
  );
}
