// ── 선종(Ship Kind) 상수 + SVG 아이콘 생성 ──
// gc-wing-simple의 SVG 기반 선종별 아이콘 시스템을 도입.
// 기타 AIS: 선종별 색상 + 이동(화살표)/정지(원형) 분리.
// 대상 선박: legacy code 색상 + 약간 더 큰 SVG + 흰색 테두리.

import { LEGACY_CODE_COLORS_RGB, rgbToHex, type Rgb } from './palette';

// ── 선종 상수 (8종) ──

export const SIGNAL_KIND = {
  FISHING: '000020',
  KCGV: '000021',
  PASSENGER: '000022',
  CARGO: '000023',
  TANKER: '000024',
  GOV: '000025',
  NORMAL: '000027',
  BUOY: '000028',
} as const;

export type SignalKindCode = (typeof SIGNAL_KIND)[keyof typeof SIGNAL_KIND] | string;

/** 선종별 한글 라벨 */
export const SHIP_KIND_LABELS: Record<string, string> = {
  '000020': '어선',
  '000021': '경비함정',
  '000022': '여객선',
  '000023': '화물선',
  '000024': '유조선',
  '000025': '관공선',
  '000027': '일반',
  '000028': '부이',
};

/** 선종별 범례/UI 색상 (hex) */
export const SHIP_KIND_COLORS: Record<string, string> = {
  '000020': '#00C853',
  '000021': '#FF5722',
  '000022': '#2196F3',
  '000023': '#9C27B0',
  '000024': '#F44336',
  '000025': '#FF9800',
  '000027': '#607D8B',
  '000028': '#795548',
};

/** 정렬된 선종 코드 목록 (범례 표시 순서) */
export const SHIP_KIND_ORDER = [
  '000020', '000021', '000022', '000023',
  '000024', '000025', '000027', '000028',
] as const;

// ── SVG 아이콘 생성기 ──

const STROKE = 'rgba(0,0,0,0.6)';
const TARGET_STROKE = 'rgba(255,255,255,0.7)';

/** 이동 중 선박 SVG (화살표 형태, 32×48) */
export function makeMovingShipSvg(fill: string): string {
  return `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="48" viewBox="0 0 32 48"><path d="M16 2 L8 13 L4 28 L7 45 L25 45 L28 28 L24 13 Z" fill="${fill}" stroke="${STROKE}" stroke-width="1.5" stroke-linejoin="round"/></svg>`;
}

