import { isDriveAppPath } from "@/lib/suite/drive-route"
import { ULTICAL_APP_NAME } from "@/lib/suite/page-metadata"

export type SuiteSplashApp = "mail" | "drive" | "agenda" | "contacts"

const SPLASH_SEEN_PREFIX = "ultisuite-splash-seen-v1"
const LEGACY_MAIL_SPLASH_KEY = "ultimail-splash-seen-v1"

export type SuiteSplashConfig = {
  pill: string
  mark: string
  /** UltiCal : variante dark mode. */
  markDark?: string
  subtitle: string
  ariaLabel: string
  spinMark?: boolean
}

export const SUITE_SPLASH_CONFIG: Record<SuiteSplashApp, SuiteSplashConfig> = {
  mail: {
    pill: "ULTIMAIL",
    mark: "/ultimail-mark.svg",
    subtitle: "Synchronisation de votre boite de reception...",
    ariaLabel: "Chargement d'Ultimail",
  },
  drive: {
    pill: "ULTIDRIVE",
    mark: "/ultidrive-mark.svg",
    subtitle: "Chargement de vos fichiers...",
    ariaLabel: "Chargement d'UltiDrive",
    spinMark: true,
  },
  agenda: {
    pill: "ULTICAL",
    mark: "/agenda-mark.svg",
    markDark: "/agenda-mark-dark.svg",
    subtitle: "Chargement de votre agenda...",
    ariaLabel: `Chargement d'${ULTICAL_APP_NAME}`,
    spinMark: true,
  },
  contacts: {
    pill: "CONTACTS",
    mark: "/contacts-mark.svg",
    subtitle: "Chargement de vos contacts...",
    ariaLabel: "Chargement des contacts",
    spinMark: true,
  },
}

export function suiteSplashStorageKey(app: SuiteSplashApp): string {
  return `${SPLASH_SEEN_PREFIX}-${app}`
}

export function suiteSplashAppFromPath(pathname: string): SuiteSplashApp | null {
  if (pathname === "/mail" || pathname.startsWith("/mail/")) return "mail"
  if (isDriveAppPath(pathname)) return "drive"
  if (pathname === "/agenda" || pathname.startsWith("/agenda/")) return "agenda"
  if (pathname === "/contacts" || pathname.startsWith("/contacts/")) return "contacts"
  return null
}

export function shouldSkipSuiteSplash(pathname: string): boolean {
  return pathname === "/" || pathname.startsWith("/demo/")
}

export function isSuiteSplashSeen(app: SuiteSplashApp): boolean {
  if (typeof window === "undefined") return false
  try {
    if (localStorage.getItem(suiteSplashStorageKey(app)) === "1") return true
    if (app === "mail" && localStorage.getItem(LEGACY_MAIL_SPLASH_KEY) === "1") {
      return true
    }
  } catch {
    // Ignore storage failures (private mode / disabled storage).
  }
  return false
}

export function markSuiteSplashSeen(app: SuiteSplashApp): void {
  try {
    localStorage.setItem(suiteSplashStorageKey(app), "1")
    if (app === "mail") {
      localStorage.setItem(LEGACY_MAIL_SPLASH_KEY, "1")
    }
  } catch {
    // Ignore storage failures (private mode / disabled storage).
  }
}

export function shouldShowSuiteSplash(pathname: string): SuiteSplashApp | null {
  if (shouldSkipSuiteSplash(pathname)) return null
  const app = suiteSplashAppFromPath(pathname)
  if (!app || isSuiteSplashSeen(app)) return null
  return app
}
