// CardColumns.tsx
import { User } from "@/constants/types";
import React, { useLayoutEffect, useRef } from "react";
import { useSelector } from "react-redux";

type ColumnCard = {
  id: string | number;
  name: string;
  image: string;
  price?: number;
  _i: number;
};

type Winner = { name: string } | null;

export type CardColumnsProps<TPhase extends string> = {
  selectedMode: number;

  columns: ColumnCard[][];
  winners: Winner[];

  columnRefs: React.MutableRefObject<(HTMLDivElement | null)[]>;
  phase: TPhase;

  CARD_W: number;
  columnOffsets: (number | null)[];
  segWidth: number;
  verticalClass: string;

  targetIndices: number[];
  centerIndices: number[];
  frozenY: number[];
  setFrozenY: React.Dispatch<React.SetStateAction<number[]>>;
  baseIndexById: Map<number, number>;
  spinValues: number[];
  backendRawValues: string[];
  winnerTrackByCol: number[];
  listRefs: React.MutableRefObject<(HTMLDivElement | null)[]>;
  winnerIdByCol: number[];
  stopAligned: boolean;
};

export function CardColumns<TPhase extends string>({
  baseIndexById,
  selectedMode,
  columns,
  winners,
  columnRefs,
  phase,
  CARD_W,
  columnOffsets,
  segWidth,
  verticalClass,
  targetIndices,
  centerIndices,
  frozenY,
  spinValues,
  backendRawValues,
  winnerTrackByCol,
  listRefs,
  setFrozenY,
  winnerIdByCol,
  stopAligned,
}: CardColumnsProps<TPhase>) {
  const user = useSelector((state: any) => state.auth.user) as User | null;

  const spinningPhases = [
    "accelerating",
    "fast",
    "slow",
    "slower",
    "slowest",
  ] as const;

  // useLayoutEffect(() => {
  //   // ✅ freeze only when entering stopping
  //   if (phase !== ("stopping" as TPhase)) return;

  //   setFrozenY((prev) => {
  //     const next = [...prev];

  //     columns.forEach((_, colIdx) => {
  //       const el = listRefs.current[colIdx];
  //       if (!el) return;

  //       const t = getComputedStyle(el).transform;
  //       let y = 0;

  //       // matrix(a,b,c,d,tx,ty)
  //       if (t && t !== "none") {
  //         const m = new DOMMatrix(t);
  //         y = m.m42; // ✅ translateY
  //       }

  //       next[colIdx] = y;
  //     });

  //     return next;
  //   });
  // }, [phase, columns, setFrozenY]);

  return (
    <div
      className={`flex px-2 items-center ${
        selectedMode === 1
          ? "justify-center"
          : "md:px-24 2xl:px-10 justify-evenly"
      } h-full`}
    >
      {columns.map((colCards, colIdx) => {
        const winner = winners[colIdx];
        const isStopped =
          phase === ("stopping" as TPhase) ||
          phase === ("showWinners" as TPhase);
        return (
          <div
            key={colIdx}
            ref={(el) => {
              columnRefs.current[colIdx] = el;
            }}
            className={`
  relative h-[300px] md:h-[380px] 2xl:h-[450px]
  flex items-center justify-center
  transition-[margin-top] duration-500 ease-out
  ${
    phase === ("stopping" as TPhase) || phase === ("showWinners" as TPhase)
      ? "mt-0"
      : colIdx % 2 === 1
      ? "-mt-40"
      : "mt-0"
  }
`}
            // style={{
            //   width: `${CARD_W}px`,
            //   // ✅ Apply transform on wrapper for smooth stop
            //   ...(phase === ("stopping" as TPhase) ||
            //   phase === ("showWinners" as TPhase)
            //     ? {
            //         transform:
            //           columnOffsets[colIdx] != null
            //             ? `translateY(${columnOffsets[colIdx]}px)`
            //             : "translateY(0px)",
            //         transition:
            //           "transform 1s cubic-bezier(0.22, 0.61, 0.36, 1)",
            //       }
            //     : {}),
            // }}
            style={{ width: `${CARD_W}px` }}
          >
            {/* BLUE GLOW */}
            <div
              className={`${
                phase === ("showWinners" as TPhase)
                  ? "-mt-20 md:mt-10 "
                  : colIdx % 2 === 1
                  ? "mt-20"
                  : "mt-0"
              } absolute top-1/2 left-1/2 transition-all duration-500
              -translate-y-1/2 -translate-x-1/2 md:w-25 w-12.5 h-12.5
              md:h-25 blur-2xl md:blur-3xl bg-[var(--color-blue)] rounded-full opacity-500`}
            />
            <div
              ref={(el) => {
                listRefs.current[colIdx] = el;
              }}
              className={`flex flex-col relative gap-10 ${
                isStopped ? "" : verticalClass
              }`}
              style={
                isStopped
                  ? ({
                      transform: `translateY(${
                        (frozenY[colIdx] ?? 0) + (columnOffsets[colIdx] ?? 0)
                      }px)`,
                      transition:
                        "transform 1s cubic-bezier(0.22, 0.61, 0.36, 1)",
                    } as React.CSSProperties)
                  : ({
                      ["--seg-v" as any]: `${-segWidth}px`,
                    } as React.CSSProperties)
              }
            >
              {colCards.map((card, cardIdx) => {
                const colWinnerTrack = winnerTrackByCol?.[colIdx] ?? -1;
                const colWinnerId = winnerIdByCol?.[colIdx] ?? -1;

                const isWinner =
                  (phase === "stopping" || phase === "showWinners") &&
                  // primary: exact visible copy chosen
                  ((colWinnerTrack >= 0 && card._i === colWinnerTrack) ||
                    // fallback: base winner id (always available from backend)
                    (colWinnerTrack < 0 &&
                      colWinnerId >= 0 &&
                      Number(card.id) === Number(colWinnerId)));

                const shouldHide =
                  phase === ("showWinners" as TPhase) &&
                  stopAligned &&
                  !isWinner;

                const isSpinningPhase = spinningPhases.includes(phase as any);

                const isCenter =
                  isSpinningPhase && centerIndices[colIdx] === cardIdx;

                const winnerAnimationClass =
                  phase === ("showWinners" as TPhase) && isWinner
                    ? cardIdx > centerIndices[colIdx]
                      ? "winner-animate-from-below"
                      : "winner-animate-from-above"
                    : "";

                return (
                  <div
                    key={`${card.id}-${cardIdx}`}
                    data-card-index={cardIdx}
                    data-card-id={card.id}
                    className={`shrink-0 flex flex-col items-center justify-center bg-white/0
                      transition-all duration-500 ${
                        shouldHide
                          ? "opacity-0 pointer-events-none"
                          : "opacity-100"
                      } ${winnerAnimationClass}`}
                  >
                    <img
                      src={`/cards${
                        card.image?.startsWith("/")
                          ? card.image
                          : `/${card.image}`
                      }`}
                      alt={card.name}
                      className={`w-12 object-contain h-16 md:w-28 md:h-40
                        transition-transform duration-300 ease-out
                        ${isWinner || isCenter ? "scale-115" : "scale-100"}`}
                    />

                    {phase === ("showWinners" as TPhase) && isWinner && (
                      <div className="text-center mt-3 md:mt-6 animate-fadeIn">
                        <h3 className="text-xs md:text-sm font-bold text-white">
                          {card.name.length > 15
                            ? card.name.slice(0, 15) + "..."
                            : card.name}
                        </h3>
                        <p className="text-xs flex items-center justify-center gap-1 md:text-lg font-extrabold text-[#FF0080]">
                          {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"
                            />
                          )}
                          {card.price ?? 0}
                        </p>
                        {/* <p className="text-[10px] md:text-xs opacity-80">
                          backendValue: {backendRawValues[colIdx] ?? "?"}
                          {" | "} baseIndex:{" "}
                          {(baseIndexById.get(Number(card.id)) ?? -1) + 1}
                          {" | "} trackIndex: {card._i}
                        </p> */}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
}
