Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

30.4 KB
Raw Blame
import { unzlibSync } from 'fflate';

export type ColorSetImportFormat = 'json' | 'cls' | 'png';

export interface ParsedColorSet {
  ok: true;
  format: ColorSetImportFormat;
  name: string;
  swatches: Array<{ hex: string; name?: string }>;
}

export interface ParsedColorSetError {
  ok: false;
  error: string;
}

export type ParseColorSetResult = ParsedColorSet | ParsedColorSetError;

export const COLOR_SET_IMPORT_ACCEPT = '.json,.cls,.png,application/json,image/png';
export const SUPPORTED_COLOR_SET_EXTENSIONS = new Set(['.json', '.cls', '.png']);

const DEFAULT_MAX_SWATCHES = 512;
const MAX_CLS_BYTES = 8 * 1024 * 1024; // 8 MB safety ceiling
const MAX_PNG_BYTES = 25 * 1024 * 1024; // 25 MB safety ceiling
const MAX_PNG_PIXELS = 64_000_000; // 64 MP safety ceiling
const MAX_QUANTIZED_SWATCHES = 24;
const EXACT_SCAN_MAP_LIMIT = 65_536;

const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] as const;

export function isSupportedColorSetFilename(filename: string): boolean {
  const lower = filename.trim().toLowerCase();
  const dot = lower.lastIndexOf('.');
  if (dot <= 0) return false;
  return SUPPORTED_COLOR_SET_EXTENSIONS.has(lower.slice(dot));
}

export function deriveColorSetNameFromFilename(
  filename: string | undefined,
  fallback: string
): string {
  if (!filename || typeof filename !== 'string') return fallback;
  const normalized = filename.replace(/\\/g, '/');
  const base = normalized.slice(normalized.lastIndexOf('/') + 1);
  // Strip `.inkcolorset.json` or any single extension
  const stripped = base.replace(/\.inkcolorset\.json$/i, '').replace(/\.[^/.]+$/, '');
  const clean = stripControlChars(stripped).trim().slice(0, 48);
  return clean || fallback;
}

function stripControlChars(value: string): string {
  let out = '';
  for (let i = 0; i < value.length; i++) {
    const code = value.charCodeAt(i);
    if (code >= 0x20 && code !== 0x7f) {
      out += value[i];
    }
  }
  return out;
}

function rgbBytesToHex(r: number, g: number, b: number): string {
  return (
    '#' +
    ((1 << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff))
      .toString(16)
      .slice(1)
  );
}

export function hasSlccMagic(bytes: Uint8Array): boolean {
  return (
    bytes.byteLength >= 4 &&
    bytes[0] === 0x53 && // 'S'
    bytes[1] === 0x4c && // 'L'
    bytes[2] === 0x43 && // 'C'
    bytes[3] === 0x43 // 'C'
  );
}

export function hasPngSignature(bytes: Uint8Array): boolean {
  if (bytes.byteLength < 8) return false;
  for (let i = 0; i < 8; i++) {
    if (bytes[i] !== PNG_SIGNATURE[i]) return false;
  }
  return true;
}

function decodeUtf8Strict(bytes: Uint8Array): string | null {
  try {
    return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
  } catch {
    return null;
  }
}

function decodeLatin1(bytes: Uint8Array): string {
  let out = '';
  for (let i = 0; i < bytes.length; i++) {
    out += String.fromCharCode(bytes[i]);
  }
  return out;
}

function decodeClsSwatchName(bytes: Uint8Array): string | undefined {
  if (bytes.byteLength === 0) return undefined;
  let decoded: string;
  if (bytes.byteLength % 2 === 0) {
    try {
      decoded = new TextDecoder('utf-16le', { fatal: true }).decode(bytes);
    } catch {
      decoded = decodeUtf8Strict(bytes) ?? decodeLatin1(bytes);
    }
  } else {
    decoded = decodeUtf8Strict(bytes) ?? decodeLatin1(bytes);
  }
  const cleaned = stripControlChars(decoded.replace(/\0+$/g, '')).trim().slice(0, 48);
  return cleaned || undefined;
}

