import {
  draftFromPageSetup,
  type PageSetupDraft,
} from "./doc-page-setup.ts"
import { DEFAULT_PAGE_FORMAT_ID, type PageFormatId } from "./page-formats.ts"

const STORAGE_KEY = "ultidrive-docs-page-defaults"

export function systemPageSetupDraft(
  fallbackFormatId: PageFormatId = DEFAULT_PAGE_FORMAT_ID
): PageSetupDraft {
  return draftFromPageSetup(null, fallbackFormatId)
}

function readStoredDefaults(): PageSetupDraft | null {
  if (typeof localStorage === "undefined") return null
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (!raw) return null
    const parsed = JSON.parse(raw) as Partial<PageSetupDraft>
    if (!parsed.formatId || !parsed.marginsCm) return null
    return {
      formatId: parsed.formatId,
      orientation: parsed.orientation === "landscape" ? "landscape" : "portrait",
      marginsCm: {
        top: Number(parsed.marginsCm.top) || 0,
        right: Number(parsed.marginsCm.right) || 0,
        bottom: Number(parsed.marginsCm.bottom) || 0,
        left: Number(parsed.marginsCm.left) || 0,
      },
      pageColor: parsed.pageColor ?? "#ffffff",
    }
  } catch {
    return null
  }
}

export function readUserPageSetupDefaults(
  fallbackFormatId: PageFormatId = DEFAULT_PAGE_FORMAT_ID
): PageSetupDraft {
  return readStoredDefaults() ?? systemPageSetupDraft(fallbackFormatId)
}

export function saveUserPageSetupDefaults(draft: PageSetupDraft): void {
  if (typeof localStorage === "undefined") return
  localStorage.setItem(STORAGE_KEY, JSON.stringify(draft))
}

export function pageSetupDraftsEqual(a: PageSetupDraft, b: PageSetupDraft): boolean {
  return (
    a.formatId === b.formatId &&
    a.orientation === b.orientation &&
    a.pageColor.toLowerCase() === b.pageColor.toLowerCase() &&
    a.marginsCm.top === b.marginsCm.top &&
    a.marginsCm.right === b.marginsCm.right &&
    a.marginsCm.bottom === b.marginsCm.bottom &&
    a.marginsCm.left === b.marginsCm.left
  )
}
