"use client";
import { useState, useEffect } from "react";
import "./style.css";
import CutImage from "./CutImage";
import Slide from "./Modes/Slide";
import Flip from "./Modes/Flip";
import Turn from "./Modes/Turn";
import Link from "next/link";
import End from "./End";
import { BASE_URL } from "@/constants";
import { useSelector } from "react-redux";
import { useRouter } from "next/navigation";

export default function Anim({ user_id, mode, pack, cards, packId, brand }) {
  const [isAnimationPlaying, setIsAnimationPlaying] = useState();
  const [isPlay, setIsPlay] = useState();
  const [is_last, set_is_last] = useState(false);
  const [next, setNext] = useState({});
  const [pack_image, set_pack_image] = useState();
  const router = useRouter();
  const [muted, setMuted] = useState(false);
  const user = useSelector((state) => state.auth.user);

  useEffect(() => {
    if (pack?.cover_image) set_pack_image(pack.cover_image);
  }, [pack?.cover_image]);

  async function getNext() {
    try {
      const res = await fetch(BASE_URL + "/api/get-next-pack", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${user?.token}`,
        },
        body: JSON.stringify({ user_id: user_id, pack: packId }),
      });
      const data = await res.json();
      if (data.resp == "success") {
        if (data.pack.image != "") {
          data.pack.image = "/" + data.pack.image?.replace(/^\/+/, "");
        }
        setNext(data.pack);
      } else {
        setNext({});
      }
    } catch (err) {
      console.error("Error:", err);
      setNext({});
    }
  }

  const handleClose = () => {
    router.back(); // or router.push("/packs") if you want fixed page
  };

  const handleToggleSound = () => {
    setMuted((m) => !m);
  };

  useEffect(() => {
    if (!user?.token || !packId || !user_id) return;
    // getNext();
  }, [user?.token, packId, user_id]);

  return (
    <>
      <div className="cm-bg">
        <div className="main ">
          {/* sound button */}
          <button
            className="sound-btn-fixed "
            onClick={handleToggleSound}
            aria-label="Toggle sound"
          >
            {muted ? (
              <svg viewBox="0 0 24 24" className="hud-ico">
                <path d="M11 5L6.5 9H3v6h3.5L11 19V5Z" fill="currentColor" />
                <path
                  d="M16 9l5 6M21 9l-5 6"
                  stroke="currentColor"
                  strokeWidth="2.5"
                  strokeLinecap="round"
                />
              </svg>
            ) : (
              <svg viewBox="0 0 24 24" className="hud-ico">
                <path d="M11 5L6.5 9H3v6h3.5L11 19V5Z" fill="currentColor" />
                <path
                  d="M14.5 8.5c1.5 1.5 1.5 5.5 0 7"
                  stroke="currentColor"
                  strokeWidth="2.5"
                  strokeLinecap="round"
                />
                <path
                  d="M17.5 6c3 3 3 9 0 12"
                  stroke="currentColor"
                  strokeWidth="2.5"
                  strokeLinecap="round"
                />
              </svg>
            )}
          </button>

          <Link href="/inventory?packs=true" className="close-btn-fixed">
            Close
          </Link>
        </div>

        <div className="fixed inset-0 z-9999 flex items-center justify-center flex-col bg-black/60 backdrop-blur-sm">
          {isPlay ? (
            <>
              {mode == "slide" ? (
                <Slide pack={pack} cards={cards} set_is_last={set_is_last} />
              ) : mode == "flip" ? (
                <Flip pack={pack} cards={cards} set_is_last={set_is_last} />
              ) : mode == "turn" ? (
                <Turn
                  is_last={is_last}
                  mode={mode}
                  next={next}
                  pack={pack}
                  cards={cards}
                  set_is_last={set_is_last}
                  muted={muted}
                  getNext={getNext}
                />
              ) : null}
            </>
          ) : (
            <>
              {/* pack_image */}
              {pack_image ? (
                <>
                  <CutImage
                    isAnimationPlaying={isAnimationPlaying}
                    setIsAnimationPlaying={setIsAnimationPlaying}
                    setIsPlay={setIsPlay}
                    pack_image={pack_image}
                    cards={cards}
                    pack={pack}
                    muted={muted}
                  />
                </>
              ) : null}
            </>
          )}
        </div>
      </div>
    </>
  );
}

{
  /* {is_last && mode != "flip" ? (
          <End mode={mode} cards={cards} pack={next} />
        ) :null} */
}
