/**
 * Compute a readable ship label color based on the map background luminance.
 * Returns RGBA arrays for Deck.gl and CSS string for MapLibre.
 */

function hexToRgb(hex: string): [number, number, number] {
  const h = hex.replace('#', '');
  return [
    parseInt(h.slice(0, 2), 16),
    parseInt(h.slice(2, 4), 16),
    parseInt(h.slice(4, 6), 16),
  ];
}

/** Relative luminance (WCAG) */
function luminance(r: number, g: number, b: number): number {
  const [rs, gs, bs] = [r, g, b].map((c) => {
    const s = c / 255;
    return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
  });
  return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
}

export interface ShipLabelColors {
  /** Deck.gl TextLayer default getColor [R,G,B,A] */
  deckDefault: [number, number, number, number];
  /** MapLibre text-color CSS string */
  mlDefault: string;
  /** MapLibre text-halo-color CSS string */
  mlHalo: string;
  /** Deck.gl outlineColor [R,G,B,A] */
  deckOutline: [number, number, number, number];
}

/**
 * Given a background hex color, compute label colors that contrast well.
 */
export function computeShipLabelColors(bgHex: string): ShipLabelColors {
  const [r, g, b] = hexToRgb(bgHex);
  const lum = luminance(r, g, b);

  // Light background (lum > 0.4): dark labels with light halo
  // Dark background (lum <= 0.4): light labels with dark halo
  if (lum > 0.4) {
    return {
      deckDefault: [30, 30, 40, 234],
      mlDefault: 'rgba(30,30,40,0.92)',
      mlHalo: 'rgba(255,255,255,0.85)',
      deckOutline: [255, 255, 255, 210],
    };
  }

  return {
    deckDefault: [226, 232, 240, 234],
    mlDefault: 'rgba(226,232,240,0.92)',
    mlHalo: 'rgba(0,0,0,0.9)',
    deckOutline: [0, 0, 0, 230],
  };
}
