"use client";

import { useState, useEffect } from "react";
import { AnimatePresence, motion } from "framer-motion";
import { SplashScreen, SPLASH_DURATION_MS } from "./SplashScreen";

const SESSION_KEY = "doliplay_splash_shown";

export function SplashWrapper({ children }: { children: React.ReactNode }) {
  const [showSplash, setShowSplash] = useState(false);
  const [splashDone, setSplashDone] = useState(false);

  useEffect(() => {
    const already = sessionStorage.getItem(SESSION_KEY);
    if (!already) {
      setShowSplash(true);
      sessionStorage.setItem(SESSION_KEY, "1");

      // Trigger exit animation after SPLASH_DURATION_MS
      const t = setTimeout(() => {
        setShowSplash(false);
      }, SPLASH_DURATION_MS);

      return () => clearTimeout(t);
    } else {
      setSplashDone(true);
    }
  }, []);

  const handleComplete = () => setSplashDone(true);

  return (
    <>
      <AnimatePresence mode="wait" onExitComplete={handleComplete}>
        {showSplash && (
          <SplashScreen key="splash" onComplete={handleComplete} />
        )}
      </AnimatePresence>

      {/* App content — fades in after splash exits */}
      <AnimatePresence>
        {(splashDone || !showSplash) && !showSplash && (
          <motion.div
            key="app"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.45, ease: "easeOut" }}
            style={{ minHeight: "100dvh" }}
          >
            {children}
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
