import React, { useState, useEffect } from "react";
import { BorderButton, PrimaryButton } from "../ui/Button";
import { useSelector } from "react-redux";
import { getSocket } from "../utils/socket";

export const PackOpeningUI = ({
  def_cards,
  show_cards,
  gameState,
  setGameState,
  multiplier,
  phase,
  userId,
  onCashout,
}) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [overlayProgress, setOverlayProgress] = useState(100);
  const [cashout, setCashout] = useState("none");

  const [ncards, set_ncards] = useState([]);

  const BET = 0.01; // ✅ set your real bet here (image jaisa profit chahiye to 0.01)
  const profit = Math.max(0, (multiplier - 1) * BET);

  useEffect(()=>{
    let c = show_cards.length > 0 ? show_cards : def_cards;
    set_ncards(c);
  },[]);
  
  const user = useSelector((state) => state.auth.user);
  const handleCardClick = () => {
    if (gameState === "crashed" || gameState === "cashedout") return;

    const nextIndex = (currentIndex + 1) % ncards.length;

    setCurrentIndex(nextIndex);
    setOverlayProgress(100);
    // setMultiplier((prev) => prev + 0.4);
    // setWinAmount((prev) => prev + packs[nextIndex].value);
  };

  const handleCashout = () => {
    if (phase !== "multiplier") return;
    const socket = getSocket();
    socket.emit("cashoutGame", userId, ncards[currentIndex].id);

    setCashout("yes");
    setGameState("cashedout");
    onCashout?.();
  };

  const getCardPosition = (index) => {
    const diff = index - currentIndex;

    const isCrash = gameState === "crashed";

    if (diff === 0) return "-translate-x-0 scale-115 z-30";

    if (diff === -1)
      return `translate-x-[-230%] scale-90 opacity-100 z-10 ${
        isCrash ? "blur-xs" : ""
      }`;

    if (diff === -2)
      return `translate-x-[-360%] scale-90 opacity-100 z-10 ${
        isCrash ? "blur-xs" : ""
      }`;

    if (diff === 1)
      return "translate-x-[120%] scale-90 blur-xs opacity-70 z-20";

    if (diff === 2)
      return "translate-x-[240%] scale-90 blur-xs opacity-70 z-20";

    return "translate-x-[240%] scale-75 opacity-30 z-10";
  };

  useEffect(() => {
    if (gameState !== "opening") return; // sirf opening me chale
    if (overlayProgress <= 0) return;

    const interval = setInterval(() => {
      setOverlayProgress((prev) => Math.max(0, prev - 2));
    }, 10);

    return () => clearInterval(interval);
  }, [gameState, overlayProgress]);

  useEffect(() => {
    if (phase !== "multiplier") return;
    if (gameState !== "opening") return;

    const currentValue = multiplier;

    // find highest card index that user has reached
    let newIndex = currentIndex;

    for (let i = 0; i < ncards.length; i++) {
      if (currentValue >= ncards[i].price) {
        newIndex = i;
      } else {
        break;
      }
    }

    if (newIndex !== currentIndex) {
      setCurrentIndex(newIndex);
      setOverlayProgress(100); // reset reveal animation
    }
  }, [multiplier, phase, gameState, ncards]);

  return (
    <div className="flex flex-col relative z-20 items-between justify-between p-8 pt-0">
      {/* Cards Container */}
      <div
        className={`relative ${
          gameState === "crashed" ? "opacity-60" : "opacity-100"
        }  w-full`}
      >
        {ncards.map((pack, index) => (
          <div
            key={pack.id}
            // || gameState === "crashed"
            className={` absolute left-1/2 md:mt-8 2xl:mt-0 top-20 md:top-1/2 ${
              cashout === "yes" ? "md:w-full" : ""
            } -translate-x-1/2 -translate-y-1/2 transition-all duration-700 ease-out ${getCardPosition(
              index,
            )}`}
            onClick={index === currentIndex ? handleCardClick : null}
            style={{ cursor: index === currentIndex ? "pointer" : "default" }}
          >
            <div className="relative">
              {/* Card */}
              <img
                src={pack.image}
                alt={`${pack.name} trading card`}
                className="w-120 #transition-transform duration-300"
              />
              {/* Overlay that reveals from bottom -> top and freezes on crash */}
              {index === currentIndex &&
                overlayProgress > 0 &&
                cashout !== "yes" && (
                  <div
                    className="absolute inset-x-0 top-0 bg-black/90 pointer-events-none"
                    style={{
                      height: `${overlayProgress}%`, // 100 -> 0 (reveal happens bottom side)
                      transition: "height 120ms linear", // smooth animation
                    }}
                  />
                )}
            </div>
          </div>
        ))}
      </div>

      {/* Multiplier and Cashout */}

      <div
        className={`mt-42 md:mt-0 text-center ${
          cashout === "yes" ? "!mt-16" : "md:mt-28"
        } `}
      >
        {cashout === "yes" ? (
          <div className="font-sofia text-white mt-5 px-6 py-2 rounded-lg font-bold text-xl">
            {ncards[currentIndex]?.name}
          </div>
        ) : (
          <>
            {/* ${
                gameState === "crashed" && "!hidden"
              } */}
            <div
              className={`  text-6xl font-black text-white italic font-sofia animate-pulse`}
            >
              {multiplier}x
            </div>
          </>
        )}
        {user ? 
        <PrimaryButton
          className={`
    !bg-[#24C18D4F]
        mb-2 font-sofia font-bold text-md flex gap-1 md:text-base 2xl:text-xl
        ${gameState === "crashed" ? "opacity-0" : ""}
        ${cashout === "yes" ? "cashedout-animate" : "opening-animate"}
  `}
        >
          {profit >= 0 ? "+" : "-"}
          {user?.activeMode === "coins" ? (
            <img
              src="/images/header/win.svg"
              alt="win"
              aria-hidden="true"
              className="h-4 w-4"
            />
          ) : (
            <img
              src="/images/header/star.svg"
              alt="star"
              aria-hidden="true"
              className="h-4 w-4"
            />
          )}

          {Math.abs(profit).toFixed(2)}
        </PrimaryButton>
        : null }
        
        {cashout === "yes" ? (
          <>
            <div className="font-sofia md:mt-8 text-base md:text-4xl 2xl:text-5xl mb-2 font-black text-white italic animate-[bounceIn_0.8s_ease-out]">
              CASHED OUT!
            </div>
          </>
        ) : (
          
          <div className="flex justify-center gap-4">
            {user ? 
            <BorderButton
              className={`md:!px-10 !bg-[#24C18D] !text-[#13151A] ${
                phase !== "multiplier" ? "opacity-50 pointer-events-none" : ""
              }`}
              onClick={phase === "multiplier" ? handleCashout : undefined}
            >
              CASHOUT
            </BorderButton>
           : null }
          </div>
        )}
      </div>
    </div>
  );
};