/**
 * Parses a Clip Studio Paint Color Set (`.cls`, magic `"SLCC"`) binary buffer.
 *
 * Binary layout:
 * - `[0..3]`   `"SLCC"` magic
 * - `[4..5]`   version `uint16 LE` (typically `0x0100` / 256)
 * - `[6..9]`   `headerByteLength` (`uint32 LE`) starting at offset 10
 * - `[10..10+headerByteLength)` metadata:
 *     `uint16 LE` name1Len + name1 bytes,
 *     optional `uint32 LE` flags/padding + `uint16 LE` name2Len + UTF-8 name2 bytes
 * - `[headerEnd..headerEnd+12)`:
 *     `uint32 LE` channelCount (4),
 *     `uint32 LE` colorCount,
 *     `uint32 LE` colorDataByteLength
 * - Repeated `colorCount` times:
 *     `uint32 LE` entryPayloadLength,
 *     `[r, g, b, a]` (4 bytes; `a === 0` represents an empty slot in CSP),
 *     optional `uint32 LE` hasNameFlag,
 *     if `hasNameFlag !== 0`: `uint16 LE` nameByteLength + UTF-16LE name bytes
 */
export function parseClipStudioColorSet(
  data: Uint8Array | ArrayBuffer,
  filename?: string,
  maxSwatches: number = DEFAULT_MAX_SWATCHES
): ParseColorSetResult {
  const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
  if (bytes.byteLength === 0) {
    return { ok: false, error: 'Clip Studio color set file is empty.' };
  }
  if (bytes.byteLength > MAX_CLS_BYTES) {
    return { ok: false, error: 'Clip Studio color set file exceeds 8 MB limit.' };
  }
  if (!hasSlccMagic(bytes)) {
    return { ok: false, error: 'Invalid Clip Studio color set (.cls): missing SLCC header.' };
  }
  if (bytes.byteLength < 22) {
    return { ok: false, error: 'Clip Studio color set (.cls) is truncated.' };
  }

  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  const headerByteLength = view.getUint32(6, true);
  const headerStart = 10;
  const headerEnd = headerStart + headerByteLength;

  if (headerEnd + 12 > bytes.byteLength) {
    return { ok: false, error: 'Clip Studio color set (.cls) header is truncated.' };
  }

  // Extract set name from header metadata (preferring the secondary UTF-8 name when present)
  let primaryName: string | null = null;
  let utf8Name: string | null = null;

  if (headerByteLength >= 2) {
    const l1 = view.getUint16(headerStart, true);
    const name1Start = headerStart + 2;
    const name1End = name1Start + l1;
    if (name1End <= headerEnd) {
      if (l1 > 0) {
        const raw1 = bytes.subarray(name1Start, name1End);
        const s1 = stripControlChars(decodeUtf8Strict(raw1) ?? decodeLatin1(raw1)).trim();
        if (s1) primaryName = s1;
      }
      // Secondary UTF-8 name block: 4-byte reserved/flags + uint16 length + UTF-8 bytes
      const l2Pos = name1End + 4;
      if (l2Pos + 2 <= headerEnd) {
        const l2 = view.getUint16(l2Pos, true);
        const name2Start = l2Pos + 2;
        const name2End = name2Start + l2;
        if (l2 > 0 && name2End <= headerEnd) {
          const raw2 = bytes.subarray(name2Start, name2End);
          const s2 = stripControlChars(decodeUtf8Strict(raw2) ?? decodeLatin1(raw2)).trim();
          if (s2) utf8Name = s2;
        }
      }
    }
  }

  const colorCount = view.getUint32(headerEnd + 4, true);
  const colorDataByteLength = view.getUint32(headerEnd + 8, true);

  let pos = headerEnd + 12;
  const entriesEnd =
    colorDataByteLength > 0
      ? Math.min(bytes.byteLength, pos + colorDataByteLength)
      : bytes.byteLength;

  if (colorCount === 0) {
    return { ok: false, error: 'Clip Studio color set contains no color swatches.' };
  }

  const swatches: Array<{ hex: string; name?: string }> = [];
  for (let i = 0; i < colorCount; i++) {
    if (pos + 4 > entriesEnd) {
      if (swatches.length === 0) {
        return { ok: false, error: 'Clip Studio color set (.cls) color table is truncated.' };
      }
      break;
    }

    const entryPayloadLen = view.getUint32(pos, true);
    pos += 4;
    if (entryPayloadLen < 4 || pos + entryPayloadLen > bytes.byteLength) {
      if (swatches.length === 0) {
        return { ok: false, error: 'Clip Studio color set (.cls) has an invalid swatch entry.' };
      }
      break;
    }

    const payloadEnd = pos + entryPayloadLen;
    const r = bytes[pos];
    const g = bytes[pos + 1];
    const b = bytes[pos + 2];
    const a = bytes[pos + 3];

    // Alpha 0 represents an empty grid cell in Clip Studio Paint color sets.
    if (a > 0 && swatches.length < maxSwatches) {
      let swatchName: string | undefined;
      if (entryPayloadLen >= 10) {
        const hasNameFlag = view.getUint32(pos + 4, true);
        if (hasNameFlag !== 0) {
          const nameByteLen = view.getUint16(pos + 8, true);
          const nameStart = pos + 10;
          const nameEnd = Math.min(payloadEnd, nameStart + nameByteLen);
          if (nameByteLen > 0 && nameEnd > nameStart) {
            swatchName = decodeClsSwatchName(bytes.subarray(nameStart, nameEnd));
          }
        }
      }

      const hex = rgbBytesToHex(r, g, b);
      swatches.push(swatchName ? { hex, name: swatchName } : { hex });
    }

    pos = payloadEnd;
  }

  if (swatches.length === 0) {
    return { ok: false, error: 'No opaque colors found in Clip Studio color set.' };
  }

  const resolvedName = (
    utf8Name ||
    primaryName ||
    deriveColorSetNameFromFilename(filename, 'Clip Studio Color Set')
  ).slice(0, 48);

  return {
    ok: true,
    format: 'cls',
    name: resolvedName,
    swatches,
  };
}

