"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import { useIsMounted } from "@/hooks/useIsMounted";

/** Must match the CSS transition duration below. */
const FADE_MS = 300;

/**
 * Splash screen that shows the Fursa logo while the app initialises.
 *
 * The artificial 2-second minimum wait has been removed.
 * The logo is visible only during the natural JS hydration window
 * (~300–700 ms on a fast connection) so it never blocks LCP.
 *
 * The component hides itself as soon as React has mounted, with a
 * short 300 ms fade-out so the transition still feels polished.
 */
export default function SplashScreen({
  children,
}: {
  children: React.ReactNode;
}) {
  const [show, setShow] = useState(true);
  /*
   * The fade starts as soon as the client has hydrated — which is exactly what
   * `useIsMounted` reports, so it is a derivation rather than a `setState` in a
   * mount effect. The effect below now does only what an effect is for: own a
   * timer and clean it up.
   */
  const fadeOut = useIsMounted();

  useEffect(() => {
    // Unmount once the transition has finished. No artificial delay before it.
    const timer = setTimeout(() => setShow(false), FADE_MS);
    return () => clearTimeout(timer);
  }, []);

  /*
   * One tree shape for both states, overlay first and the page second, so
   * hiding the overlay only removes the overlay. The page used to sit inside a
   * wrapper `<div>` beside it and come back bare once `show` flipped — a
   * different element in a different position, so React threw the whole page
   * away and mounted it again 300 ms after load: every effect ran twice, every
   * uncached request went out twice, and anything typed or focused in that
   * window was lost.
   */
  return (
    <>
      {/* Splash overlay — fades out immediately after hydration */}
      {show && <div
        className={`fixed inset-0 z-[9999] flex items-center justify-center bg-white transition-opacity duration-300 ${
          fadeOut ? "opacity-0 pointer-events-none" : "opacity-100"
        }`}
        aria-hidden="true"
      >
        <div className="relative w-[148px] h-[69px] mobilescreen:w-[100px] mobilescreen:h-[44px]">
          <Image
            src="/assets/auth/logo.svg"
            alt="Fursa"
            fill
            sizes="(max-width: 768px) 100px, 148px"
            className="object-contain"
            priority
            unoptimized
          />
        </div>
      </div>}

      {/* Page content is rendered immediately — not blocked behind splash */}
      {children}
    </>
  );
}
