"use client";
import { useEffect, useRef } from "react";

// Shows a GIF (or falls back to the default sparkle/snow burst if none is
// set) plus an optional sound, for a capped duration. If the admin sets a
// display duration longer than the GIF's own real playback length, the
// popup only stays up for the GIF's actual length — never held open
// artificially longer than the animation itself runs.
export function SparkleBurst({ show, big = false }: { show: boolean; big?: boolean }) {
  if (!show) return null;
  const stars = Array.from({ length: big ? 30 : 16 });
  return (
    <div className="pointer-events-none fixed inset-0 z-[200] overflow-hidden">
      {stars.map((_, i) => {
        const left = Math.random() * 100;
        const delay = Math.random() * 0.4;
        const duration = 1.2 + Math.random() * 0.8;
        const size = (big ? 12 : 9) + Math.random() * (big ? 16 : 10);
        const symbol = Math.random() > 0.5 ? "✨" : "❄️";
        return (
          <span
            key={i}
            style={{
              position: "absolute",
              left: `${left}%`,
              top: "-5%",
              fontSize: size,
              animation: `sparkle-fall ${duration}s ease-in ${delay}s forwards`,
              opacity: 0,
            }}
          >
            {symbol}
          </span>
        );
      })}
      <style>{`
        @keyframes sparkle-fall {
          0% { transform: translateY(0) rotate(0deg); opacity: 0; }
          10% { opacity: 1; }
          100% { transform: translateY(110vh) rotate(360deg); opacity: 0; }
        }
      `}</style>
    </div>
  );
}

export function GifPopup({ src, show }: { src: string; show: boolean }) {
  if (!show || !src) return null;
  return (
    <div className="pointer-events-none fixed inset-0 z-[200] flex items-center justify-center">
      <img src={src} alt="" className="max-w-[60vw] max-h-[60vh] rounded-xl shadow-2xl animate-[gif-pop_0.3s_ease-out]" />
      <style>{`
        @keyframes gif-pop {
          0% { transform: scale(0.7); opacity: 0; }
          100% { transform: scale(1); opacity: 1; }
        }
      `}</style>
    </div>
  );
}

// Given an admin-configured display duration and the GIF's own real
// playback length (if the admin recorded one after uploading it), returns
// whichever is smaller — so the popup never outlasts the GIF itself.
export function cappedDuration(configuredSeconds: number, gifLengthSeconds?: string | number): number {
  const gifLen = typeof gifLengthSeconds === "string" ? parseFloat(gifLengthSeconds) : gifLengthSeconds;
  if (gifLen && !isNaN(gifLen) && gifLen > 0) {
    return Math.min(configuredSeconds, gifLen);
  }
  return configuredSeconds;
}

export function useCelebration() {
  const audioRef = useRef<HTMLAudioElement | null>(null);
  function play(soundUrl?: string) {
    if (soundUrl && audioRef.current) {
      audioRef.current.currentTime = 0;
      audioRef.current.play().catch(() => {});
    }
  }
  return { audioRef, play };
}