// ============================================================================
// Pure PNG Decoder + Smart Palette Extractor
// ============================================================================

export interface DecodedPng {
  width: number;
  height: number;
  rgba: Uint8ClampedArray;
  title?: string;
}

function paethPredictor(a: number, b: number, c: number): number {
  const p = a + b - c;
  const pa = Math.abs(p - a);
  const pb = Math.abs(p - b);
  const pc = Math.abs(p - c);
  if (pa <= pb && pa <= pc) return a;
  if (pb <= pc) return b;
  return c;
}

function unfilterScanline(
  filterType: number,
  raw: Uint8Array,
  rawOffset: number,
  dest: Uint8Array,
  prev: Uint8Array | null,
  stride: number,
  bpp: number
): void {
  switch (filterType) {
    case 0: // None
      for (let i = 0; i < stride; i++) {
        dest[i] = raw[rawOffset + i];
      }
      break;
    case 1: // Sub
      for (let i = 0; i < stride; i++) {
        const left = i >= bpp ? dest[i - bpp] : 0;
        dest[i] = (raw[rawOffset + i] + left) & 0xff;
      }
      break;
    case 2: // Up
      for (let i = 0; i < stride; i++) {
        const up = prev ? prev[i] : 0;
        dest[i] = (raw[rawOffset + i] + up) & 0xff;
      }
      break;
    case 3: // Average
      for (let i = 0; i < stride; i++) {
        const left = i >= bpp ? dest[i - bpp] : 0;
        const up = prev ? prev[i] : 0;
        dest[i] = (raw[rawOffset + i] + ((left + up) >> 1)) & 0xff;
      }
      break;
    case 4: // Paeth
      for (let i = 0; i < stride; i++) {
        const left = i >= bpp ? dest[i - bpp] : 0;
        const up = prev ? prev[i] : 0;
        const upLeft = prev && i >= bpp ? prev[i - bpp] : 0;
        dest[i] = (raw[rawOffset + i] + paethPredictor(left, up, upLeft)) & 0xff;
      }
      break;
    default:
      throw new Error(`Unsupported PNG filter type: ${filterType}`);
  }
}

function readSample(scanline: Uint8Array, pixelIndex: number, bitDepth: number): number {
  if (bitDepth === 8) return scanline[pixelIndex];
  if (bitDepth === 16) return scanline[pixelIndex * 2]; // High byte
  const pixelsPerByte = 8 / bitDepth;
  const byteIndex = Math.floor(pixelIndex / pixelsPerByte);
  const shift = 8 - bitDepth * ((pixelIndex % pixelsPerByte) + 1);
  const mask = (1 << bitDepth) - 1;
  return (scanline[byteIndex] >> shift) & mask;
}

