"use client";
import { User } from "@/constants/types";
import React, { useEffect, useState } from "react";

const ROUND_SECONDS = 5;
export const CoinflipGameViewModal: React.FC<{
  isOpen: boolean;
  onClose: () => void;
  game: any | null;
  currentUser: any;
  user: User | null;
  loadGames: () => void;
  joinGameLoading: boolean;
}> = ({
  isOpen,
  onClose,
  game,
  currentUser,
  user,
  loadGames,
  joinGameLoading,
}) => {
  const [secondsLeft, setSecondsLeft] = useState(ROUND_SECONDS);
  const [winner, setWinner] = useState<"left" | "right" | null>(null);
  const [phase, setPhase] = useState<
    "idle" | "countdown" | "flipping" | "done"
  >("idle");

  const left = game?.leftPlayer;
  const right = game?.rightPlayer;
  const leftLost = phase === "done" && winner === "right";
  const rightLost = phase === "done" && winner === "left";
  const leftWin = phase === "done" && winner === "left";
  const rightWin = phase === "done" && winner === "right";

  const isDone = phase === "done" && !!winner;

  const winnerPlayer =
    winner === "left" ? left : winner === "right" ? right : null;
  const loserPlayer =
    winner === "left" ? right : winner === "right" ? left : null;

  // winner side key (for title etc.)
  const winnerSide = winner; // "left" | "right" | null

  useEffect(() => {
    if (!isOpen) return;

    // ❗ game tabhi start hogi jab dono players hon
    if (!game?.leftPlayer || !game?.rightPlayer) {
      setPhase("idle");
      setWinner(null);
      setSecondsLeft(ROUND_SECONDS);
      return;
    }

    setPhase("countdown");
    setSecondsLeft(ROUND_SECONDS);
    setWinner(null);

    const countdown = setInterval(() => {
      setSecondsLeft((prev) => {
        if (prev <= 1) {
          clearInterval(countdown);
          setPhase("flipping");

          // flip ke baad result
          setTimeout(() => {
            const winKey = game?.winnerSide ?? game?.w; // ✅ backend returns "w"

            if (!winKey) return;

            const w =
              winKey === "player1"
                ? "left"
                : winKey === "player2"
                ? "right"
                : winKey === "left"
                ? "left"
                : winKey === "right"
                ? "right"
                : null;

            setWinner(w);
            setPhase("done");
          }, 3000);

          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(countdown);
  }, [isOpen, game?.leftPlayer, game?.rightPlayer, game?.winnerSide, game?.w]);

  const radius = 45;
  const circumference = 2 * Math.PI * radius;

  const progress = (ROUND_SECONDS - secondsLeft) / ROUND_SECONDS; // 0 → 1
  const dashOffset = circumference * (1 - progress); //  full → 0



  const ItemRow = ({ item }: { item: any }) => (
    <div className="bg-[#161B22] p-3 py-1 flex items-center gap-3 hover:bg-[#1C2128] transition">
      <div className="w-12 h-16 overflow-hidden">
        <img
          src={
            item.image?.includes("cardsimages")
              ? item.image.replace("cardsimages", "cards/images")
              : item.image?.startsWith("/cards")
              ? item.image
              : `/cards${item.image}`
          }
          className="object-contain"
          alt=""
        />
      </div>
      <div className="text-xs md:text-[15px] font-onest flex-1 min-w-0">
        <div className="text-white whitespace-pre-line">
          {item.name?.trim()?.split(/\s+/)?.slice(0, 2)?.join(" ") +
            (item.name?.trim()?.split(/\s+/).length > 2 ? "..." : "")}
        </div>
      </div>
      <div className="text-xs flex items-center gap-2 md:text-[15px] font-onest font-semibold text-(--color-pink)">
        {user?.activeMode === "coins" ? (
          <img src="/images/header/win.svg" alt="" className="h-4 w-4" />
        ) : (
          <img src="/images/header/star.svg" alt="" className="h-4 w-4" />
        )}
        {Number(item.price || 0).toFixed(2)}
      </div>
    </div>
  );

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/90 backdrop-blur-sm z-999999 flex items-center justify-center p-4">
      <div className="bg-(--color-naviBlue) box-shadow-custom w-full max-w-274.25 max-h-125 2xl:max-h-200 flex flex-col shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between px-6 pr-0 py-4 border-b-2 border-(--color-gray)">
          {/* <h2 className="text-sm md:text-xl font-onest font-semibold text-white">
            Coinflip {game?.id}
          </h2> */}
          <div className="flex items-center justify-between w-full gap-4">
            <button className="bg-[#2B5AFF26]    hover:bg-[#022850] px-6 py-2 rounded-lg font-bold text-sm md:text-base text-white transition uppercase">
              Provably Fair
            </button>
            <button
              onClick={() => {
                // close modal
                onClose();

                // ✅ only refresh if both players exist (game completed/joined)
                if (game?.leftPlayer && game?.rightPlayer) {
                  loadGames();
                }
              }}
              className="cursor-pointer"
            >
              <img
                src="/images/coinFlip/modal/cross.svg"
                alt=""
                className=" p-5"
              />
            </button>
          </div>
        </div>

        {/* Players Section */}
        <div className="px-6 py-4 2xl:py-6 border-b-2 border-(--color-gray)">
          <div className="flex flex-col md:flex-row gap-2 items-center justify-between">
            {/* Player 1 */}
            <div className="flex flex-1 items-center gap-4">
              <div className="w-12 md:w-20 md:h-20 h-12 rounded-full flex items-center justify-center text-3xl shadow-lg overflow-hidden">
                <img
                  // src={`${left.avatar}  /images/coinFlip/modal/player1.svg`}
                  src={left?.avatar || "/images/coinFlip/modal/player1.svg"}
                  alt=""
                />
              </div>
              {leftLost ? (
                <>
                  {/* LOST */}
                  <div className="text-red-500 text-xl font-bold"></div>
                </>
              ) : (
                <>
                  {leftWin ? (
                    <div className="text-green-500 text-xl font-bold">WIN</div>
                  ) : (
                    <div>
                      <div className="text-sm md:text-xl font-semibold font-onest text-white mb-1">
                        {left?.name}
                      </div>
                      <div className="flex text-xs md:text-base font-onest items-center gap-2">
                        <span className="font-bold flex items-center gap-2 text-(--color-pink)">
                          {user?.activeMode === "coins" ? (
                            <img
                              src="/images/header/win.svg"
                              alt=""
                              className="h-4 w-4"
                            />
                          ) : (
                            <img
                              src="/images/header/star.svg"
                              alt=""
                              className="h-4 w-4"
                            />
                          )}
                          {left?.amount.toFixed(2)}
                        </span>
                        <span className="text-[#DBFAFF]">
                          {left?.itemCount} Items
                        </span>
                      </div>
                    </div>
                  )}
                </>
              )}
            </div>

            {!joinGameLoading && left && right && (
              <>
                {/* Center: timer OR coin flip */}
                <div className="relative flex-1 flex items-center justify-center">
                  {/* COUNTDOWN RING */}
                  {phase === "countdown" && (
                    <div className="relative">
                      <svg className="w-10 h-10 md:w-22.5 md:h-22.5 -rotate-90">
                        <circle
                          cx="50%"
                          cy="50%"
                          r={radius + "%"}
                          fill="none"
                          stroke="#1f2937"
                          strokeWidth="4"
                        />
                        <circle
                          cx="50%"
                          cy="50%"
                          r={radius + "%"}
                          fill="none"
                          stroke="url(#gradient)"
                          strokeWidth="4"
                          strokeLinecap="round"
                          strokeDasharray={circumference}
                          strokeDashoffset={dashOffset}
                          style={{
                            transition: "stroke-dashoffset 1s linear",
                          }}
                        />
                        <defs>
                          <linearGradient
                            id="gradient"
                            x1="0%"
                            y1="0%"
                            x2="100%"
                            y2="100%"
                          >
                            <stop offset="0%" stopColor="#4D4CFE" />
                            <stop offset="100%" stopColor="#8b5cf6" />
                          </linearGradient>
                        </defs>
                      </svg>
                      <div className="absolute inset-0 flex items-center justify-center">
                        <span className="md:text-4xl 2xl:text-5xl font-bold text-white">
                          {secondsLeft}
                        </span>
                      </div>
                    </div>
                  )}

                  {/* COIN FLIP (3–4s) AND FINAL RESULT */}
                  {phase !== "countdown" && (
                    <div className="relative w-12 h-12 md:w-20 md:h-20 perspective-[1000px]">
                      <div
                        className={`
                absolute inset-0 rounded-full
                transform-3d
                ${phase === "flipping" ? "animate-coin-flip" : ""}
                  ${
                    phase === "done" && winner === "right" ? "rotate-y-180" : ""
                  }
              `}
                      >
                        {/* Front: player 1 */}
                        <img
                          src={
                            left?.avatar || "/images/coinFlip/modal/player1.svg"
                          }
                          alt=""
                          className="absolute inset-0 w-full h-full rounded-full backface-hidden"
                        />
                        {/* Back: player 2 */}
                        <img
                          src={
                            // "/images/coinFlip/modal/player2.svg"
                            right?.avatar ||
                            "/images/coinFlip/modal/player2.svg"
                          }
                          alt=""
                          className="absolute inset-0 w-full h-full rounded-full backface-hidden transform-[rotateY(180deg)]"
                        />
                      </div>
                    </div>
                  )}
                </div>
              </>
            )}

            {/* Player 2 (static info on the right) */}
            <div className="flex flex-1 items-center justify-end gap-4">
              {right ? (
                <>
                  {rightLost ? (
                    <>
                      {/* LOST */}
                      <div className="text-red-500 text-xl font-bold"></div>
                    </>
                  ) : (
                    <>
                      {rightWin ? (
                        <div className="text-green-500 text-xl font-bold">
                          WIN
                        </div>
                      ) : (
                        <div>
                          <div className="text-sm md:text-xl font-semibold font-onest text-white mb-1">
                            {right?.name}
                          </div>
                          <div className="flex text-xs md:text-base font-onest items-center gap-2">
                            <span className="font-bold flex items-center gap-2 text-(--color-pink)">
                              {user?.activeMode === "coins" ? (
                                <img
                                  src="/images/header/win.svg"
                                  alt=""
                                  className="h-4 w-4"
                                />
                              ) : (
                                <img
                                  src="/images/header/star.svg"
                                  alt=""
                                  className="h-4 w-4"
                                />
                              )}
                              {right?.amount.toFixed(2)}
                            </span>
                            <span className="text-[#DBFAFF]">
                              {right?.itemCount} Items
                            </span>
                          </div>
                        </div>
                      )}
                    </>
                  )}
                </>
              ) : (
                <div className="text-white/60 font-semibold">
                  No opponent yet...
                </div>
              )}

              <div className="w-12 md:w-20 md:h-20 h-12 rounded-full flex items-center justify-center text-3xl shadow-lg overflow-hidden">
                <img
                  // src={right?.avatar || "/images/coinFlip/modal/player2.svg"}
                  src={right?.avatar}
                  alt=""
                />
              </div>
            </div>
          </div>
        </div>

        {/* Items Section */}
        <div className="flex-1 no-scrollbar overflow-y-auto p-6">
          <div className="grid md:grid-cols-2 gap-2">
            {/* Player 1 Items */}
            <div>
              <div className="bg-(--color-gray) font-onest p-4 py-2 mb-2 flex items-center justify-between">
                <span className="text-xl font-bold text-white">
                  ${left?.amount.toFixed(2)}
                </span>
                <span className="text-sm ">{left?.items.length} items</span>
              </div>

              {/* Left items */}
              <div className="">
                {!leftLost ? (
                  <>
                    {left?.items.map((item: any) => (
                      <ItemRow key={`left-${item.id}`} item={item} />
                    ))}
                    {/* ✅ If LEFT is winner, show loser (RIGHT) items under it */}
                    {isDone &&
                      winnerSide === "left" &&
                      loserPlayer?.items?.length > 0 && (
                        <>
                          <div className="mt-3 mb-2 text-xs md:text-sm font-bold text-white/70">
                            Opponent&apos;s items won
                          </div>
                          {loserPlayer.items.map((item: any) => (
                            <ItemRow key={`won-${item.id}`} item={item} />
                          ))}
                        </>
                      )}
                  </>
                ) : (
                  <div className="text-center text-red-500 py-10 font-bold">
                    {/* LOST */}
                  </div>
                )}
              </div>
            </div>

            {/* Player 2 Items */}
            {left ? (
              <div>
                <div className="bg-(--color-gray) p-4 py-2 mb-2 font-onest flex items-center justify-between">
                  <span className="text-xl font-bold text-white">
                    ${right?.amount.toFixed(2)}
                  </span>
                  <span className="text-sm ">{right?.items.length} items</span>
                </div>

                <div>
                  {right ? (
                    <>
                      {!rightLost ? (
                        <>
                          {right?.items.map((item: any) => (
                            // <div
                            //   key={item.id}
                            //   className="bg-[#161B22] p-3 py-1 flex items-center gap-3 hover:bg-[#1C2128] transition"
                            // >
                            //   <div className="w-12 h-16 overflow-hidden">
                            //     <img
                            //       src={item.image.replace(
                            //         "cardsimages",
                            //         "cards/images"
                            //       )}
                            //       className="object-contain"
                            //       alt=""
                            //     />
                            //   </div>
                            //   <div className=" text-xs md:text-[15px] font-onest flex-1 min-w-0">
                            //     <div className=" text-white whitespace-pre-line">
                            //       {item.name
                            //         .trim()
                            //         .split(/\s+/)
                            //         .slice(0, 2)
                            //         .join(" ") +
                            //         (item.name.trim().split(/\s+/).length > 2
                            //           ? "..."
                            //           : "")}
                            //     </div>
                            //   </div>
                            //   <div className="text-xs md:text-[15px] font-onest font-semibold text-(--color-pink)">
                            //     ${item.price.toFixed(2)}
                            //   </div>
                            // </div>
                            <ItemRow key={`right-${item.id}`} item={item} />
                          ))}
                          {/* ✅ If RIGHT is winner, show loser (LEFT) items under it */}
                          {isDone &&
                            winnerSide === "right" &&
                            loserPlayer?.items?.length > 0 && (
                              <>
                                <div className="mt-3 mb-2 text-xs md:text-sm font-bold text-white/70">
                                  Opponent&apos;s items won
                                </div>
                                {loserPlayer.items.map((item: any) => (
                                  <ItemRow key={`won-${item.id}`} item={item} />
                                ))}
                              </>
                            )}
                        </>
                      ) : (
                        <div className="text-center text-red-500 py-10 font-bold">
                          {/* LOST */}
                        </div>
                      )}
                    </>
                  ) : (
                    <div className="text-center text-white/60 py-10">
                      Waiting for opponent...
                    </div>
                  )}
                </div>
              </div>
            ) : null}
          </div>
        </div>
      </div>
    </div>
  );
};
