"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import { AnimatePresence, motion } from "framer-motion";

/**
 * Global preloader — covers the viewport on first paint with the spinning
 * Cerkel mark, wordmark and a shimmer bar, then sweeps up and away. Scroll
 * is locked while visible. Pure client-side; shows once per full page load.
 */
const MIN_SHOW_MS = 1500;

export default function Preloader() {
  const [done, setDone] = useState(false);

  useEffect(() => {
    document.documentElement.style.overflow = "hidden";
    const t = setTimeout(() => {
      setDone(true);
      document.documentElement.style.overflow = "";
    }, MIN_SHOW_MS);
    return () => {
      clearTimeout(t);
      document.documentElement.style.overflow = "";
    };
  }, []);

  return (
    <AnimatePresence>
      {!done && (
        <motion.div
          exit={{ y: "-100%" }}
          transition={{ duration: 0.7, ease: [0.76, 0, 0.24, 1] }}
          className="fixed inset-0 z-[100] flex flex-col items-center justify-center bg-background"
          aria-hidden="true"
        >
          {/* logo + pulse halo */}
          <div className="relative flex h-24 w-24 items-center justify-center">
            <span className="absolute inset-0 animate-ping rounded-full bg-primary/15 [animation-duration:1.8s]" />
            <Image
              src="/images/CerkelLogo.png"
              alt=""
              width={64}
              height={64}
              priority
              className="h-16 w-16 animate-spin [animation-duration:2.6s]"
            />
          </div>

          <span className="mt-4 font-heading text-2xl font-semibold tracking-tight">
            Cerkel
          </span>

          {/* shimmer progress bar */}
          <div className="mt-6 h-0.5 w-44 overflow-hidden rounded-full bg-border">
            <motion.span
              initial={{ x: "-100%" }}
              animate={{ x: "200%" }}
              transition={{ repeat: Infinity, duration: 1.1, ease: "easeInOut" }}
              className="block h-full w-1/2 rounded-full bg-gradient-to-r from-primary to-accent"
            />
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
