"use client";

import { useEffect, useRef } from "react";
import gsap from "gsap";

export function CartridgeBoot({
  label,
  accent,
  onComplete,
}: {
  label: string;
  accent: string;
  onComplete: () => void;
}) {
  const root = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const ctx = gsap.context(() => {
      const tl = gsap.timeline({
        onComplete,
        defaults: { ease: "power2.inOut" },
      });
      gsap.set(".cart", { y: -180, opacity: 0 });
      gsap.set(".slot-glow", { opacity: 0 });
      gsap.set(".power-led", { opacity: 0.2 });
      gsap.set(".crt-flash", { opacity: 0 });

      tl.to(".cart", { y: 0, opacity: 1, duration: 0.55 })
        .to(".cart", { y: 42, duration: 0.35, ease: "power3.in" })
        .to(".slot-glow", { opacity: 0.8, duration: 0.15 }, "-=0.1")
        .to(".power-led", { opacity: 1, duration: 0.2 })
        .to(".crt-flash", { opacity: 0.35, duration: 0.12 })
        .to(".crt-flash", { opacity: 0.08, duration: 0.35 })
        .to({}, { duration: 0.35 });
    }, root);
    return () => ctx.revert();
  }, [onComplete]);

  return (
    <div ref={root} className="boot-stage">
      <div className="crt-flash absolute inset-0 bg-crt" />
      <div className="relative flex w-[min(92vw,420px)] flex-col items-center">
        <div
          className="cart relative z-10 mb-[-28px] h-36 w-28 rounded-sm border border-white/20 shadow-2xl"
          style={{
            background: `linear-gradient(160deg, ${accent}, #1a1a1a 70%)`,
          }}
        >
          <div className="absolute inset-x-3 top-3 border border-black/30 bg-black/40 px-2 py-3">
            <p className="font-display text-[0.45rem] leading-tight tracking-wide text-white/90 uppercase">
              {label}
            </p>
          </div>
          <div className="absolute inset-x-4 bottom-3 h-2 bg-black/50" />
        </div>
        <div className="relative w-full rounded-sm border border-white/10 bg-[#1a1f28] px-8 pb-6 pt-10 shadow-2xl">
          <div className="slot-glow absolute inset-x-10 top-6 h-3 rounded-sm bg-accent/40 blur-sm" />
          <div className="mx-auto h-3 w-40 rounded-sm bg-black/70" />
          <div className="mt-6 flex items-center justify-between">
            <span className="font-display text-[0.55rem] tracking-[0.2em] text-muted uppercase">
              Power
            </span>
            <span
              className="power-led h-2.5 w-2.5 rounded-full bg-crt shadow-[0_0_14px_var(--crt-green)]"
              style={{ animation: "power-pulse 0.9s ease-in-out infinite" }}
            />
          </div>
        </div>
        <p className="mt-8 font-display text-[0.55rem] tracking-[0.25em] text-muted uppercase">
          Inserting cartridge…
        </p>
      </div>
    </div>
  );
}
