"use client"

import { useEffect, useState } from "react"
import { usePathname } from "next/navigation"
import { UltiMailLogo } from "@/components/ultimail-logo"
import { isDriveAppPath } from "@/lib/suite/drive-route"
import { cn } from "@/lib/utils"

const SPLASH_SEEN_KEY = "ultimail-splash-seen-v1"
const SPLASH_VISIBLE_MS = 1750
const SPLASH_EXIT_MS = 500

export function FirstLaunchSplash({
  children,
}: {
  children: React.ReactNode
}) {
  const pathname = usePathname()
  const [isHiding, setIsHiding] = useState(false)
  const [isComplete, setIsComplete] = useState(false)

  useEffect(() => {
    const root = document.documentElement
    const skipForDrive =
      pathname === "/" ||
      pathname.startsWith("/demo/") ||
      isDriveAppPath(pathname) ||
      root.dataset.routeScope === "drive" ||
      root.dataset.splashSeen === "1"

    if (skipForDrive) {
      if (isDriveAppPath(pathname)) root.dataset.splashSeen = "1"
      setIsComplete(true)
      return
    }

    const hideTimer = window.setTimeout(() => {
      setIsHiding(true)
    }, SPLASH_VISIBLE_MS)

    const completeTimer = window.setTimeout(() => {
      try {
        localStorage.setItem(SPLASH_SEEN_KEY, "1")
      } catch {
        // Ignore storage failures (private mode / disabled storage).
      }
      root.dataset.splashSeen = "1"
      setIsComplete(true)
    }, SPLASH_VISIBLE_MS + SPLASH_EXIT_MS)

    return () => {
      window.clearTimeout(hideTimer)
      window.clearTimeout(completeTimer)
    }
  }, [pathname])

  return (
    <>
      {children}
      {!isComplete ? (
        <div
          className={cn("app-first-launch-splash", isHiding && "app-first-launch-splash--hide")}
          role="status"
          aria-live="polite"
          aria-label="Chargement d'Ultimail"
        >
          <div className="app-first-launch-splash__aurora" aria-hidden />
          <div className="app-first-launch-splash__grain" aria-hidden />
          <div className="app-first-launch-splash__content">
            <div className="app-first-launch-splash__pill">ULTIMAIL</div>
            <UltiMailLogo href={null} className="app-first-launch-splash__logo" />
            <p className="app-first-launch-splash__subtitle">
              Synchronisation de votre boite de reception...
            </p>
            <div className="app-first-launch-splash__loader" aria-hidden>
              <span />
            </div>
          </div>
        </div>
      ) : null}
    </>
  )
}
