'use client';

import { useEffect, useState } from 'react';
import { UefLoader } from '@/components/uef-loader';

/**
 * The splash shown while the site itself is loading — a browser refresh, a hard
 * refresh, or arriving at the site cold.
 *
 * app/loading.tsx cannot cover this: it only runs for navigations once React is
 * already mounted. On a fresh document load there is no React yet, so the first
 * paint would otherwise be a half-styled page.
 *
 * Deliberately short-lived. It clears as soon as the window reports its assets
 * are in, with a small floor so it registers as a moment rather than a flicker,
 * and a hard ceiling so a stalled image can never leave a visitor staring at a
 * logo. The overlay is painted, not conditional on JavaScript succeeding — if
 * this component somehow never mounts, nothing is covering the page.
 */
const MIN_VISIBLE = 500;
const MAX_VISIBLE = 2500;

export function PageLoader() {
  const [done, setDone] = useState(false);

  useEffect(() => {
    const started = performance.now();

    const finish = () => {
      const elapsed = performance.now() - started;
      const wait = Math.max(0, MIN_VISIBLE - elapsed);
      setTimeout(() => setDone(true), wait);
    };

    // `load` has usually already fired by the time React hydrates, so check
    // readyState first rather than waiting for an event that will never come.
    if (document.readyState === 'complete') finish();
    else window.addEventListener('load', finish, { once: true });

    // Backstop: never hold the page hostage to a slow asset.
    const ceiling = setTimeout(() => setDone(true), MAX_VISIBLE);

    return () => {
      window.removeEventListener('load', finish);
      clearTimeout(ceiling);
    };
  }, []);

  return (
    <div
      // Kept mounted through the fade so it does not vanish abruptly, then
      // pulled out of the accessibility tree and pointer events once hidden.
      aria-hidden={done}
      className={`fixed inset-0 z-[100] flex items-center justify-center bg-background
                  transition-opacity duration-500 ${
                    done ? 'pointer-events-none opacity-0' : 'opacity-100'
                  }`}
    >
      <UefLoader size={112} />
    </div>
  );
}
