import type { MailBackgroundId } from "@/lib/mail-settings/types"

export type MailBackgroundPreset = {
  id: MailBackgroundId
  label: string
  /** Valeur CSS pour `background` (image, gradient, ou combinaison). */
  background: string
  /** Couleur de repli sous l’image. */
  fallbackColor: string
}

/** Anciens ids persistés → nouveaux presets. */
const LEGACY_BACKGROUND_IDS: Record<string, MailBackgroundId> = {
  mountains: "photo-mountains",
  ocean: "gradient-ocean",
  forest: "photo-nature",
  abstract: "gradient-blossom",
}

export const MAIL_BACKGROUND_PRESETS: MailBackgroundPreset[] = [
  {
    id: "none",
    label: "Aucun",
    background: "none",
    fallbackColor: "var(--app-canvas)",
  },
  {
    id: "gradient-aurora",
    label: "Aurore",
    background: `url("/mail-backgrounds/gradient-aurora.svg") center / cover no-repeat`,
    fallbackColor: "#667eea",
  },
  {
    id: "gradient-sunset",
    label: "Coucher de soleil",
    background: `url("/mail-backgrounds/gradient-sunset.svg") center / cover no-repeat`,
    fallbackColor: "#e44d26",
  },
  {
    id: "gradient-ocean",
    label: "Océan",
    background: `url("/mail-backgrounds/gradient-ocean.svg") center / cover no-repeat`,
    fallbackColor: "#203a43",
  },
  {
    id: "gradient-blossom",
    label: "Floral",
    background: `url("/mail-backgrounds/gradient-blossom.svg") center / cover no-repeat`,
    fallbackColor: "#ffecd2",
  },
  {
    id: "photo-mountains",
    label: "Montagnes",
    background: `url("https://picsum.photos/seed/ultimail-mountains/1920/1080") center / cover no-repeat`,
    fallbackColor: "#5c6b73",
  },
  {
    id: "photo-ocean",
    label: "Mer",
    background: `url("https://picsum.photos/seed/ultimail-ocean/1920/1080") center / cover no-repeat`,
    fallbackColor: "#1a5276",
  },
  {
    id: "photo-city",
    label: "Ville",
    background: `url("https://picsum.photos/seed/ultimail-city/1920/1080") center / cover no-repeat`,
    fallbackColor: "#2c3e50",
  },
  {
    id: "photo-nature",
    label: "Nature",
    background: `url("https://picsum.photos/seed/ultimail-nature/1920/1080") center / cover no-repeat`,
    fallbackColor: "#2d5016",
  },
]

export function normalizeMailBackgroundId(id: string): MailBackgroundId {
  if (MAIL_BACKGROUND_PRESETS.some((p) => p.id === id)) {
    return id as MailBackgroundId
  }
  return LEGACY_BACKGROUND_IDS[id] ?? "none"
}

export function getMailBackgroundPreset(id: string): MailBackgroundPreset {
  const normalized = normalizeMailBackgroundId(id)
  return (
    MAIL_BACKGROUND_PRESETS.find((p) => p.id === normalized) ??
    MAIL_BACKGROUND_PRESETS[0]!
  )
}

export function mailBackgroundStyle(id: string): {
  background: string
  fallbackColor: string
} {
  const preset = getMailBackgroundPreset(id)
  return {
    background: preset.background,
    fallbackColor: preset.fallbackColor,
  }
}
