"use client"
import { useState, useEffect } from "react";
import "./css/flip.css";
import { IMAGE_BASE } from "@/constants";

export default function Flip({ cards, pack, set_is_last }) {
  const [flipped, setFlipped] = useState(() => cards.map(() => false));
  const [slid, setSlid] = useState(() => cards.map(() => false));
  const [rev, setRev] = useState(0);

  useEffect(() => {
    setFlipped(cards.map(() => false));
    setSlid(cards.map(() => false));
  }, [cards.length]);

  const toggle = (i) => {
    setFlipped((prev) => {
      const copy = [...prev];
      if (!copy[i]) {
        copy[i] = true;

        // trigger slide after flip duration (0.6s)
        setTimeout(() => {
          setSlid((prevSlide) => {
            const slideCopy = [...prevSlide];
            slideCopy[i] = true;
            return slideCopy;
          });
          setRev(rev + 1);
        }, 600);
      }
      return copy;
    });
  };

  useEffect(() => {
    if (cards.length > 0 && cards.length == rev) {
      set_is_last(true);
    }
  }, [rev]);

  return (
    <div className="cards flipmode">
      <div className="in">
        {cards.map((c, index) => (
          <div
            className={`flip ${flipped[index] ? "flipped" : ""} ${
              slid[index] ? "slid" : ""
            }`}
            key={index}
            onClick={() => toggle(index)}
          >
            {/* <p className="text-white font-onest tracking-widest">
              {pack.brand}
            </p> */}
            <div className="flip-inner">
              <div className="flip-front">
                <img
                  src={
                    pack.brand === "MTG"
                      ? "/images/inventory/magicBack.webp"
                      : pack.brand === "Pokemon"
                      ? "/images/inventory/pokemonBack.png"
                      : "/images/inventory/lorcanaBack.png"
                  }
                  alt={`back-${index}`}
                  draggable="false"
                  className=""
                />
              </div>
              <div
                className={
                  c.probability === "Reverse Holofoil"
                    ? "card-image-wrapper  flip-back"
                    : "flip-back"
                }
              >
                <img
                  src={`${IMAGE_BASE}/${c.cover_image.replace(/^\/+/, "")}`}
                  alt={`front-${index}`}
                  draggable="false"
                  className="img-border-radius"
                />
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
