import type { AisTarget } from '../../../entities/aisTarget/model/types';
import type { LegacyVesselInfo } from '../../../entities/legacyVessel/model/types';
import { rgbToHex } from '../../../shared/lib/map/palette';
import { SHIP_KIND_COLORS } from '../../../shared/lib/map/shipKind';
import {
  ANCHOR_SPEED_THRESHOLD_KN,
  LEGACY_CODE_COLORS,
} from '../constants';
import { isFiniteNumber } from './setUtils';
import { normalizeAngleDeg } from './geometry';

export function toValidBearingDeg(value: unknown): number | null {
  if (typeof value !== 'number' || !Number.isFinite(value)) return null;
  if (value === 511) return null;
  if (value < 0) return null;
  if (value >= 360) return null;
  return value;
}

export function isAnchoredShip({
  sog,
  cog,
  heading,
}: {
  sog: number | null | undefined;
  cog: number | null | undefined;
  heading: number | null | undefined;
}): boolean {
  if (!isFiniteNumber(sog)) return true;
  if (sog <= ANCHOR_SPEED_THRESHOLD_KN) return true;
  return toValidBearingDeg(cog) == null && toValidBearingDeg(heading) == null;
}

export function getDisplayHeading({
  cog,
  heading,
  offset = 0,
}: {
  cog: number | null | undefined;
  heading: number | null | undefined;
  offset?: number;
}) {
  const raw = toValidBearingDeg(cog) ?? toValidBearingDeg(heading) ?? 0;
  return normalizeAngleDeg(raw, offset);
}

export function lightenColor(rgb: [number, number, number], ratio = 0.32) {
  const out = rgb.map((v) => Math.round(v + (255 - v) * ratio) as number) as [number, number, number];
  return out;
}

export function getGlobeBaseShipColor({
  legacy,
  signalKindCode,
}: {
  legacy: string | null;
  signalKindCode?: string;
}) {
  // 대상 선박: legacy code 색상 (밝게)
  if (legacy) {
    const rgb = LEGACY_CODE_COLORS[legacy];
    if (rgb) return rgbToHex(lightenColor(rgb, 0.38));
  }

  // 기타 AIS: signalKindCode → 선종별 색상
  const kindColor = SHIP_KIND_COLORS[signalKindCode || '000027'];
  if (kindColor) return kindColor;
  return '#607D8B';
}

export function buildGlobeShipFeature(
  t: AisTarget,
  legacy: LegacyVesselInfo | undefined,
  selectedMmsi: number | null,
  highlightedMmsis: Set<number>,
  offset: number,
) {
  const isSelected = selectedMmsi != null && t.mmsi === selectedMmsi ? 1 : 0;
  const isHighlighted = highlightedMmsis.has(t.mmsi) ? 1 : 0;
  const anchored = isAnchoredShip(t);

  return {
    mmsi: t.mmsi,
    heading: getDisplayHeading({ cog: t.cog, heading: t.heading, offset }),
    anchored,
    color: getGlobeBaseShipColor({
      legacy: legacy?.shipCode ?? null,
      signalKindCode: t.signalKindCode || t.shipKindCode || '000027',
    }),
    selected: isSelected,
    highlighted: isHighlighted,
    permitted: legacy ? 1 : 0,
    labelName: (legacy?.shipNameRoman?.toUpperCase() || legacy?.shipNameCn || t.name?.toUpperCase() || '').trim(),
    legacyTag: legacy ? `${legacy.permitNo} (${legacy.shipCode})` : '',
  };
}