function writePngRowToRgba(
  scanline: Uint8Array,
  rowWidth: number,
  colorType: number,
  bitDepth: number,
  palette: Uint8Array | null,
  trns: Uint8Array | null,
  rgba: Uint8ClampedArray,
  imageWidth: number,
  destY: number,
  destXStart: number,
  destXStep: number
): void {
  const maxSample = bitDepth < 8 ? (1 << bitDepth) - 1 : 255;

  let trnsGray = -1;
  let trnsR = -1;
  let trnsG = -1;
  let trnsB = -1;
  if (trns) {
    if (colorType === 0 && trns.length >= 2) {
      trnsGray = bitDepth === 16 ? trns[0] : ((trns[0] << 8) | trns[1]) & maxSample;
    } else if (colorType === 2 && trns.length >= 6) {
      if (bitDepth === 16) {
        trnsR = trns[0];
        trnsG = trns[2];
        trnsB = trns[4];
      } else {
        trnsR = trns[1];
        trnsG = trns[3];
        trnsB = trns[5];
      }
    }
  }

  for (let x = 0; x < rowWidth; x++) {
    const outIdx = (destY * imageWidth + (destXStart + x * destXStep)) * 4;
    let r = 0;
    let g = 0;
    let b = 0;
    let a = 255;

    if (colorType === 3) {
      // Indexed color (PLTE)
      const idx = readSample(scanline, x, bitDepth);
      if (palette && idx * 3 + 2 < palette.length) {
        r = palette[idx * 3];
        g = palette[idx * 3 + 1];
        b = palette[idx * 3 + 2];
      }
      if (trns && idx < trns.length) {
        a = trns[idx];
      }
    } else if (colorType === 0) {
      // Grayscale
      const sample = readSample(scanline, x, bitDepth);
      const v = bitDepth < 8 ? Math.round((sample * 255) / maxSample) : sample;
      r = v;
      g = v;
      b = v;
      if (trnsGray >= 0 && sample === trnsGray) {
        a = 0;
      }
    } else if (colorType === 2) {
      // Truecolor RGB
      const step = bitDepth === 16 ? 2 : 1;
      const base = x * 3 * step;
      r = scanline[base];
      g = scanline[base + step];
      b = scanline[base + 2 * step];
      if (trnsR >= 0 && r === trnsR && g === trnsG && b === trnsB) {
        a = 0;
      }
    } else if (colorType === 4) {
      // Grayscale + Alpha
      const step = bitDepth === 16 ? 2 : 1;
      const base = x * 2 * step;
      const v = scanline[base];
      r = v;
      g = v;
      b = v;
      a = scanline[base + step];
    } else if (colorType === 6) {
      // Truecolor RGBA
      const step = bitDepth === 16 ? 2 : 1;
      const base = x * 4 * step;
      r = scanline[base];
      g = scanline[base + step];
      b = scanline[base + 2 * step];
      a = scanline[base + 3 * step];
    }

    rgba[outIdx] = r;
    rgba[outIdx + 1] = g;
    rgba[outIdx + 2] = b;
    rgba[outIdx + 3] = a;
  }
}

const ADAM7_PASSES: ReadonlyArray<readonly [number, number, number, number]> = [
  [0, 0, 8, 8],
  [4, 0, 8, 8],
  [0, 4, 4, 8],
  [2, 0, 4, 4],
  [0, 2, 2, 4],
  [1, 0, 2, 2],
  [0, 1, 1, 2],
];

