export const PAPER_SIZE_REGISTRY = {
  A4: { type: 'A4', unit: 'mm', width: 210, height: 297 },
  A3: { type: 'A3', unit: 'mm', width: 297, height: 420 },
  Letter: { type: 'Letter', unit: 'mm', width: 215.9, height: 279.4 },
  Legal: { type: 'Legal', unit: 'mm', width: 215.9, height: 355.6 },
} as const;

const INCH_TO_MM = 25.4;
const CM_TO_MM = 10;

export function normalizePaperSize(input?: string): {
  type: string;
  unit: 'mm';
  width: number;
  height: number;
} {
  if (!input) return PAPER_SIZE_REGISTRY.A4;

  // 1️⃣ Match named sizes (A4, A3, Letter, Legal)
  const keyMatch = input.match(/\b(A\d|Letter|Legal)\b/i);
  const key = keyMatch?.[1] as keyof typeof PAPER_SIZE_REGISTRY;

  if (key && PAPER_SIZE_REGISTRY[key]) return PAPER_SIZE_REGISTRY[key];

  // 2️⃣ Match custom dimensions: supports mm | cm | in
  const dimMatch = input.match(
    /(\d+(?:\.\d+)?)\s*(mm|cm|in)\s*[x×]\s*(\d+(?:\.\d+)?)\s*(mm|cm|in)/i,
  );

  if (dimMatch) {
    let [, w, unitW, h, unitH] = dimMatch;

    let width = Number(w);
    let height = Number(h);

    if (unitW === 'cm') width *= CM_TO_MM;
    if (unitW === 'in') width *= INCH_TO_MM;

    if (unitH === 'cm') height *= CM_TO_MM;
    if (unitH === 'in') height *= INCH_TO_MM;

    return {
      type: 'Custom',
      unit: 'mm',
      width,
      height,
    };
  }

  // 3️⃣ Safe fallback
  return PAPER_SIZE_REGISTRY.A4;
}