/** 정지 선박 SVG (원형, 16×16) */
export function makeStoppedShipSvg(fill: string): string {
  return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><circle cx="8" cy="8" r="5.5" fill="${fill}" stroke="${STROKE}" stroke-width="1.2"/></svg>`;
}

/** 부이 SVG (다색, 32×44) */
export function makeBuoySvg(): string {
  return `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="44" viewBox="0 0 32 44"><line x1="16" y1="10" x2="16" y2="38" stroke="#5D4037" stroke-width="2.5" stroke-linecap="round"/><line x1="10" y1="38" x2="22" y2="38" stroke="#5D4037" stroke-width="2" stroke-linecap="round"/><ellipse cx="16" cy="24" rx="9" ry="7" fill="#E53935" stroke="#333" stroke-width="1"/><rect x="8" y="22" width="16" height="4" rx="1" fill="#FDD835" opacity="0.85"/><rect x="14.5" y="8" width="3" height="10" fill="#666"/><circle cx="16" cy="7" r="3.5" fill="#FFC107" stroke="#444" stroke-width="0.8"/></svg>`;
}

/** 대상 선박 이동 SVG (36×52, 흰색 반투명 테두리) */
export function makeTargetMovingShipSvg(fill: string): string {
  return `<svg xmlns="http://www.w3.org/2000/svg" width="36" height="52" viewBox="0 0 36 52"><path d="M18 2 L9 14 L5 30 L8 49 L28 49 L31 30 L27 14 Z" fill="${fill}" stroke="${TARGET_STROKE}" stroke-width="2" stroke-linejoin="round"/></svg>`;
}

/** 대상 선박 정지 SVG (20×20, 흰색 반투명 테두리) */
export function makeTargetStoppedShipSvg(fill: string): string {
  return `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><circle cx="10" cy="10" r="7" fill="${fill}" stroke="${TARGET_STROKE}" stroke-width="1.5"/></svg>`;
}

function toDataUri(svg: string): string {
  return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
}

/** Deck.gl IconLayer getIcon 반환 타입 */
export interface ShipIconSpec {
  url: string;
  width: number;
  height: number;
  anchorX: number;
  anchorY: number;
}

// ── 기타 AIS 아이콘 스펙 사전 생성 (8종 × 2상태 + buoy) ──

const OTHER_ICON_SPECS: Record<string, ShipIconSpec> = {};

for (const code of SHIP_KIND_ORDER) {
  const color = SHIP_KIND_COLORS[code] || '#607D8B';

  if (code === '000028') {
    OTHER_ICON_SPECS[`${code}-buoy`] = {
      url: toDataUri(makeBuoySvg()),
      width: 32, height: 44, anchorX: 16, anchorY: 22,
    };
    continue;
  }

  OTHER_ICON_SPECS[`${code}-moving`] = {
    url: toDataUri(makeMovingShipSvg(color)),
    width: 32, height: 48, anchorX: 16, anchorY: 24,
  };
  OTHER_ICON_SPECS[`${code}-stopped`] = {
    url: toDataUri(makeStoppedShipSvg(color)),
    width: 16, height: 16, anchorX: 8, anchorY: 8,
  };
}

// fallback
const FALLBACK_MOVING: ShipIconSpec = OTHER_ICON_SPECS['000027-moving'];
const FALLBACK_STOPPED: ShipIconSpec = OTHER_ICON_SPECS['000027-stopped'];

// ── 대상 선박 아이콘 스펙 사전 생성 (7 legacyCode × 2상태) ──

const LEGACY_CODES = ['PT', 'PT-S', 'GN', 'OT', 'PS', 'FC', 'C21'] as const;

const TARGET_ICON_SPECS: Record<string, ShipIconSpec> = {};

for (const code of LEGACY_CODES) {
  const rgb: Rgb = LEGACY_CODE_COLORS_RGB[code] || [100, 116, 139];
  const hex = rgbToHex(rgb);

  TARGET_ICON_SPECS[`${code}-moving`] = {
    url: toDataUri(makeTargetMovingShipSvg(hex)),
    width: 36, height: 52, anchorX: 18, anchorY: 26,
  };
  TARGET_ICON_SPECS[`${code}-stopped`] = {
    url: toDataUri(makeTargetStoppedShipSvg(hex)),
    width: 20, height: 20, anchorX: 10, anchorY: 10,
  };
}

// fallback (FC 색상)
const TARGET_FALLBACK_MOVING: ShipIconSpec = TARGET_ICON_SPECS['FC-moving'];
const TARGET_FALLBACK_STOPPED: ShipIconSpec = TARGET_ICON_SPECS['FC-stopped'];

// ── SOG 기준 이동/정지 판단 (kn) ──

export const SPEED_THRESHOLD_KN = 1;

// ── 조회 함수 ──

/** 기타 AIS 아이콘 스펙 조회 */
export function getShipIconSpec(
  signalKindCode: string | undefined | null,
  sog: number | undefined | null,
): ShipIconSpec {
  const code = signalKindCode || '000027';
  if (code === '000028') return OTHER_ICON_SPECS['000028-buoy'] || FALLBACK_STOPPED;

  const isMoving = Number.isFinite(sog) && (sog as number) > SPEED_THRESHOLD_KN;
  const key = `${code}-${isMoving ? 'moving' : 'stopped'}`;
  return OTHER_ICON_SPECS[key] || (isMoving ? FALLBACK_MOVING : FALLBACK_STOPPED);
}

/** 대상 선박 아이콘 스펙 조회 */
export function getTargetShipIconSpec(
  legacyShipCode: string | undefined | null,
  sog: number | undefined | null,
): ShipIconSpec {
  const code = legacyShipCode || 'FC';
  const isMoving = Number.isFinite(sog) && (sog as number) > SPEED_THRESHOLD_KN;
  const key = `${code}-${isMoving ? 'moving' : 'stopped'}`;
  return TARGET_ICON_SPECS[key] || (isMoving ? TARGET_FALLBACK_MOVING : TARGET_FALLBACK_STOPPED);
}

/** 선박 아이콘 회전각 (부이는 0, 나머지는 -cog) */
export function getShipIconAngle(
  signalKindCode: string | undefined | null,
  cog: number | undefined | null,
): number {
  const code = signalKindCode || '000027';
  if (code === '000028') return 0;
  return -(Number.isFinite(cog) ? (cog as number) : 0);
}
