import { InputError, parseJson, type ValidationResult } from './validation';
export function escapeHtml(value: unknown): string { return String(value ?? '').replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[char]!)); }
export function formatMoney(value: string | number, currency: 'CAD' | 'USD' = 'CAD'): string { return new Intl.NumberFormat('en-CA', { style: 'currency', currency, currencyDisplay: 'code' }).format(Number(value)); }
export function downloadBlob(data: Blob | Uint8Array | string, filename: string, mime = 'application/octet-stream'): void {
  const blob = data instanceof Blob ? data : new Blob([typeof data === 'string' ? data : data.slice().buffer as ArrayBuffer], { type: mime });
  const url = URL.createObjectURL(blob); const link = document.createElement('a');
  link.href = url; link.download = filename.replace(/[^a-zA-Z0-9._-]/g, '-'); link.hidden = true;
  document.body.append(link); link.click(); link.remove(); setTimeout(() => URL.revokeObjectURL(url), 10_000);
}
export function downloadJson(data: unknown, filename: string): void { downloadBlob(JSON.stringify(data, null, 2), filename, 'application/json'); }
export function confirmReplace(message = 'Replace this draft? Export it first if you want to keep a copy.'): boolean { return window.confirm(message); }
const storageKey = (key: string) => `essential-tools:${key}:v1`;
export function saveDraft(key: string, value: unknown): void {
  try { localStorage.setItem(storageKey(key), JSON.stringify(value)); } catch { throw new InputError('This browser could not save the draft. Download JSON to keep a copy.'); }
}
export function loadDraft<T>(key: string, validate?: (input: unknown) => ValidationResult<T>): T | null {
  let text: string | null;
  try { text = localStorage.getItem(storageKey(key)); } catch { throw new InputError('Browser storage is unavailable. You can import a JSON file instead.'); }
  if (!text) return null;
  const data = parseJson(text);
  if (!validate) return data as T;
  const result = validate(data);
  if (!result.ok) throw new InputError('The saved draft is damaged or uses an unsupported version. Your current draft is unchanged.');
  return result.value;
}
export function clearSavedDraft(key: string): void {
  try { localStorage.removeItem(storageKey(key)); } catch { throw new InputError('This browser could not clear the saved draft.'); }
}
