/**
 * GeoJSON 폴리곤 레이어 팩토리 (deck.gl GeoJsonLayer)
 *
 * 용도: 어구 그룹 폴리곤, 특정해역 I~IV 경계 등
 * deck.gl GeoJsonLayer로 GeoJSON Feature/FeatureCollection을 직접 렌더링.
 */
import { GeoJsonLayer } from 'deck.gl';

function hexToRgba(hex: string, alpha = 200): [number, number, number, number] {
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  return [r, g, b, alpha];
}

interface GeoJsonPolygonOptions {
  fillOpacity?: number;
  lineColor?: string;
  lineWidth?: number;
  pickable?: boolean;
}

/**
 * GeoJSON FeatureCollection/Feature 배열을 폴리곤 레이어로 렌더링.
 * feature.properties.color 가 있으면 해당 색상 사용, 없으면 defaultColor.
 */
export function createGeoJsonLayer(
  id: string,
  data: unknown,
  defaultColor = '#3b82f6',
  options: GeoJsonPolygonOptions = {},
) {
  const { fillOpacity = 30, lineColor, lineWidth = 1.5, pickable = true } = options;

  return new GeoJsonLayer({
    id,
    data: data as GeoJSON.FeatureCollection,
    pickable,
    stroked: true,
    filled: true,
    extruded: false,
    getFillColor: (f: GeoJSON.Feature) => {
      const color = (f.properties as Record<string, unknown>)?.color as string | undefined;
      return hexToRgba(color ?? defaultColor, fillOpacity);
    },
    getLineColor: (f: GeoJSON.Feature) => {
      const color = (f.properties as Record<string, unknown>)?.color as string | undefined;
      return hexToRgba(lineColor ?? color ?? defaultColor, 180);
    },
    getLineWidth: lineWidth,
    lineWidthUnits: 'pixels' as const,
    // tooltip용 데이터
    autoHighlight: true,
    highlightColor: [255, 255, 255, 40],
  });
}

/**
 * 어구 그룹 폴리곤 전용 레이어.
 * data: {polygon: GeoJSON.Geometry, color: string, label: string, risk: string}[]
 */
export function createGearPolygonLayer(
  id: string,
  data: { polygon: unknown; color: string; label: string; risk: string }[],
) {
  // Convert each item to a GeoJSON Feature
  const fc: GeoJSON.FeatureCollection = {
    type: 'FeatureCollection',
    features: data
      .filter(d => d.polygon != null)
      .map((d, i) => ({
        type: 'Feature' as const,
        properties: { color: d.color, label: d.label, risk: d.risk, idx: i },
        geometry: d.polygon as GeoJSON.Geometry,
      })),
  };

  return createGeoJsonLayer(id, fc, '#64748b', {
    fillOpacity: 25,
    lineWidth: 2,
  });
}