export function decodePngBytes(data: Uint8Array | ArrayBuffer): DecodedPng {
  const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
  if (!hasPngSignature(bytes)) {
    throw new Error('Invalid PNG file: missing PNG signature.');
  }

  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  let offset = 8;

  let width = 0;
  let height = 0;
  let bitDepth = 0;
  let colorType = 0;
  let interlace = 0;
  let sawIhdr = false;
  let palette: Uint8Array | null = null;
  let trns: Uint8Array | null = null;
  let title: string | undefined;
  const idatChunks: Uint8Array[] = [];
  let totalIdatLen = 0;

  while (offset + 12 <= bytes.byteLength) {
    const length = view.getUint32(offset, false);
    const type = String.fromCharCode(
      bytes[offset + 4],
      bytes[offset + 5],
      bytes[offset + 6],
      bytes[offset + 7]
    );
    const dataStart = offset + 8;
    const dataEnd = dataStart + length;
    if (dataEnd + 4 > bytes.byteLength) {
      throw new Error('PNG file is truncated.');
    }

    if (type === 'IHDR') {
      if (length < 13) throw new Error('Invalid PNG IHDR chunk.');
      width = view.getUint32(dataStart, false);
      height = view.getUint32(dataStart + 4, false);
      bitDepth = bytes[dataStart + 8];
      colorType = bytes[dataStart + 9];
      const compression = bytes[dataStart + 10];
      const filterMethod = bytes[dataStart + 11];
      interlace = bytes[dataStart + 12];
      if (width === 0 || height === 0) {
        throw new Error('PNG image has zero dimensions.');
      }
      if (width * height > MAX_PNG_PIXELS) {
        throw new Error('PNG image dimensions exceed safety limit.');
      }
      if (compression !== 0 || filterMethod !== 0 || (interlace !== 0 && interlace !== 1)) {
        throw new Error('Unsupported PNG encoding parameters.');
      }
      sawIhdr = true;
    } else if (type === 'PLTE') {
      palette = bytes.subarray(dataStart, dataEnd);
    } else if (type === 'tRNS') {
      trns = bytes.subarray(dataStart, dataEnd);
    } else if (type === 'IDAT') {
      const chunk = bytes.subarray(dataStart, dataEnd);
      idatChunks.push(chunk);
      totalIdatLen += chunk.byteLength;
    } else if ((type === 'tEXt' || type === 'iTXt') && !title) {
      const chunk = bytes.subarray(dataStart, dataEnd);
      const nul = chunk.indexOf(0);
      if (nul > 0) {
        const keyword = decodeLatin1(chunk.subarray(0, nul)).toLowerCase();
        if (keyword === 'title') {
          if (type === 'tEXt') {
            const rawVal = stripControlChars(decodeLatin1(chunk.subarray(nul + 1))).trim();
            if (rawVal) title = rawVal.slice(0, 48);
          } else if (type === 'iTXt' && nul + 3 < chunk.length && chunk[nul + 1] === 0) {
            const langEnd = chunk.indexOf(0, nul + 3);
            if (langEnd >= 0) {
              const transEnd = chunk.indexOf(0, langEnd + 1);
              if (transEnd >= 0) {
                const textBytes = chunk.subarray(transEnd + 1);
                const rawVal = stripControlChars(
                  decodeUtf8Strict(textBytes) ?? decodeLatin1(textBytes)
                ).trim();
                if (rawVal) title = rawVal.slice(0, 48);
              }
            }
          }
        }
      }
    } else if (type === 'IEND') {
      break;
    }

    offset = dataEnd + 4; // skip CRC
  }

  if (!sawIhdr) {
    throw new Error('Invalid PNG file: missing IHDR chunk.');
  }
  if (idatChunks.length === 0) {
    throw new Error('Invalid PNG file: missing IDAT image data.');
  }

  let channels: number;
  switch (colorType) {
    case 0:
      channels = 1;
      break;
    case 2:
      channels = 3;
      break;
    case 3:
      channels = 1;
      if (!palette) throw new Error('Indexed PNG is missing PLTE palette chunk.');
      break;
    case 4:
      channels = 2;
      break;
    case 6:
      channels = 4;
      break;
    default:
      throw new Error(`Unsupported PNG color type: ${colorType}`);
  }

  if (![1, 2, 4, 8, 16].includes(bitDepth)) {
    throw new Error(`Unsupported PNG bit depth: ${bitDepth}`);
  }

  const combinedIdat = new Uint8Array(totalIdatLen);
  let idatPos = 0;
  for (const chunk of idatChunks) {
    combinedIdat.set(chunk, idatPos);
    idatPos += chunk.byteLength;
  }

  let inflated: Uint8Array;
  try {
    inflated = unzlibSync(combinedIdat);
  } catch {
    throw new Error('Failed to decompress PNG image data.');
  }

  const bitsPerPixel = channels * bitDepth;
  const bpp = Math.max(1, Math.ceil(bitsPerPixel / 8));
  const rgba = new Uint8ClampedArray(width * height * 4);

  if (interlace === 0) {
    const stride = Math.ceil((width * bitsPerPixel) / 8);
    let curr: Uint8Array = new Uint8Array(stride);
    let prev: Uint8Array | null = null;
    let srcOff = 0;

    for (let y = 0; y < height; y++) {
      if (srcOff + 1 + stride > inflated.byteLength) {
        throw new Error('PNG scanline data is truncated.');
      }
      const filterType = inflated[srcOff];
      unfilterScanline(filterType, inflated, srcOff + 1, curr, prev, stride, bpp);
      srcOff += 1 + stride;

      writePngRowToRgba(curr, width, colorType, bitDepth, palette, trns, rgba, width, y, 0, 1);

      const nextPrev = prev ?? new Uint8Array(stride);
      prev = curr;
      curr = nextPrev;
    }
  } else {
    let srcOff = 0;
    for (const [xStart, yStart, xStep, yStep] of ADAM7_PASSES) {
      const passW = Math.ceil((width - xStart) / xStep);
      const passH = Math.ceil((height - yStart) / yStep);
      if (passW <= 0 || passH <= 0) continue;

      const stride = Math.ceil((passW * bitsPerPixel) / 8);
      let curr: Uint8Array = new Uint8Array(stride);
      let prev: Uint8Array | null = null;

      for (let py = 0; py < passH; py++) {
        if (srcOff + 1 + stride > inflated.byteLength) {
          throw new Error('Interlaced PNG scanline data is truncated.');
        }
        const filterType = inflated[srcOff];
        unfilterScanline(filterType, inflated, srcOff + 1, curr, prev, stride, bpp);
        srcOff += 1 + stride;

        writePngRowToRgba(
          curr,
          passW,
          colorType,
          bitDepth,
          palette,
          trns,
          rgba,
          width,
          yStart + py * yStep,
          xStart,
          xStep
        );

        const nextPrev = prev ?? new Uint8Array(stride);
        prev = curr;
        curr = nextPrev;
      }
    }
  }

  return { width, height, rgba, title };
}

