export type DocxPreviewFormat = {
  fontFamily: string;
  fontSizePt: number;
  lineHeight: number;
  zoomPercent: number;
  bold: boolean;
  italic: boolean;
};

export const DOCX_PREVIEW_FONT_PRESETS: { label: string; value: string }[] = [
  { label: 'Times New Roman', value: "'Times New Roman', Times, serif" },
  { label: 'Arial', value: 'Arial, Helvetica, sans-serif' },
  { label: 'Calibri', value: "'Calibri', 'Segoe UI', sans-serif" },
  { label: 'Georgia', value: 'Georgia, serif' },
];

export const DOCX_PREVIEW_DEFAULT_FORMAT: DocxPreviewFormat = {
  fontFamily: DOCX_PREVIEW_FONT_PRESETS[0].value,
  fontSizePt: 13,
  lineHeight: 1.25,
  zoomPercent: 100,
  bold: false,
  italic: false,
};

const STORAGE_KEY = 'app-docx-preview-format-v1';

export function loadDocxPreviewFormat(): DocxPreviewFormat {
  const allowedZoom = [85, 100, 125, 150] as const;
  const allowedLine = [1.15, 1.5, 2] as const;
  const snap = (n: number, allowed: readonly number[]) =>
    allowed.reduce((best, x) => (Math.abs(x - n) < Math.abs(best - n) ? x : best));

  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return DOCX_PREVIEW_DEFAULT_FORMAT;
    const p = JSON.parse(raw) as Partial<DocxPreviewFormat>;
    return {
      fontFamily: typeof p.fontFamily === 'string' ? p.fontFamily : DOCX_PREVIEW_DEFAULT_FORMAT.fontFamily,
      fontSizePt: typeof p.fontSizePt === 'number' ? clamp(p.fontSizePt, 9, 24) : DOCX_PREVIEW_DEFAULT_FORMAT.fontSizePt,
      lineHeight:
        typeof p.lineHeight === 'number'
          ? snap(clamp(p.lineHeight, 1, 3), allowedLine)
          : DOCX_PREVIEW_DEFAULT_FORMAT.lineHeight,
      zoomPercent:
        typeof p.zoomPercent === 'number'
          ? snap(clamp(p.zoomPercent, 75, 200), allowedZoom)
          : DOCX_PREVIEW_DEFAULT_FORMAT.zoomPercent,
      bold: Boolean(p.bold),
      italic: Boolean(p.italic),
    };
  } catch {
    return DOCX_PREVIEW_DEFAULT_FORMAT;
  }
}

export function saveDocxPreviewFormat(f: DocxPreviewFormat): void {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(f));
  } catch {
    /* ignore quota / private mode */
  }
}

function clamp(n: number, min: number, max: number): number {
  return Math.min(max, Math.max(min, n));
}
