"use client";
import { useEffect, useRef, useState } from "react";
import { SparkleBurst, GifPopup, cappedDuration } from "@/components/Celebration";

export default function UpgradeSuccessCelebration({
  gif = "",
  gifLength = "",
  sound = "",
  durationSeconds = 3,
}: {
  gif?: string;
  gifLength?: string;
  sound?: string;
  durationSeconds?: number;
}) {
  const [show, setShow] = useState(true);
  const audioRef = useRef<HTMLAudioElement | null>(null);

  useEffect(() => {
    if (sound && audioRef.current) {
      audioRef.current.currentTime = 0;
      audioRef.current.play().catch(() => {});
    }
    const duration = cappedDuration(durationSeconds, gifLength);
    const t = setTimeout(() => setShow(false), duration * 1000);
    return () => clearTimeout(t);
  }, []);

  return (
    <>
      <GifPopup src={gif} show={show && !!gif} />
      <SparkleBurst show={show && !gif} big />
      {sound && <audio ref={audioRef} src={sound} preload="auto" />}
    </>
  );
}