interface ColorStat {
  rgb: number;
  r: number;
  g: number;
  b: number;
  count: number;
  firstIndex: number;
  sumX: number;
  sumY: number;
}

interface QuantizedCluster {
  r: number;
  g: number;
  b: number;
  count: number;
  centerX: number;
  centerY: number;
}

function medianCutExtract(
  rgba: Uint8ClampedArray,
  width: number,
  height: number,
  maxColors: number
): Array<{ hex: string }> {
  const totalPixels = width * height;
  const maxSamples = 65536;
  const step = Math.max(1, Math.floor(Math.sqrt(totalPixels / maxSamples)));

  const samples: Array<[number, number, number, number, number]> = [];
  for (let y = 0; y < height; y += step) {
    const rowOff = y * width;
    for (let x = 0; x < width; x += step) {
      const idx = (rowOff + x) * 4;
      if (rgba[idx + 3] < 128) continue;
      samples.push([rgba[idx], rgba[idx + 1], rgba[idx + 2], x, y]);
    }
  }

  if (samples.length === 0) return [];

  interface Box {
    items: Array<[number, number, number, number, number]>;
    rMin: number;
    rMax: number;
    gMin: number;
    gMax: number;
    bMin: number;
    bMax: number;
  }

  const makeBox = (items: Array<[number, number, number, number, number]>): Box => {
    let rMin = 255;
    let rMax = 0;
    let gMin = 255;
    let gMax = 0;
    let bMin = 255;
    let bMax = 0;
    for (let i = 0; i < items.length; i++) {
      const [r, g, b] = items[i];
      if (r < rMin) rMin = r;
      if (r > rMax) rMax = r;
      if (g < gMin) gMin = g;
      if (g > gMax) gMax = g;
      if (b < bMin) bMin = b;
      if (b > bMax) bMax = b;
    }
    return { items, rMin, rMax, gMin, gMax, bMin, bMax };
  };

  const boxes: Box[] = [makeBox(samples)];

  while (boxes.length < maxColors) {
    let bestIdx = -1;
    let bestScore = 0;
    for (let i = 0; i < boxes.length; i++) {
      const box = boxes[i];
      if (box.items.length < 2) continue;
      const range = Math.max(box.rMax - box.rMin, box.gMax - box.gMin, box.bMax - box.bMin);
      if (range <= 4) continue;
      const score = range * Math.sqrt(box.items.length);
      if (score > bestScore) {
        bestScore = score;
        bestIdx = i;
      }
    }
    if (bestIdx < 0) break;

    const target = boxes[bestIdx];
    const rRange = target.rMax - target.rMin;
    const gRange = target.gMax - target.gMin;
    const bRange = target.bMax - target.bMin;
    const channel = rRange >= gRange && rRange >= bRange ? 0 : gRange >= bRange ? 1 : 2;

    target.items.sort((a, b) => a[channel] - b[channel]);
    const mid = Math.floor(target.items.length / 2);
    const left = target.items.slice(0, mid);
    const right = target.items.slice(mid);
    if (left.length === 0 || right.length === 0) break;

    boxes.splice(bestIdx, 1, makeBox(left), makeBox(right));
  }

  const rawClusters: QuantizedCluster[] = boxes.map((box) => {
    let sumR = 0;
    let sumG = 0;
    let sumB = 0;
    let sumX = 0;
    let sumY = 0;
    const n = box.items.length;
    for (let i = 0; i < n; i++) {
      const [r, g, b, x, y] = box.items[i];
      sumR += r;
      sumG += g;
      sumB += b;
      sumX += x;
      sumY += y;
    }
    return {
      r: Math.round(sumR / n),
      g: Math.round(sumG / n),
      b: Math.round(sumB / n),
      count: n,
      centerX: sumX / n,
      centerY: sumY / n,
    };
  });

  // Merge near-duplicate clusters so lossy-reencoded flat blocks collapse cleanly
  rawClusters.sort((a, b) => b.count - a.count);
  const merged: QuantizedCluster[] = [];
  const MERGE_DIST_SQ = 12 * 12;

  for (const cluster of rawClusters) {
    let found = false;
    for (const existing of merged) {
      const dr = existing.r - cluster.r;
      const dg = existing.g - cluster.g;
      const db = existing.b - cluster.b;
      if (dr * dr + dg * dg + db * db <= MERGE_DIST_SQ) {
        const total = existing.count + cluster.count;
        existing.r = Math.round((existing.r * existing.count + cluster.r * cluster.count) / total);
        existing.g = Math.round((existing.g * existing.count + cluster.g * cluster.count) / total);
        existing.b = Math.round((existing.b * existing.count + cluster.b * cluster.count) / total);
        existing.centerX =
          (existing.centerX * existing.count + cluster.centerX * cluster.count) / total;
        existing.centerY =
          (existing.centerY * existing.count + cluster.centerY * cluster.count) / total;
        existing.count = total;
        found = true;
        break;
      }
    }
    if (!found) {
      merged.push({ ...cluster });
    }
  }

  // Order spatially top-to-bottom, left-to-right
  const rowBand = Math.max(1, height / 8);
  merged.sort((a, b) => {
    const bandA = Math.floor(a.centerY / rowBand);
    const bandB = Math.floor(b.centerY / rowBand);
    if (bandA !== bandB) return bandA - bandB;
    return a.centerX - b.centerX;
  });

  const seenHex = new Set<string>();
  const out: Array<{ hex: string }> = [];
  for (const c of merged) {
    const hex = rgbBytesToHex(c.r, c.g, c.b);
    if (!seenHex.has(hex)) {
      seenHex.add(hex);
      out.push({ hex });
    }
  }
  return out;
}

