"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import { gsap, ScrollTrigger, prefersReducedMotion } from "./gsap-setup";

const DURATION = 1.4;

/**
 * Full-screen intro: the wordmark over a 000 -> 100 counter, then the panel
 * lifts away and hands control to the hero.
 *
 * Deliberately restrained — a brief, quiet hold rather than a display-scale
 * countdown, which is the register a financial platform can carry.
 *
 * The page content is fully rendered underneath the whole time — this is an
 * overlay, never a gate on rendering — so server-side copy and JSON-LD are
 * intact for crawlers even while the panel is up. Scrolling is locked for the
 * duration so the visitor cannot scroll blind behind the panel.
 */
export default function Preloader({ onDone }: { onDone: () => void }) {
  const rootRef = useRef<HTMLDivElement>(null);
  const counterRef = useRef<HTMLSpanElement>(null);
  const barRef = useRef<HTMLSpanElement>(null);
  const [hidden, setHidden] = useState(false);

  useEffect(() => {
    const root = rootRef.current;
    if (!root) return;

    const finish = () => {
      document.body.style.overflow = "";
      setHidden(true);
      // Section heights change when the panel leaves the flow; re-measure so
      // the first scroll triggers fire against the settled layout.
      ScrollTrigger.refresh();
      onDone();
    };

    if (prefersReducedMotion()) {
      finish();
      return;
    }

    document.body.style.overflow = "hidden";
    const progress = { value: 0 };

    const ctx = gsap.context(() => {
      const tl = gsap.timeline({ onComplete: finish });

      tl.to(progress, {
        value: 100,
        duration: DURATION,
        // Loading counters read as mechanical when linear; the slow-in/out
        // makes it feel like real work settling.
        ease: "power2.inOut",
        onUpdate() {
          const v = Math.round(progress.value);
          if (counterRef.current) {
            counterRef.current.textContent = String(v).padStart(3, "0");
          }
          if (barRef.current) barRef.current.style.width = `${v}%`;
        },
      })
        .to(".immersive-preloader__meta", {
          opacity: 0,
          duration: 0.28,
          ease: "power2.in",
        })
        .to(
          root,
          {
            yPercent: -100,
            duration: 0.9,
            ease: "expo.inOut",
          },
          "-=0.1"
        );
    }, rootRef);

    return () => {
      document.body.style.overflow = "";
      ctx.revert();
    };
  }, [onDone]);

  if (hidden) return null;

  return (
    <div
      ref={rootRef}
      // aria-hidden: the same information (and all real content) is already in
      // the document below, so this is decoration to a screen reader.
      aria-hidden
      className="fixed inset-0 z-[120] flex flex-col items-center justify-center bg-[hsl(222_24%_7%)] px-6"
    >
      <div className="immersive-preloader__meta flex w-full max-w-sm flex-col items-center">
        <Image
          src="/assets/logooxy.png"
          alt=""
          width={200}
          height={65}
          className="h-9 w-auto object-contain"
          priority
        />

        <span className="mt-10 block h-px w-full bg-white/10">
          <span ref={barRef} className="block h-px w-0 bg-[hsl(129_38%_50%)]" />
        </span>

        <div className="mt-4 flex w-full items-center justify-between">
          <span className="immersive-label">Loading</span>
          <span ref={counterRef} className="immersive-label tabular-nums">
            000
          </span>
        </div>
      </div>
    </div>
  );
}