/**
 * Extracts color swatches from an RGBA image buffer.
 *
 * Strategy:
 * 1. Exact palette PNGs (1px strips, 8x/32x Lospec/Aseprite strips, swatch grids):
 *    preserves every exact opaque RGB color in reading order (top-to-bottom, left-to-right).
 *    On large images (>= 10k opaque pixels), filters out tiny anti-aliased text/border fringes
 *    if dominant flat colors already cover >= 90% of opaque pixels.
 * 2. Large flat-swatch palette sheets with anti-aliased labels (>512 unique colors):
 *    detects dominant exact flat colors when they cover >= 75% of opaque pixels.
 * 3. General / photographic / gradient PNGs:
 *    runs deterministic Median-Cut quantization to extract up to 24 cohesive swatches.
 */
export function extractSwatchesFromRgba(
  rgba: Uint8ClampedArray,
  width: number,
  height: number,
  maxSwatches: number = DEFAULT_MAX_SWATCHES
): Array<{ hex: string }> {
  const colorMap = new Map<number, ColorStat>();
  let totalOpaque = 0;
  let maxColorCount = 0;
  let exceededExactCap = false;

  for (let y = 0; y < height; y++) {
    const rowOff = y * width;
    for (let x = 0; x < width; x++) {
      const pixelIndex = rowOff + x;
      const idx = pixelIndex * 4;
      if (rgba[idx + 3] < 128) continue;

      totalOpaque++;
      if (exceededExactCap) continue;

      const r = rgba[idx];
      const g = rgba[idx + 1];
      const b = rgba[idx + 2];
      const key = (r << 16) | (g << 8) | b;

      const stat = colorMap.get(key);
      if (stat) {
        stat.count++;
        stat.sumX += x;
        stat.sumY += y;
        if (stat.count > maxColorCount) maxColorCount = stat.count;
      } else if (colorMap.size < EXACT_SCAN_MAP_LIMIT) {
        colorMap.set(key, {
          rgb: key,
          r,
          g,
          b,
          count: 1,
          firstIndex: pixelIndex,
          sumX: x,
          sumY: y,
        });
        if (1 > maxColorCount) maxColorCount = 1;
      } else {
        exceededExactCap = true;
      }
    }
  }

  if (totalOpaque === 0) return [];

  // Tier 1: Clean palette PNG (<= maxSwatches exact unique opaque colors)
  if (!exceededExactCap && colorMap.size <= maxSwatches) {
    const allStats = Array.from(colorMap.values());

    if (totalOpaque >= 10_000 && allStats.length > 2) {
      const minMajorCount = Math.max(maxColorCount * 0.015, totalOpaque * 0.001);
      const majorStats = allStats.filter((s) => s.count >= minMajorCount);
      if (majorStats.length >= 2 && majorStats.length < allStats.length) {
        const majorPixels = majorStats.reduce((sum, s) => sum + s.count, 0);
        if (majorPixels / totalOpaque >= 0.9) {
          majorStats.sort((a, b) => a.firstIndex - b.firstIndex);
          return majorStats.map((s) => ({ hex: rgbBytesToHex(s.r, s.g, s.b) }));
        }
      }
    }

    allStats.sort((a, b) => a.firstIndex - b.firstIndex);
    return allStats.map((s) => ({ hex: rgbBytesToHex(s.r, s.g, s.b) }));
  }

  // Tier 2: Flat palette card with anti-aliased text/borders pushing exact unique colors > maxSwatches
  if (!exceededExactCap && colorMap.size > 0 && totalOpaque >= 10_000) {
    const minMajorCount = Math.max(maxColorCount * 0.015, totalOpaque * 0.002);
    const majorStats = Array.from(colorMap.values()).filter((s) => s.count >= minMajorCount);
    if (majorStats.length >= 2 && majorStats.length <= 64) {
      const majorPixels = majorStats.reduce((sum, s) => sum + s.count, 0);
      if (majorPixels / totalOpaque >= 0.75) {
        const rowBand = Math.max(1, height / 12);
        majorStats.sort((a, b) => {
          const ay = a.sumY / a.count;
          const by = b.sumY / b.count;
          const bandA = Math.floor(ay / rowBand);
          const bandB = Math.floor(by / rowBand);
          if (bandA !== bandB) return bandA - bandB;
          return a.sumX / a.count - b.sumX / b.count;
        });
        return majorStats.map((s) => ({ hex: rgbBytesToHex(s.r, s.g, s.b) }));
      }
    }
  }

  // Tier 3: Continuous-tone / photographic / gradient PNG -> Median-Cut extraction
  return medianCutExtract(rgba, width, height, Math.min(MAX_QUANTIZED_SWATCHES, maxSwatches));
}

/**
 * Parses a PNG color palette image (`.png`) into a Color Set.
 */
export function parsePngColorSet(
  data: Uint8Array | ArrayBuffer,
  filename?: string,
  maxSwatches: number = DEFAULT_MAX_SWATCHES
): ParseColorSetResult {
  const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
  if (bytes.byteLength === 0) {
    return { ok: false, error: 'PNG palette file is empty.' };
  }
  if (bytes.byteLength > MAX_PNG_BYTES) {
    return { ok: false, error: 'PNG palette file exceeds 25 MB limit.' };
  }
  if (!hasPngSignature(bytes)) {
    return { ok: false, error: 'Invalid PNG palette file: missing PNG signature.' };
  }

  let decoded: DecodedPng;
  try {
    decoded = decodePngBytes(bytes);
  } catch (err) {
    const msg = err instanceof Error ? err.message : 'Failed to decode PNG palette file.';
    return { ok: false, error: msg };
  }

  const swatches = extractSwatchesFromRgba(decoded.rgba, decoded.width, decoded.height, maxSwatches);
  if (swatches.length === 0) {
    return { ok: false, error: 'No opaque colors found in PNG palette image.' };
  }

  const name = (
    decoded.title || deriveColorSetNameFromFilename(filename, 'PNG Color Palette')
  ).slice(0, 48);

  return {
    ok: true,
    format: 'png',
    name,
    swatches,
  };
}