// eslint-disable-next-line no-unused-vars
import React, { useState, useEffect, useRef } from "react";
import {
  Text,
  Image,
  Box,
  Button, // eslint-disable-next-line no-unused-vars
  NumberIncrementStepper,
} from "@chakra-ui/react";
import { useNavigate } from "react-router-dom";
import { io } from "socket.io-client";
import "./Funroutlet.css";

// Importing images from Assest folder
import rouletteImage from "./Assest/roulette_2.png"; // eslint-disable-next-line no-unused-vars
import rouletteOuterImage from "./Assest/roulette_1.jpg"; // eslint-disable-next-line no-unused-vars
import rouletteInnerImage from "./Assest/brown_disk.png";
import rouletteInnerBackground from "./Assest/roulette_4.png";
import rouletteOuterRing from "./Assest/roulette_5.png";
// import roulette_3d from "./Assest/roulette_3d.png";
import score from "./Assest/score2.png"; // eslint-disable-next-line no-unused-vars
import score2 from "./Assest/score.png";

import winner from "./Assest/winner2.png";
import timerPng from "./Assest/timer2.png";
import balancePng from "./Assest/balancePng2.png";
import takePng from "./Assest/takePng2.png";
import betOkPng from "./Assest/betOkPng2.png";
import minBetPng from "./Assest/minBetPng.png";
import exitPng from "./Assest/exitPng.png";
import FunRouletteHeader from "./Assest/FunRouletteHeader.png"; // eslint-disable-next-line no-unused-vars
import Roulette_wheel from "./Assest/roulette_wheel.png";
import gloden_pattern1 from "./Assest/golden_pattern1.png"; // eslint-disable-next-line no-unused-vars
import gloden_pattern2 from "./Assest/golden_pattern2.png";
import Red_btn from "./Assest/Red_btn.png";
import Black_btn from "./Assest/black_btn.png";
import red_coin from "./Assest/red_coin.svg";
import blue_coin from "./Assest/blue_coin.svg";
import green_coin from "./Assest/green_coin.svg";
import purple_coin from "./Assest/purple_coin.svg";
import star from "./Assest/Group 52.png";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import wheel_ON from "./Assest/wheel_ON.png";
import tiltedWheel from "./Assest/wheel_ON.png";
import diamond from "./Assest/diamond.png"; // eslint-disable-next-line no-unused-vars
import golden_line from "./Assest/golden_line.png";
import { useMediaQuery } from "@chakra-ui/react";
const userId = localStorage.getItem("userId");
// const funRoutlet = import.meta.env.VITE_APP_FUN_ROULETTE;

console.log("userId", userId);
const socket = io("https://mahalaxmi-funroulette-backend.onrender.com", {
  query: {
    userID: userId,
  },
  transports: ["websocket"],
});
// const socket = io("http://localhost:8000/", {
//   query: {
//     userID: userId,
//   },
//   transports: ["websocket"],
// });

const roulette_numbers = [
  [
    ["3", "red", 0, false],
    ["6", "black", 0, false],
    ["9", "red", 0, false],
    ["12", "red", 0, false],
    ["15", "black", 0, false],
    ["18", "red", 0, false],
    ["21", "red", 0, false],
    ["24", "black", 0, false],
    ["27", "red", 0, false],
    ["30", "red", 0, false],
    ["33", "black", 0, false],
    ["36", "red", 0, false],
  ],
  [
    ["2", "black", 0, false],
    ["5", "red", 0, false],
    ["8", "black", 0, false],
    ["11", "black", 0, false],
    ["14", "red", 0, false],
    ["17", "black", 0, false],
    ["20", "black", 0, false],
    ["23", "red", 0, false],
    ["26", "black", 0, false],
    ["29", "black", 0, false],
    ["32", "red", 0, false],
    ["35", "black", 0, false],
  ],
  [
    ["1", "red", 0, false],
    ["4", "black", 0, false],
    ["7", "red", 0, false],
    ["10", "black", 0, false],
    ["13", "black", 0, false],
    ["16", "red", 0, false],
    ["19", "red", 0, false],
    ["22", "black", 0, false],
    ["25", "red", 0, false],
    ["28", "black", 0, false],
    ["31", "black", 0, false],
    ["34", "red", 0, false],
  ],
];
// const roulette_numbers = [
//   [
//     ["3", "red", 0, false, { h_split: "3-6", corners: ["3-6-2-5"] }],
//     ["6", "black", 0, false, { h_split: ["3-6", "6-9"], corners: ["3-6-2-5", "6-9-5-8"] }],
//     ["9", "red", 0, false, { h_split: ["6-9", "9-12"], corners: ["6-9-5-8", "9-12-8-11"] }],
//     ["12", "red", 0, false, { h_split: ["9-12", "12-15"], corners: ["9-12-8-11", "12-15-11-14"] }],
//     ["15", "black", 0, false, { h_split: ["12-15", "15-18"], corners: ["12-15-11-14", "15-18-14-17"] }],
//     ["18", "red", 0, false, { h_split: ["15-18", "18-21"], corners: ["15-18-14-17", "18-21-17-20"] }],
//     ["21", "red", 0, false, { h_split: ["18-21", "21-24"], corners: ["18-21-17-20", "21-24-20-23"] }],
//     ["24", "black", 0, false, { h_split: ["21-24", "24-27"], corners: ["21-24-20-23", "24-27-23-26"] }],
//     ["27", "red", 0, false, { h_split: ["24-27", "27-30"], corners: ["24-27-23-26", "27-30-26-29"] }],
//     ["30", "red", 0, false, { h_split: ["27-30", "30-33"], corners: ["27-30-26-29", "30-33-29-32"] }],
//     ["33", "black", 0, false, { h_split: ["30-33", "33-36"], corners: ["30-33-29-32", "33-36-32-35"] }],
//     ["36", "red", 0, false, { h_split: "33-36", corners: ["33-36-32-35"] }],
//   ],
//   [
//     ["2", "black", 0, false, { h_split: "2-5", corners: ["3-6-2-5", "2-5-1-4"] }],
//     ["5", "red", 0, false, { h_split: ["2-5", "5-8"], corners: ["3-6-2-5", "6-9-5-8", "2-5-1-4", "5-8-4-7"] }],
//     ["8", "black", 0, false, { h_split: ["5-8", "8-11"], corners: ["6-9-5-8", "9-12-8-11", "5-8-4-7", "8-11-7-10"] }],
//     ["11", "black", 0, false, { h_split: ["8-11", "11-14"], corners: ["9-12-8-11", "12-15-11-14", "8-11-7-10", "11-14-10-13"] }],
//     ["14", "red", 0, false, { h_split: ["11-14", "14-17"], corners: ["12-15-11-14", "15-18-14-17", "11-14-10-13", "14-17-13-16"] }],
//     ["17", "black", 0, false, { h_split: ["14-17", "17-20"], corners: ["15-18-14-17", "18-21-17-20", "14-17-13-16", "17-20-16-19"] }],
//     ["20", "black", 0, false, { h_split: ["17-20", "20-23"], corners: ["18-21-17-20", "21-24-20-23", "17-20-16-19", "20-23-19-22"] }],
//     ["23", "red", 0, false, { h_split: ["20-23", "23-26"], corners: ["21-24-20-23", "24-27-23-26", "20-23-19-22", "23-26-22-25"] }],
//     ["26", "black", 0, false, { h_split: ["23-26", "26-29"], corners: ["24-27-23-26", "27-30-26-29", "23-26-22-25", "26-29-25-28"] }],
//     ["29", "black", 0, false, { h_split: ["26-29", "29-32"], corners: ["27-30-26-29", "30-33-29-32", "26-29-25-28", "29-32-28-31"] }],
//     ["32", "red", 0, false, { h_split: ["29-32", "32-35"], corners: ["30-33-29-32", "33-36-32-35", "29-32-28-31", "32-35-31-34"] }],
//     ["35", "black", 0, false, { h_split: "32-35", corners: ["33-36-32-35", "32-35-31-34"] }],
//   ],
//   [
//     ["1", "red", 0, false, { h_split: "1-4", corners: ["2-5-1-4"] }],
//     ["4", "black", 0, false, { h_split: ["1-4", "4-7"], corners: ["2-5-1-4", "5-8-4-7"] }],
//     ["7", "red", 0, false, { h_split: ["4-7", "7-10"], corners: ["5-8-4-7", "8-11-7-10"] }],
//     ["10", "black", 0, false, { h_split: ["7-10", "10-13"], corners: ["8-11-7-10", "11-14-10-13"] }],
//     ["13", "black", 0, false, { h_split: ["10-13", "13-16"], corners: ["11-14-10-13", "14-17-13-16"] }],
//     ["16", "red", 0, false, { h_split: ["13-16", "16-19"], corners: ["14-17-13-16", "17-20-16-19"] }],
//     ["19", "red", 0, false, { h_split: ["16-19", "19-22"], corners: ["17-20-16-19", "20-23-19-22"] }],
//     ["22", "black", 0, false, { h_split: ["19-22", "22-25"], corners: ["20-23-19-22", "23-26-22-25"] }],
//     ["25", "red", 0, false, { h_split: ["22-25", "25-28"], corners: ["23-26-22-25", "26-29-25-28"] }],
//     ["28", "black", 0, false, { h_split: ["25-28", "28-31"], corners: ["26-29-25-28", "29-32-28-31"] }],
//     ["31", "black", 0, false, { h_split: ["28-31", "31-34"], corners: ["29-32-28-31", "32-35-31-34"] }],
//     ["34", "red", 0, false, { h_split: "31-34", corners: ["32-35-31-34"] }],
//   ],
// ];
// eslint-disable-next-line no-unused-vars
// const getAdjacentNumbers = (type, rowIndex, colIndex) => {
//   const numbers = [];

//   // Assuming 3 rows of 12 columns (3x12)
//   const rowCount = roulette_numbers.length;
//   const colCount = roulette_numbers[0].length;

//   switch (type) {
//     case "split-horizontal":
//       if (colIndex < colCount - 1)
//         numbers.push(
//           parseInt(roulette_numbers[rowIndex][colIndex][0]),
//           parseInt(roulette_numbers[rowIndex][colIndex + 1][0])
//         );
//       break;
//     case "split-vertical":
//       if (rowIndex < rowCount - 1)
//         numbers.push(
//           parseInt(roulette_numbers[rowIndex][colIndex][0]),
//           parseInt(roulette_numbers[rowIndex + 1][colIndex][0])
//         );
//       break;
//     case "street":
//       if (colIndex <= colCount - 3)
//         numbers.push(
//           parseInt(roulette_numbers[rowIndex][colIndex][0]),
//           parseInt(roulette_numbers[rowIndex][colIndex + 1][0]),
//           parseInt(roulette_numbers[rowIndex][colIndex + 2][0])
//         );
//       break;
//     case "corner":
//       if (rowIndex < rowCount - 1 && colIndex < colCount - 1)
//         numbers.push(
//           parseInt(roulette_numbers[rowIndex][colIndex][0]),
//           parseInt(roulette_numbers[rowIndex][colIndex + 1][0]),
//           parseInt(roulette_numbers[rowIndex + 1][colIndex][0]),
//           parseInt(roulette_numbers[rowIndex + 1][colIndex + 1][0])
//         );
//       break;
//     case "double-street":
//       if (rowIndex < rowCount - 1 && colIndex <= colCount - 3)
//         numbers.push(
//           ...[
//             parseInt(roulette_numbers[rowIndex][colIndex][0]),
//             parseInt(roulette_numbers[rowIndex][colIndex + 1][0]),
//             parseInt(roulette_numbers[rowIndex][colIndex + 2][0]),
//             parseInt(roulette_numbers[rowIndex + 1][colIndex][0]),
//             parseInt(roulette_numbers[rowIndex + 1][colIndex + 1][0]),
//             parseInt(roulette_numbers[rowIndex + 1][colIndex + 2][0]),
//           ]
//         );
//       break;
//     default:
//       break;
//   }

//   return numbers;
// };

const getCornerNumbers = (rowIndex, colIndex, board) => {
  try {
    const topLeft = parseInt(board[rowIndex][colIndex][0]);
    const topRight = parseInt(board[rowIndex][colIndex + 1][0]);
    const bottomLeft = parseInt(board[rowIndex + 1][colIndex][0]);
    const bottomRight = parseInt(board[rowIndex + 1][colIndex + 1][0]);

    return [topLeft, topRight, bottomLeft, bottomRight].sort((a, b) => a - b);
  } catch (e) {
    console.warn("Invalid corner indices", rowIndex, colIndex);
    return [];
  }
};

const handleSpecialBet = (type, rowIndex, colIndex) => {
  if (colIndex === undefined) {
    console.warn("Missing colIndex in handleSpecialBet");
    return;
  }
  const numbers = getAdjacentNumbers(type, rowIndex, colIndex);
  numbers.forEach((num) => handleBetClick(num));
};

// --- rowBet definition ---
const rowBet_initial = [
  [
    ["2 To 1", 0, false],
    ["2 To 1", 0, false],
    ["2 To 1", 0, false],
  ],
  [
    ["1st 12", 0, false],
    ["2nd 12", 0, false],
    ["3rd 12", 0, false],
  ],
  [
    ["1to18", 0, false],
    ["Even", 0, false],
    ["red", 0, false],
    ["black", 0, false],
    ["Odd", 0, false],
    ["19to36", 0, false],
  ],
];

// -- betTypes definition --
const betTypes = {
  green: {
    color: "green",
    numbers: [0],
  },
  red: {
    color: "red",
    numbers: [
      1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36,
    ],
  },
  black: {
    color: "black",
    numbers: [
      2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35,
    ],
  },
  even: { condition: (num) => num % 2 === 0 },
  odd: { condition: (num) => num % 2 !== 0 },
  "1to18": { range: [1, 18] },
  "19to36": { range: [19, 36] },
  first12: { range: [1, 12] },
  second12: { range: [13, 24] },
  third12: { range: [25, 36] },
  firstRow: { numbers: [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34] },
  secondRow: { numbers: [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35] },
  thirdRow: { numbers: [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36] },

  corner: {
    // All possible corner combinations (each 2x2 square on the roulette table)
    combinations: [
      [1, 2, 4, 5],
      [2, 3, 5, 6],
      [4, 5, 7, 8],
      [5, 6, 8, 9],
      [7, 8, 10, 11],
      [8, 9, 11, 12],
      [10, 11, 13, 14],
      [11, 12, 14, 15],
      [13, 14, 16, 17],
      [14, 15, 17, 18],
      [16, 17, 19, 20],
      [17, 18, 20, 21],
      [19, 20, 22, 23],
      [20, 21, 23, 24],
      [22, 23, 25, 26],
      [23, 24, 26, 27],
      [25, 26, 28, 29],
      [26, 27, 29, 30],
      [28, 29, 31, 32],
      [29, 30, 32, 33],
      [31, 32, 34, 35],
      [32, 33, 35, 36],
    ],
  },

  // Horizontal split combinations (adjacent numbers in the same row)
  horizontalSplit: {
    combinations: [
      [1, 2], [2, 3],
      [4, 5], [5, 6],
      [7, 8], [8, 9],
      [10, 11], [11, 12],
      [13, 14], [14, 15],
      [16, 17], [17, 18],
      [19, 20], [20, 21],
      [22, 23], [23, 24],
      [25, 26], [26, 27],
      [28, 29], [29, 30],
      [31, 32], [32, 33],
      [34, 35], [35, 36]
    ]
  },

  // Vertical split combinations (numbers in adjacent rows)
  verticalSplit: {
    combinations: [
      [1, 4], [4, 7], [7, 10], [10, 13], [13, 16], [16, 19], [19, 22], [22, 25], [25, 28], [28, 31], [31, 34],
      [2, 5], [5, 8], [8, 11], [11, 14], [14, 17], [17, 20], [20, 23], [23, 26], [26, 29], [29, 32], [32, 35],
      [3, 6], [6, 9], [9, 12], [12, 15], [15, 18], [18, 21], [21, 24], [24, 27], [27, 30], [30, 33], [33, 36]
    ]
  },

};
const FunRoulette = () => {
  const [winningNumber, setWinningNumber] = useState(null);
  const [user, setUser] = useState(null);
  const [isSpinning, setIsSpinning] = useState(false); // eslint-disable-next-line no-unused-vars
  const [betAmount, setBetAmount] = useState(0); // eslint-disable-next-line no-unused-vars
  const [betNumber, setBetNumber] = useState(null);
  const [balance, setBalance] = useState(1000); // Initial balance
  const [message, setMessage] = useState([
    "Please Bet to Start Game.",
    "green",
  ]);
  const TOAST_ID = "toast-functionality";
  const [gameState, setGameState] = useState({ value: "waiting" });
  const [gameHistory, setGameHistory] = useState(false);
  const [selectedCoin, setSelectedCoin] = useState(null); // eslint-disable-next-line no-unused-vars
  const [isGameStarted, setIsGameStarted] = useState(false); // eslint-disable-next-line no-unused-vars
  const [gameMatchId, setGameMatchId] = useState(null);
  // const [isBettingEnabled, setIsBettingEnabled] = useState(true);
  const [finalRotation, setFinalRotation] = useState(0);
  const [extraRotation, setExtraRotation] = useState(null);
  const [alignmentOffset, setAlignmentOffset] = useState(null);
  const [zoomOn, setZoomOn] = useState(false);
  // const [ballRotationCalled,setBallRotationCalled] = useState(false)
  const [userBetType, setUserBetType] = useState(null);
  const [winStatus, setWinStatus] = useState(true);
  const [btnDisable, setBtnDisable] = useState(false);
  const [timer, setTimer] = useState(null);
  const [display, setDisplay] = useState(false);
  const [userAmount, setUserAmount] = useState(0);
  const [userID, setUserID] = useState(null);
  const [amount, setTotalAmount] = useState(0);
  const [status, setStatus] = useState(true);

  // Refs to hold the latest state for use in intervals/timeouts
  const userRef = useRef(user);
  const amountRef = useRef(amount);
  const selectedCoinRef = useRef(selectedCoin);
  const predictiveAmountRef = useRef(null); // Ref for predictive total during hold
  const noBetConsecutiveRoundsRef = useRef(0); // Counter for consecutive no-bet rounds
  const navigate = useNavigate();

  useEffect(() => {
    userRef.current = user;
  }, [user]);
  useEffect(() => {
    amountRef.current = amount;
  }, [amount]);
  useEffect(() => {
    selectedCoinRef.current = selectedCoin;
  }, [selectedCoin]);

  const [zeroBetAmount, setZeroBetAmount] = useState(0); // New state for "0" bet amount
  // const [rouletteNumber, setRouletteNumber] = useState(roulette_numbers);
  // const [rowBet, setRowBet] = useState([[["2 To 1", 0, false], ["2 To 1", 0, false], ["2 To 1", 0, false]], [["1st 12", 0, false], ["2nd 12", 0, false], ["3rd 12", 0, false]], [["1to18", 0, false], ["Even", 0, false], ["red", 0, false], ["black", 0, false], ["Odd", 0, false], ["19to36", 0, false]]])
  // State for the betting board numbers and outside bets

  // Example roulette number order (this may vary depending on your wheel design)
  const rouletteNumbers = [
    0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 30, 8, 23, 10, 5,
    24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26,
  ];
  const numberOfSlots = rouletteNumbers.length;
  const degreesPerSlot = 360 / numberOfSlots;
  // const getAlignmentOffset = () => Math.floor(Math.random()*37) * degreesPerSlot;
  const ballRotation = () => {
    // if(ballRotationCalled){
    //   return
    // }
    // console.log("ballRotation Called!!")
    if (extraRotation !== null) {
      // setBallRotationCalled(true)
      return -3600 - alignmentOffset;
    }
  };
  const [rouletteNumber, setRouletteNumber] = useState(
    JSON.parse(JSON.stringify(roulette_numbers))
  ); // Deep copy
  const [rowBet, setRowBet] = useState(
    JSON.parse(JSON.stringify(rowBet_initial))
  ); // Deep copy

  // const handleSpecialBet = (type, rowIndex, colIndex) => {
  //   // const user = JSON.parse(localStorage.getItem("user"));
  //   if (selectedCoin === null) {
  //     toast.warn("Please select the bet amount", { /* ... toast options ... */ });
  //     return;
  //   }
  //   if (user?.coins < selectedCoin) {
  //     toast.warn("Insufficient Balance", { /* ... toast options ... */ });
  //     return;
  //   }

  //   const numbersToBet = getAdjacentNumbers(type, rowIndex, colIndex); // Use the existing helper function

  //   if (numbersToBet.length > 0) {
  //     console.log(`Placing ${type} bet on numbers:`, numbersToBet, "with amount:", selectedCoin);
  //     // Emit a bet for each number involved in the special bet
  //     setRouletteNumber(prev => {
  //       const newState = JSON.parse(JSON.stringify(prev));

  //       numbersToBet.forEach(num => {
  //         for (let row = 0; row < newState.length; row++) {
  //           for (let col = 0; col < newState[row].length; col++) {
  //             if (parseInt(newState[row][col][0]) === num) {
  //               newState[row][col][2] += selectedCoin;
  //               newState[row][col][3] = true;
  //             }
  //           }
  //         }

  //         // Send socket event for each number
  //         const betData = {
  //           userId: localStorage.getItem("userId"),
  //           matchId: gameState.matchId,
  //           betAmount: selectedCoin,
  //           betType: num,
  //           // You could also add `originalType: type` if backend needs it
  //         };
  //         console.log("betData", betData);
  //         socket.emit("betPlaced", betData);
  //       });

  //       return newState;
  //     });

  //     setMessage([`Placed ${type} bet`, "white"]);
  //   } else {
  //     console.warn(`Could not place ${type} bet at`, rowIndex, colIndex);
  //   }
  // };

  // const handleCornerBet = (rowIndex, colIndex) => {
  //   if (selectedCoin === null) {
  //     toast.warn("Please select the bet amount", {
  //       position: "top-center",
  //       autoClose: 5000,
  //       hideProgressBar: false,
  //       closeOnClick: true,
  //       pauseOnHover: true,
  //       draggable: true,
  //       progress: undefined,
  //       theme: "dark",
  //       toastId: TOAST_ID,
  //     });
  //     return;
  //   }
  //   if (user?.coins < selectedCoin * 4) {
  //     toast.warn("Insufficient Balance", {
  //       position: "top-center",
  //       autoClose: 5000,
  //       hideProgressBar: false,
  //       closeOnClick: true,
  //       pauseOnHover: true,
  //       draggable: true,
  //       progress: undefined,
  //       theme: "dark",
  //       toastId: TOAST_ID,
  //     });
  //     return;
  //   }

  //   // Check if the total bet amount (including the new corner bet) exceeds 100
  //   const newTotalAmount = amount + selectedCoin * 4;
  //   if (newTotalAmount > 10000) {
  //     toast.warn("1000 is the maximum bet limit!", {
  //       position: "top-center",
  //       autoClose: 5000,
  //       hideProgressBar: false,
  //       closeOnClick: true,
  //       pauseOnHover: true,
  //       draggable: true,
  //       progress: undefined,
  //       theme: "dark",
  //       toastId: TOAST_ID,
  //     });
  //     return;
  //   }

  //   const numbersToBet = getCornerNumbers(rowIndex, colIndex, rouletteNumber);

  //   const isValidCorner = betTypes.corner.combinations.some(
  //     (combo) =>
  //       combo.length === numbersToBet.length &&
  //       combo.every((num) => numbersToBet.includes(num))
  //   );

  //   if (!isValidCorner) {
  //     console.warn("Invalid corner bet at:", rowIndex, colIndex);
  //     toast.warn("Invalid corner position", {

  //     });
  //     return;
  //   }

  //   console.log(
  //     `Placing corner bet on numbers:`,
  //     numbersToBet,
  //     "with amount:",
  //     selectedCoin
  //   );

  //   setRouletteNumber((prev) => {
  //     const newState = JSON.parse(JSON.stringify(prev));

  //     numbersToBet.forEach((num) => {
  //       for (let row = 0; row < newState.length; row++) {
  //         for (let col = 0; col < newState[row].length; col++) {
  //           if (parseInt(newState[row][col][0]) === num) {
  //             newState[row][col][2] += selectedCoin; // Distribute bet visually (optional)
  //             newState[row][col][3] = true;
  //           }
  //         }
  //       }
  //     });

  //     const betData = {
  //       userId: localStorage.getItem("userId"),
  //       matchId: gameState.matchId,
  //       betAmount: selectedCoin * 4,
  //       betType: numbersToBet, // send entire corner group
  //       originalType: "corner",
  //     };
  //     console.log("betData", betData);
  //     socket.emit("betPlaced", betData);

  //     return newState;
  //   });

  //   setMessage([`Placed corner bet`, "white"]);
  // };

  // Function to handle user logout due to inactivity

  const handleLogout = () => {
    // Perform critical logout actions immediately
    localStorage.removeItem("userId");
    // localStorage.removeItem("token"); // If you use a token
    if (socket.connected) {
      socket.disconnect();
    }
    console.log(
      "User logged out due to inactivity (3 consecutive rounds without betting)."
    );

    // Show toast and then reload/redirect
    // You might want to use react-router-dom's navigate for a cleaner SPA navigation
    // navigate('/login');
    toast.warn("Logged out due to inactivity. Please log in again.", {
      position: "top-center",
      autoClose: 5000,
      hideProgressBar: false,
      closeOnClick: true,
      pauseOnHover: true,
      draggable: true,
      progress: undefined,
      theme: "dark",
      toastId: "logout-inactivity-toast",
      onClose: () => {
        window.location.reload(); // Reloads the page, effectively logging out
      },
    });
    navigate("/login");
  };

  const handleCancelBet = () => {
    setBetNumber(null);
    setMessage("Your bet has been canceled.");
  };
  useEffect(() => {
    const userID = localStorage.getItem("userId");
    // console.log("107", userID);
    if (userID) {
      socket.io.opts.query.userID = userID;
      socket.disconnect();
      socket.connect();
      socket.io.on("reconnect_attempt", () => {
        socket.io.opts.query.userID;
      });
    }
  }, [localStorage.getItem("userId")]);

  useEffect(() => {
    // Handler for game state updates
    const handleGameUpdate = (updatedGameState) => {
      // Set the entire gamestate object into state
      setGameState(updatedGameState?.gamestate);
      setTimer(updatedGameState?.gamestate?.value);
      console.log(updatedGameState?.gamestate?.value);

      // Extract matchId from the gamestate and update state
      const matchId = updatedGameState?.matchId;
      setGameMatchId(matchId); // No need for null check, just set it directly

      // Example logic (optional) to manipulate values or control UI:
      if (updatedGameState?.gamestate?.value - 25 === 20) {
        // Example: Reset the betting amount or disable a button
        // setBettingAmount(0);
        // setbuttonDisabled(true);
      }
    };

    const handleUserDetails = (data) => {
      // console.log("handleUserDetails.data", data);
      setUser(data?.user);
      setUserID(data?.user?.id);
    };
    handleUserDetails();

    const handleGameResult = (data) => {
      setBtnDisable(true);
      let { number, winnerbetType } = data;
      console.log(winnerbetType, "winnerBetType");
      spinRoulette(number);
      setSelectedCoin(null);
    };
    const handleGameHistory = (data) => {
      // setTimeout(() => {
      //   setGameHistory(data?.gamestate?.matchHistory.splice(0, 5));
      // }, 12000);
      setTimeout(() => {
        // Ensure data.gamestate.matchHistory exists and is an array
        const history = data?.gamestate?.matchHistory;
        if (Array.isArray(history)) {
          setGameHistory(history.slice(0, 5)); // Take last 10 results
        } else {
          setGameHistory([]); // Set empty if data is invalid
        }
      }, 17000);
    };

    const handelAmount = (data) => {
      // console.log("Users Amount:", data);
      if (data.Userdata[userId]) {
        setUserAmount(data.Userdata[userId]);
        console.log(data.Userdata[userId], "userAmount");
      } else {
        setUserAmount(0);
        console.log("userAmount not coming");
      }
    };

    const TotalAmount = (data) => {
      console.log("Total Bet Amount:", data);
      setTotalAmount(data.totalBetAmountOfUser);
    };

    // Listen for game state updates
    socket.on("gameUpdate", handleGameUpdate);
    socket.on("userDetails", handleUserDetails);
    socket.on("game_result", handleGameResult);
    socket.on("user_amount", handelAmount);
    socket.on("Total_bet_amount_of_user", TotalAmount);

    socket.on("history", handleGameHistory);
    return () => {
      socket.off("gameUpdate", handleGameUpdate);
      socket.off("userDetails", handleUserDetails);
      socket.off("game_result", handleGameResult);
      socket.off("user_amount", handelAmount);
      socket.off("Total_bet_amount_of_user", TotalAmount);

      socket.off("history", handleGameHistory);
    };
  }, []);

  if (timer === 61) {
    if (winStatus) {
      // === START NO-BET LOGOUT LOGIC ===
      if (amountRef.current === 0) {
        // No bet was placed in the round that just ended
        noBetConsecutiveRoundsRef.current += 1;
        console.log(
          `FunRoulette: Consecutive no-bet rounds: ${noBetConsecutiveRoundsRef.current}`
        );

        if (noBetConsecutiveRoundsRef.current === 2) {
          toast.warn(
            "Please place a bet this round, otherwise you will be logged out.",
            {
              position: "top-center",
              autoClose: 4000,
              hideProgressBar: false,
              closeOnClick: true,
              pauseOnHover: true,
              draggable: true,
              progress: undefined,
              theme: "dark",
              toastId: "funroulette-no-bet-warning",
            }
          );
        } else if (noBetConsecutiveRoundsRef.current >= 3) {
          handleLogout();
          // noBetConsecutiveRoundsRef.current = 0;
          // setWinStatus(false); // To prevent further execution of this block's logic if needed, though return does that.
          return; // Exit early as user is being logged out
        }
      } else {
        // A bet was placed in the round
        noBetConsecutiveRoundsRef.current = 0;
        console.log("FunRoulette: Bet placed, no-bet counter reset.");
      }
      // === END NO-BET LOGOUT LOGIC ===
      setTotalAmount(0);

      checkWinStatus(winningNumber);
      console.log("roulette number changing");
      setRouletteNumber([
        [
          ["3", "red", 0, false],
          ["6", "black", 0, false],
          ["9", "red", 0, false],
          ["12", "red", 0, false],
          ["15", "black", 0, false],
          ["18", "red", 0, false],
          ["21", "red", 0, false],
          ["24", "black", 0, false],
          ["27", "red", 0, false],
          ["30", "red", 0, false],
          ["33", "black", 0, false],
          ["36", "red", 0, false],
        ],
        [
          ["2", "black", 0, false],
          ["5", "red", 0, false],
          ["8", "black", 0, false],
          ["11", "black", 0, false],
          ["14", "red", 0, false],
          ["17", "black", 0, false],
          ["20", "black", 0, false],
          ["23", "red", 0, false],
          ["26", "black", 0, false],
          ["29", "black", 0, false],
          ["32", "red", 0, false],
          ["35", "black", 0, false],
        ],
        [
          ["1", "red", 0, false],
          ["4", "black", 0, false],
          ["7", "red", 0, false],
          ["10", "black", 0, false],
          ["13", "black", 0, false],
          ["16", "red", 0, false],
          ["19", "red", 0, false],
          ["22", "black", 0, false],
          ["25", "red", 0, false],
          ["28", "black", 0, false],
          ["31", "black", 0, false],
          ["34", "red", 0, false],
        ],
      ]);
      setRowBet([
        [
          ["2 To 1", 0, false],
          ["2 To 1", 0, false],
          ["2 To 1", 0, false],
        ],
        [
          ["1st 12", 0, false],
          ["2nd 12", 0, false],
          ["3rd 12", 0, false],
        ],
        [
          ["1to18", 0, false],
          ["Even", 0, false],
          ["red", 0, false],
          ["black", 0, false],
          ["Odd", 0, false],
          ["19to36", 0, false],
        ],
      ]);
      setWinStatus(false);
      setTimeout(() => {
        setWinStatus(true);
      }, 3000);
    }
  }
  if (timer === 56) {
    if (status) {
      setUserAmount(0);
      setStatus(false);
      setTimeout(() => {
        setStatus(true);
      }, 6000);
    }
  }

  if (gameState.value === 64) {
    socket.emit("updateUserAfterMatch");
  }
  // Wheel logic
  const spinRoulette = (number) => {
    setIsSpinning(true);
    setMessage("");
    setWinningNumber(false);
    // setZoomOn(true);
    const spinDuration = 16000; // Spin duration in milliseconds

    // Randomly select a winning number
    const winnerNumber = number;
    // console.log("winnerNumber", winnerNumber);
    // for ball to rotate extra
    setExtraRotation(winnerNumber);
    const winningIndex = rouletteNumbers.indexOf(winnerNumber);

    // Get the alignment offset for the winning number
    setAlignmentOffset(Math.floor(Math.random() * 37) * degreesPerSlot);
    // Calculate final rotation: 10 full spins + alignment for the winning number
    const finalRotationAngle = 3600 - winningIndex * degreesPerSlot;
    setFinalRotation(finalRotationAngle);

    // Set random winning number after spinning
    setTimeout(() => {
      // checkWin(winnerNumber); // Check win logic
      setIsSpinning(false); // Stop spinning
      setZoomOn(false);
      setBtnDisable(false);
      setWinningNumber(winnerNumber);

      // socket.emit("updateUserAfterMatch");
      // setBallRotationCalled(false)
    }, spinDuration);
  };

  // Coins
  const handleBetClick = (num) => {
    if (selectedCoin === null) {
      toast.warn("Please select the bet amount", {
        position: "top-center",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "dark",
        toastId: TOAST_ID,
      });
    } else if (user?.coins >= selectedCoin && selectedCoin !== null) {
      setIsGameStarted(true);
      setUserBetType(num);
      const obj = {
        userId: localStorage.getItem("userId"),
        matchId: gameState.matchId,
        betAmount: selectedCoin,
        betType: num,
      };
      socket.emit("betPlaced", obj);
      console.log(`betData for ${num}`, obj);
      switch (num) {
        case "first12":
          setMessage([`Amount ${selectedCoin} on 1st Dozen`, "white"]);
          break;
        case "second12":
          setMessage([`Amount ${selectedCoin} on 2nd Dozen`, "white"]);
          break;
        case "third12":
          setMessage([`Amount ${selectedCoin} on 3rd Dozen`, "white"]);
          break;
        case "firstRow":
          setMessage([`Amount ${selectedCoin} on 1st Column`, "white"]);
          break;
        case "secondRow":
          setMessage([`Amount ${selectedCoin} on 2nd Column`, "white"]);
          break;
        case "thirdRow":
          setMessage([`Amount ${selectedCoin} on 3rd Column`, "white"]);
          break;
        case "1to18":
          setMessage([`Amount ${selectedCoin} on Low`, "white"]);
          break;
        case "19to36":
          setMessage([`Amount ${selectedCoin} on High`, "white"]);
          break;
        default:
          setMessage([`Amount ${selectedCoin} on ${num}`, "white"]);
          break;
      }
      // Optionally, emit this updated score to the server
      // socket.emit("betPlaced", obj);
      // console.log("obj", obj);
    } else {
      toast.warn("Insufficient Balance", {
        position: "top-center",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "dark",
        toastId: TOAST_ID,
      });
    }
  };

  const holdTimerRef = useRef(null);

  // --- New Hold Function for Zero Bet ---

  const startHoldZeroBet = () => {
    // Initial Checks using refs
    if (!selectedCoinRef.current) {
      toast.warn("Please select the bet amount", { toastId: TOAST_ID });
      return;
    }
    if (userRef.current?.coins < selectedCoinRef.current) {
      toast.warn("Insufficient Balance", { toastId: TOAST_ID });
      clearInterval(holdTimerRef.current);
      return;
    }

    // Use a local variable to track the running total during hold
    let localZeroBetAmount = zeroBetAmount;

    // --- Bet Placement Logic for Zero ---
    const placeZeroBet = () => {
      if (userRef.current?.coins < selectedCoinRef.current) {
        console.warn(
          "Zero bet placement stopped due to insufficient balance just before emit."
        );
        clearInterval(holdTimerRef.current);
        return false;
      }
      if (localZeroBetAmount + selectedCoinRef.current > 5000) {
        toast.warn("5000 bet limit reached for number 0!", {
          toastId: TOAST_ID,
        });
        clearInterval(holdTimerRef.current);
        return false;
      }

      setIsGameStarted(true);
      setUserBetType(0);
      setMessage([`Amount ${selectedCoinRef.current} on 0`, "white"]);
      setZeroBetAmount((prev) => prev + selectedCoinRef.current);

      const betData = {
        userId: localStorage.getItem("userId"),
        matchId: gameState.matchId,
        betAmount: selectedCoin,
        betType: 0,
      };

      socket.emit("betPlaced", betData);
      console.log("betData for 0", betData);

      // Predictive Update
      amountRef.current += selectedCoinRef.current;
      if (userRef.current) userRef.current.coins -= selectedCoinRef.current;

      // Update local tracker
      localZeroBetAmount += selectedCoinRef.current;

      return true;
    };
    // --- End Bet Placement Logic ---

    if (!placeZeroBet()) return;

    // Start Interval
    holdTimerRef.current = setInterval(() => {
      if (!selectedCoinRef.current) {
        clearInterval(holdTimerRef.current);
        return;
      }
      if (userRef.current?.coins < selectedCoinRef.current) {
        toast.warn("Insufficient Balance", { toastId: TOAST_ID });
        clearInterval(holdTimerRef.current);
        return;
      }
      if (localZeroBetAmount + selectedCoinRef.current > 5000) {
        toast.warn("Maximum bet limit reached!", { toastId: TOAST_ID });
        clearInterval(holdTimerRef.current);
        return;
      }

      if (!placeZeroBet()) {
        clearInterval(holdTimerRef.current);
      }
    }, 1000);
  };
  //--- End New Hold Function for Zero Bet ---

  const stopHoldZeroBet = () => {
    clearInterval(holdTimerRef.current);
  };
  // --- End New Hold Function for Zero Bet ---
  // ... (Rest of the functions remain unchanged)

  // Update the reset logic when timer === 61
  if (timer === 61) {
    if (winStatus) {
      setTotalAmount(0);
      checkWinStatus(winningNumber);
      console.log("roulette number changing");
      setRouletteNumber([
        [
          ["3", "red", 0, false],
          ["6", "black", 0, false],
          ["9", "red", 0, false],
          ["12", "red", 0, false],
          ["15", "black", 0, false],
          ["18", "red", 0, false],
          ["21", "red", 0, false],
          ["24", "black", 0, false],
          ["27", "red", 0, false],
          ["30", "red", 0, false],
          ["33", "black", 0, false],
          ["36", "red", 0, false],
        ],
        [
          ["2", "black", 0, false],
          ["5", "red", 0, false],
          ["8", "black", 0, false],
          ["11", "black", 0, false],
          ["14", "red", 0, false],
          ["17", "black", 0, false],
          ["20", "black", 0, false],
          ["23", "red", 0, false],
          ["26", "black", 0, false],
          ["29", "black", 0, false],
          ["32", "red", 0, false],
          ["35", "black", 0, false],
        ],
        [
          ["1", "red", 0, false],
          ["4", "black", 0, false],
          ["7", "red", 0, false],
          ["10", "black", 0, false],
          ["13", "black", 0, false],
          ["16", "red", 0, false],
          ["19", "red", 0, false],
          ["22", "black", 0, false],
          ["25", "red", 0, false],
          ["28", "black", 0, false],
          ["31", "black", 0, false],
          ["34", "red", 0, false],
        ],
      ]);
      setRowBet([
        [
          ["2 To 1", 0, false],
          ["2 To 1", 0, false],
          ["2 To 1", 0, false],
        ],
        [
          ["1st 12", 0, false],
          ["2nd 12", 0, false],
          ["3rd 12", 0, false],
        ],
        [
          ["1to18", 0, false],
          ["Even", 0, false],
          ["red", 0, false],
          ["black", 0, false],
          ["Odd", 0, false],
          ["19to36", 0, false],
        ],
      ]);
      setZeroBetAmount(0); // Reset bet amount for "0"
      setWinStatus(false);
      setTimeout(() => {
        setWinStatus(true);
      }, 3000);
    }
  }
  // Function to start placing bet repeatedly while holding

  const startHoldBet = (num, rowIndex, colIndex) => {
    if (!selectedCoinRef.current) {
      toast.warn("Please select the bet amount", {
        position: "top-center",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "dark",
        toastId: TOAST_ID,
      });
      return;
    } else if (user?.coins < selectedCoin) {
      toast.warn("Insufficient Balance", {
        position: "top-center",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "dark",
        toastId: TOAST_ID,
      });
      return;
    }

    // Get the current bet amount for this cell
    let localBetAmount = rouletteNumber[rowIndex][colIndex][2];

    // Initial bet
    if (localBetAmount + selectedCoinRef.current <= 5000) {
      handleBetClick(num);
      setRouletteNumber((pre) => {
        const newState = JSON.parse(JSON.stringify(pre));
        if (!pre[rowIndex][colIndex][3]) {
          newState[rowIndex][colIndex][3] = true;
        }
        newState[rowIndex][colIndex][2] += selectedCoinRef.current;
        return newState;
      });

      // Predictive update
      amountRef.current += selectedCoinRef.current;
      if (userRef.current) userRef.current.coins -= selectedCoinRef.current;

      // Update local tracker
      localBetAmount += selectedCoinRef.current;
    } else {
      toast.warn(`Bet limit of 5000 reached for number ${num}!`, {
        position: "top-center",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "dark",
        toastId: TOAST_ID,
      });
      return;
    }

    holdTimerRef.current = setInterval(() => {
      if (!selectedCoinRef.current) {
        console.warn("Hold bet interval running without selected coin.");
        clearInterval(holdTimerRef.current);
        return;
      } else if (userRef.current?.coins < selectedCoinRef.current) {
        toast.warn("Insufficient Balance", {
          position: "top-center",
          autoClose: 5000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "dark",
          toastId: TOAST_ID,
        });
        clearInterval(holdTimerRef.current);
        return;
      }

      // Use localBetAmount to enforce the limit
      if (localBetAmount + selectedCoinRef.current <= 5000) {
        handleBetClick(num);
        setRouletteNumber((pre) => {
          const newPre = [...pre];
          newPre[rowIndex] = [...newPre[rowIndex]];
          newPre[rowIndex][colIndex] = [...newPre[rowIndex][colIndex]];
          if (!newPre[rowIndex][colIndex][3]) {
            newPre[rowIndex][colIndex][3] = true;
          }
          newPre[rowIndex][colIndex][2] += selectedCoinRef.current;
          return newPre;
        });

        // Predictive update
        amountRef.current += selectedCoinRef.current;
        if (userRef.current) userRef.current.coins -= selectedCoinRef.current;

        // Update local tracker
        localBetAmount += selectedCoinRef.current;

        console.log(
          "Placing bet on number:",
          num,
          "with amount (hold):",
          selectedCoinRef.current
        );
      } else {
        toast.warn(`Bet limit of 5000 reached for number ${num}!`, {
          position: "top-center",
          autoClose: 5000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "dark",
          toastId: TOAST_ID,
        });
        clearInterval(holdTimerRef.current);
      }
    }, 1000);
  };

  const startHoldBetExtra = (num, arrayIndex, index) => {
    // Initial bet
    if (!selectedCoinRef.current) {
      toast.warn("Please select the bet amount", {
        position: "top-center",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "dark",
        toastId: TOAST_ID,
      });
      return;
    } else if (userRef.current?.coins < selectedCoinRef.current) {
      toast.warn("Insufficient Balance", {
        position: "top-center",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "dark",
        toastId: TOAST_ID,
      });
      return; // Stop if not enough balance
    }
    // Use a local variable to track the running bet total for this cell
    let localOutsideBet = rowBet[arrayIndex][index][1];

    // Initial bet
    if (localOutsideBet + selectedCoinRef.current <= 5000) {
      handleBetClick(num);
      setRowBet((pre) => {
        const newState = JSON.parse(JSON.stringify(pre));
        if (!pre[arrayIndex][index][2]) {
          newState[arrayIndex][index][2] = true;
        }
        newState[arrayIndex][index][1] += selectedCoinRef.current; // Use ref
        return newState;
      });
      // --- Predictive Update (Initial Bet) ---
      amountRef.current += selectedCoinRef.current;
      if (userRef.current) userRef.current.coins -= selectedCoinRef.current;
      // --- End Predictive Update ---
      localOutsideBet += selectedCoinRef.current; // Update local tracker
    } else {
      toast.warn(`Bet limit of 5000 reached for ${num}!`, {
        position: "top-center",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "dark",
        toastId: TOAST_ID,
      });
      return;
    }

    holdTimerRef.current = setInterval(() => {
      if (!selectedCoinRef.current) {
        console.warn("Hold bet extra interval running without selected coin.");
        clearInterval(holdTimerRef.current);
        return;
      } else if (userRef.current?.coins < selectedCoinRef.current) {
        toast.warn("Insufficient Balance", {
          position: "top-center",
          autoClose: 5000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "dark",
          toastId: TOAST_ID,
        });
        clearInterval(holdTimerRef.current); // Stop hold betting
        return;
      }
      // Use localOutsideBet for the limit check
      if (localOutsideBet + selectedCoinRef.current <= 5000) {
        handleBetClick(num);
        setRowBet((pre) => {
          const newState = JSON.parse(JSON.stringify(pre));
          // Deep copy
          if (!newState[arrayIndex][index][2]) {
            newState[arrayIndex][index][2] = true;
          }
          newState[arrayIndex][index][1] += selectedCoinRef.current; // Use ref
          return newState;
        });

        // --- Predictive Update (Inside Interval) ---
        amountRef.current += selectedCoinRef.current;
        if (userRef.current) userRef.current.coins -= selectedCoinRef.current;
        // --- End Predictive Update --
        localOutsideBet += selectedCoinRef.current; // Update local tracker

        console.log(
          "Placing bet on number:",
          num,
          "with amount:",
          selectedCoinRef.current
        );
      } else {
        toast.warn(`Bet limit of 5000 reached for ${num}!`, {
          position: "top-center",
          autoClose: 5000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "dark",
          toastId: TOAST_ID,
        });
        clearInterval(holdTimerRef.current); // Stop hold betting
      }
    }, 1000); // Place bet every second while holding
  };

  // --- New Hold Function for Split Bets ---
  const startHoldSplitBet = (type, rowIndex, colIndex) => {
    // Get the numbers involved in the split bet
    const getSplitNumbers = (type, rowIndex, colIndex) => {
      if (type === "horizontal") {
        try {
          const leftNumber = parseInt(rouletteNumber[rowIndex][colIndex][0]);
          const rightNumber = parseInt(rouletteNumber[rowIndex][colIndex + 1][0]);
          return [leftNumber, rightNumber].sort((a, b) => a - b);
        } catch (e) {
          console.warn("Invalid horizontal split indices", rowIndex, colIndex);
          return [];
        }
      } else if (type === "vertical") {
        try {
          const topNumber = parseInt(rouletteNumber[rowIndex][colIndex][0]);
          const bottomNumber = parseInt(rouletteNumber[rowIndex + 1][colIndex][0]);
          return [topNumber, bottomNumber].sort((a, b) => a - b);
        } catch (e) {
          console.warn("Invalid vertical split indices", rowIndex, colIndex);
          return [];
        }
      }
      return [];
    };

    // Helper to get the current total bet for both numbers in the split
    const getSplitTotalBet = (numbers, board) => {
      let total = 0;
      numbers.forEach((num) => {
        const info = board.flat().find((n) => parseInt(n[0]) === num);
        if (info) total += info[2];
      });
      return total;
    };

    // --- Initial Checks ---
    const splitBetAmount = selectedCoinRef.current * 2; // Split bet is 2 numbers
    if (!selectedCoinRef.current) {
      toast.warn("Please select the bet amount", { toastId: TOAST_ID });
      return;
    }
    if (userRef.current?.coins < splitBetAmount) {
      toast.warn("Insufficient Balance for Split Bet", { toastId: TOAST_ID });
      return;
    }

    // --- Get split numbers and initial total ---
    const numbersToBet = getSplitNumbers(type, rowIndex, colIndex);
    if (numbersToBet.length !== 2) {
      toast.warn(`Invalid ${type} split position`, { toastId: TOAST_ID });
      return;
    }

    // Local tracker for running total during hold
    let localSplitTotal = getSplitTotalBet(numbersToBet, rouletteNumber);

    // --- Place Bet Helper ---
    const placeBet = () => {
      const currentSplitBetAmount = selectedCoinRef.current * 2;

      // Check balance
      if (userRef.current?.coins < currentSplitBetAmount) {
        toast.warn("Insufficient Balance for Split Bet (Hold Check)", {
          toastId: TOAST_ID,
        });
        clearInterval(holdTimerRef.current);
        return false;
      }

      // Check combined limit for both numbers
      if (localSplitTotal + currentSplitBetAmount > 5000) {
        toast.warn("Combined bet limit of 5000 reached for this split!", {
          toastId: TOAST_ID,
        });
        clearInterval(holdTimerRef.current);
        return false;
      }

      // Place the bet visually and update local tracker
      setRouletteNumber((prev) => {
        const newState = JSON.parse(JSON.stringify(prev));
        numbersToBet.forEach((num) => {
          for (let row = 0; row < newState.length; row++) {
            for (let col = 0; col < newState[row].length; col++) {
              if (parseInt(newState[row][col][0]) === num) {
                newState[row][col][2] += selectedCoinRef.current;
                newState[row][col][3] = true;
              }
            }
          }
        });
        return newState;
      });

      // Predictive update
      predictiveAmountRef.current += currentSplitBetAmount;
      if (userRef.current) userRef.current.coins -= currentSplitBetAmount;

      // Update local tracker
      localSplitTotal += currentSplitBetAmount;

      // Emit bet
      const betData = {
        userId: localStorage.getItem("userId"),
        matchId: gameState.matchId,
        betAmount: currentSplitBetAmount,
        betType: numbersToBet,
        originalType: type,
      };
      socket.emit("betPlaced", betData);
      console.log(`betData for ${type} split`, betData);

      return true;
    };

    // --- Initial Bet ---
    if (!placeBet()) return;

    // --- Start Hold Interval ---
    holdTimerRef.current = setInterval(() => {
      if (!selectedCoinRef.current) {
        clearInterval(holdTimerRef.current);
        predictiveAmountRef.current = null;
        return;
      }
      if (!placeBet()) {
        clearInterval(holdTimerRef.current);
      }
    }, 1000);
  };

  const stopHoldSplitBet = () => {
    clearInterval(holdTimerRef.current);
    predictiveAmountRef.current = null; // Reset predictive ref on stop
  };

  // --- End New Hold Function for Split Bets ---

  // --- New Hold Function for Corner Bets ---

  const startHoldCornerBet = (rowIndex, colIndex) => {
    const getCornerNumbers = (rowIndex, colIndex, board) => {
      try {
        const topLeft = parseInt(board[rowIndex][colIndex][0]);
        const topRight = parseInt(board[rowIndex][colIndex + 1][0]);
        const bottomLeft = parseInt(board[rowIndex + 1][colIndex][0]);
        const bottomRight = parseInt(board[rowIndex + 1][colIndex + 1][0]);
        return [topLeft, topRight, bottomLeft, bottomRight].sort(
          (a, b) => a - b
        );
      } catch (e) {
        console.warn("Invalid corner indices", rowIndex, colIndex);
        return [];
      }
    };

    // Helper to get the current total bet for all 4 numbers in the corner
    const getCornerTotalBet = (numbers, board) => {
      let total = 0;
      numbers.forEach((num) => {
        const info = board.flat().find((n) => parseInt(n[0]) === num);
        if (info) total += info[2];
      });
      return total;
    };

    // --- Initial Checks ---
    const cornerBetAmount = selectedCoinRef.current * 4;
    if (!selectedCoinRef.current) {
      toast.warn("Please select the bet amount", { toastId: TOAST_ID });
      return;
    }
    if (userRef.current?.coins < cornerBetAmount) {
      toast.warn("Insufficient Balance for Corner Bet", { toastId: TOAST_ID });
      return;
    }

    // --- Get corner numbers and initial total ---
    const numbersToBet = getCornerNumbers(rowIndex, colIndex, rouletteNumber);
    if (numbersToBet.length !== 4) {
      toast.warn("Invalid corner position", { toastId: TOAST_ID });
      return;
    }

    // Local tracker for running total during hold
    let localCornerTotal = getCornerTotalBet(numbersToBet, rouletteNumber);

    // --- Place Bet Helper ---
    const placeBet = () => {
      const currentCornerBetAmount = selectedCoinRef.current * 4;

      // Check balance
      if (userRef.current?.coins < currentCornerBetAmount) {
        toast.warn("Insufficient Balance for Corner Bet (Hold Check)", {
          toastId: TOAST_ID,
        });
        clearInterval(holdTimerRef.current);
        return false;
      }

      // Check combined limit for all 4 numbers
      if (localCornerTotal + currentCornerBetAmount > 5000) {
        toast.warn("Combined bet limit of 5000 reached for this corner!", {
          toastId: TOAST_ID,
        });
        clearInterval(holdTimerRef.current);
        return false;
      }

      // Place the bet visually and update local tracker
      setRouletteNumber((prev) => {
        const newState = JSON.parse(JSON.stringify(prev));
        numbersToBet.forEach((num) => {
          for (let row = 0; row < newState.length; row++) {
            for (let col = 0; col < newState[row].length; col++) {
              if (parseInt(newState[row][col][0]) === num) {
                newState[row][col][2] += selectedCoinRef.current;
                newState[row][col][3] = true;
              }
            }
          }
        });
        return newState;
      });

      // Predictive update
      predictiveAmountRef.current += currentCornerBetAmount;
      if (userRef.current) userRef.current.coins -= currentCornerBetAmount;

      // Update local tracker
      localCornerTotal += currentCornerBetAmount;

      // Emit bet
      const betData = {
        userId: localStorage.getItem("userId"),
        matchId: gameState.matchId,
        betAmount: currentCornerBetAmount,
        betType: numbersToBet,
        originalType: "corner",
      };
      socket.emit("betPlaced", betData);
      console.log("betData for corner", betData);

      return true;
    };

    // --- Initial Bet ---
    if (!placeBet()) return;

    // --- Start Hold Interval ---
    holdTimerRef.current = setInterval(() => {
      if (!selectedCoinRef.current) {
        clearInterval(holdTimerRef.current);
        predictiveAmountRef.current = null;
        return;
      }
      if (!placeBet()) {
        clearInterval(holdTimerRef.current);
      }
    }, 1000);
  };

  const stopHoldCornerBet = () => {
    clearInterval(holdTimerRef.current);
    predictiveAmountRef.current = null; // Reset predictive ref on stop
  };
  // --- End New Hold Function for Corner Bets ---

  // Function to stop placing bet
  const stopHoldBet = () => {
    clearInterval(holdTimerRef.current);
  };
  const stopHoldBetExtra = () => {
    clearInterval(holdTimerRef.current);
  };

  // Function to handle coin selection
  const handleBetSelection = (coinValue) => {
    setSelectedCoin(coinValue); // Store selected coin value
  };

  // Exit-button

  const handleExit = () => {
    navigate("/home");
  };

  function checkWinStatus(number) {
    let payout = 0;
    console.log(number, "number", userBetType, "userbettype");
    if (userBetType === null) {
      console.log("return");
      setMessage("");
      return;
    }
    // Check for each bet type
    if (userBetType === "red" && betTypes.red.numbers.includes(number)) {
      payout = betAmount * 2; // 1:1 payout
      setMessage([`Congratulations! You won.`, "green"]);
    } else if (
      userBetType === "black" &&
      betTypes.black.numbers.includes(number)
    ) {
      payout = betAmount * 2;
      setMessage([`Congratulations! You won.`, "green"]);
    } else if (userBetType === "even" && betTypes.even.condition(number)) {
      payout = betAmount * 2;
      setMessage([`Congratulations! You won.`, "green"]);
    } else if (userBetType === "odd" && betTypes.odd.condition(number)) {
      payout = betAmount * 2;
      setMessage([`Congratulations! You won.`, "green"]);
    } else if (
      userBetType === "1to18" &&
      number >= betTypes["1to18"].range[0] &&
      number <= betTypes["1to18"].range[1]
    ) {
      payout = betAmount * 2;
      setMessage([`Congratulations! You won.`, "green"]);
    } else if (
      userBetType === "19to36" &&
      number >= betTypes["19to36"].range[0] &&
      number <= betTypes["19to36"].range[1]
    ) {
      payout = betAmount * 2;
      setMessage([`Congratulations! You won.`, "green"]);
    } else if (
      userBetType === "first12" &&
      number >= betTypes.first12.range[0] &&
      number <= betTypes.first12.range[1]
    ) {
      payout = betAmount * 3; // 2:1 payout
      setMessage([`Congratulations! You won.`, "green"]);
    } else if (
      userBetType === "second12" &&
      number >= betTypes.second12.range[0] &&
      number <= betTypes.second12.range[1]
    ) {
      payout = betAmount * 3;
      setMessage([`Congratulations! You won.`, "green"]);
    } else if (
      userBetType === "third12" &&
      number >= betTypes.third12.range[0] &&
      number <= betTypes.third12.range[1]
    ) {
      payout = betAmount * 3;
      setMessage([`Congratulations! You won.`, "green"]);
    } else if (
      userBetType === "firstRow" &&
      betTypes.firstRow.numbers.includes(number)
    ) {
      payout = betAmount * 3;
      setMessage([`Congratulations! You won.`, "green"]);
    } else if (
      userBetType === "secondRow" &&
      betTypes.secondRow.numbers.includes(number)
    ) {
      payout = betAmount * 3;
      setMessage([`Congratulations! You won.`, "green"]);
    } else if (
      userBetType === "thirdRow" &&
      betTypes.thirdRow.numbers.includes(number)
    ) {
      payout = betAmount * 3;
      setMessage([`Congratulations! You won.`, "green"]);
    } else {
      setMessage([`You lost! Better luck next time.`, "red"]);
    }
    setUserBetType(null);
    setBalance(balance + payout - betAmount); // Update balance
  }

  useEffect(() => {
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;

    let portrate = window.matchMedia("(orientation:portrait)").matches;
    if (portrate) {
      setDisplay(true);
    }
    window.addEventListener("orientationchange", orientation);
    function orientation() {
      if (!window.matchMedia("(orientation:portrait)").matches) {
        setDisplay(true);
      } else {
        setDisplay(false);
      }
    }
    // if(portrate){
    //   console.log("portrait")
    //   const button = document.createElement('button');
    //   button.textContent = 'Enable Landscape Mode';
    //   button.style.padding = '10px';
    //   button.style.fontSize = '16px';
    //   button.onclick = autoRotateScreen;
    //   button.id="rotatebtn"
    //   document.body.appendChild(button);
    // }
    return () => {
      window.removeEventListener("orientationchange", orientation);
    };
  }, []);

  //autorotating screen in mobile
  // function autoRotateScreen() {
  //   // Check if the Screen Orientation API is supported
  //   if ('orientation' in screen && 'lock' in screen.orientation) {
  //       // Detect if the device is a mobile device
  //       const isMobile = /Mobi|Android/i.test(navigator.userAgent);

  //       if (isMobile) {
  //           // Try to lock the orientation to landscape
  //           screen.orientation.lock('landscape')
  //               .then(() => {
  //                   console.log('Screen orientation locked to landscape.');
  //               })
  //               .catch(err => {
  //                   console.error('Failed to lock screen orientation:', err);
  //               });
  //       } else {
  //           console.log('Screen orientation lock skipped (not a mobile device).');
  //       }
  //   } else {
  //       console.warn('Screen Orientation API is not supported in this browser.');
  //   }
  // }

  // Trigger the function after user interaction (e.g., on a button click)

  //huzafa
  const [showCoinTwo, setShowCoinTwo] = useState(false);
  useEffect(() => {
    if (timer <= 10) {
      setShowCoinTwo(false); // go back to coinone automatically
    }
  }, [timer]);

  return (
    <>
      <Box
        paddingInline={["4px", "4px", "4px", "10px"]}
        className="sm:px-[10px] md:px-[30px] text-center relative overflow-x-hidden "
        style={{
          background: "linear-gradient(rgb(0 22 0), rgb(0 58 1), rgb(0 20 0))",
        }}
      >
        <Box
          style={display ? { dispaly: "block" } : { display: "none" }}
          className="absolute bg-slate-900 top-0 left-0 h-[100vh] w-full z-50"
        >
          <Text className="text-white text-3xl mt-[30%]">
            Please rotate screen for better experience.
          </Text>
        </Box>

        <Box
          style={
            isSpinning
              ? { background: "rgba(0,0,0,0.8)" }
              : { background: "rgba(0,0,0,0)" }
          }
          left={"0"}
          top={"0"}
          className="absolute w-full h-full"
          transition={"all 0.3s"}
          zIndex={isSpinning ? 10 : -1}
        ></Box>

        <div className="w-full flex justify-center items-center">
          <Image
            className="golden-pattern"
            width={"20%"}
            height={["36px", "36px", "48px", "64px"]}
            opacity={"0.7"}
            src={gloden_pattern1}
          />
          <Image
            className="golden-pattern"
            width={"20%"}
            height={["36px", "36px", "48px", "64px"]}
            opacity={"0.7"}
            src={gloden_pattern1}
          />
          <Image
            marginBottom={["0.5rem", "0.5rem", "0.5rem", "1.25rem"]}
            className="block m-0 text-3xl text-[#B8860B] font-bold mb-5"
            width={"35%"}
            src={FunRouletteHeader}
            alt="Fun Roulette Game"
          />
          <Image
            className="golden-pattern"
            width={"20%"}
            height={["36px", "36px", "48px", "64px"]}
            opacity={"0.7"}
            src={gloden_pattern1}
          />
          <Image
            className="golden-pattern"
            width={"20%"}
            height={["36px", "36px", "48px", "64px"]}
            opacity={"0.7"}
            src={gloden_pattern1}
          />
        </div>

        {/* Score Text*/}
        <div className="flex justify-between w-[100%]">
          <div>
            <div className="text-left w-[100%]">
              {/* Score Section */}
              <Box
                // marginBottom={["0rem", "0rem", "0rem", "1rem"]}
                display={["none", "none", "block"]} // Hide on base and sm, show as block on md and up
                width={["129px", "129px", "129px", "225px"]}
                height={["55px", "55px", "55px", "80px"]}
                className="relative"
              >
                <div
                  className=" w-[100%] h-[100%] absolute top-0 left-0 z-0 bg-cover"
                  style={{
                    backgroundImage: `url(${score})`,
                    backgroundSize: "100% 100%",
                    backgroundPosition: "center",
                  }}
                />
                <Image
                  className="twinkling2"
                  position={"absolute"}
                  width={["24px", "24px", "24px", "unset"]}
                  left={["4%", "4%", "4%", "-5%"]}
                  top={["9%", "9%", "9%", "-15%"]}
                  src={star}
                />
                <Image
                  className="twinkling1"
                  position={"absolute"}
                  right={["-2%", "-2%", "-2%", "-5%"]}
                  bottom={["-9%", "-9%", "-9%", "-26%"]}
                  width={["27px", "27px", "27px", "65px"]}
                  src={star}
                />
                <div className=" relative z-[1] flex flex-col items-center justify-center h-[100%]">
                  <Box marginTop={["1rem", "1rem", "1rem", "1.5rem"]}>
                    <Text
                      fontSize={["1rem", "1rem", "1rem", "1.5rem"]}
                      className="bg-transparent text-white rounded-[50px] px-3 py-0 "
                    // style={{colorScheme:"blue",fontSize:"1.5rem"}}
                    >
                      {Math.round(user?.coins * 100) / 100 || "0"}
                    </Text>
                  </Box>
                </div>
              </Box>

              {/* Timer Section */}
              <Box
                width={["163px", "163px", "173px", "282px"]}
                left={["-4px", "-4px", "-7px", "-12px"]}
                height={["42px", "42px", "45px", "60px"]}
                className="relative"
              >
                <div
                  className="w-[100%] h-[100%] absolute top-0 left-0 z-0 bg-contain bg-no-repeat"
                  style={{
                    backgroundImage: `url(${timerPng})`,
                    backgroundPosition: "center",
                  }}
                />
                <Image
                  className="twinkling1"
                  position={"absolute"}
                  left={["3%", "3%", "3%", "2%"]}
                  top={["-24%", "-24%", "-24%", "-49%"]}
                  width={["27px", "27px", "27px", "52px"]}
                  src={star}
                />
                <Image
                  className="twinkling2"
                  position={"absolute"}
                  right={["3%", "3%", "3%", "2%"]}
                  bottom={["-9%", "-9%", "-9%", "-27%"]}
                  width={["30px", "30px", "30px", "58px"]}
                  src={star}
                />
                <div className=" relative z-[1] flex flex-col items-center justify-center h-[100%]">
                  <Box
                    marginBottom={["1.2rem", "1.2rem", "1.2rem", "1.75rem"]}
                    className="mb-7"
                  >
                    <Box
                      fontSize={["0.8rem", "0.8rem", "0.8rem", "1.2rem"]}
                      className="orbitron bg-transparent rounded-[50px] mt-2"
                      style={{
                        colorScheme: "yellow",
                        color: timer <= 10 ? "red" : "white",
                      }}
                    >
                      {typeof timer !== "number"
                        ? "Waiting..."
                        : timer > 60
                          ? 0
                          : `${timer}`}
                    </Box>
                  </Box>
                </div>
              </Box>
            </div>
          </div>
          <div className="flex items-end flex-col justify-end">
            {/* Winner Section */}
            <Box
              marginBottom={["0rem", "0rem", "0rem", "1.25rem"]}
              height={["58px", "58px", "58px", "80px"]}
              width={["159px", "159px", "159px", "225px"]}
              className="relative"
            >
              <Box
                width={["144px", "144px", "144px", "243px"]}
                height={["62px", "62px", "62px", "90px"]}
                className="winningNumber absolute top-0 right-0 z-0 bg-center bg-contain bg-no-repeat "
                style={{ backgroundImage: `url(${winner})` }}
              />
              <Image
                className="twinkling2"
                position={"absolute"}
                // left={["13%","13%","13%","-8%"]}
                top={["17%", "17%", "17%", "17%"]}
                width={["31px", "31px", "31px", "52px"]}
                left={["6%", "6%", "6%", "-8%"]}
                src={star}
              />
              <Image
                className="twinkling1"
                position={"absolute"}
                right={["4%", "4%", "4%", "-1%"]}
                top={["15%", "15%", "15%", "2%"]}
                width={["24px", "24px", "24px", "58px"]}
                src={star}
              />
              <div className="relative w-full z-[1] flex flex-col items-center justify-center h-full">
                <Box
                  left={["55%", "55%", "55%", "38%"]}
                  marginTop={["0rem", "0rem", "0rem", "2rem"]}
                  className="absolute translate-x-[-50%]"
                >
                  <Box
                    fontSize={["12px", "12px", "12px", "20px"]}
                    paddingTop={["23p", "23px", "23px", "12px"]}
                    className="bg-transparent text-white rounded-[50px] px-4 py-1"
                  >
                    {winningNumber ? `${winningNumber}` : "Waiting..."}
                  </Box>
                </Box>
              </div>
            </Box>

            {/* Balance Section */}
            <Box
              width={["163px", "163px", "169px", "282px"]}
              height={["42px", "42px", "37px", "60px"]}
              className="relative mb-[7px]"
            >
              <div
                className=" bg-center bg-cover w-full h-full absolute top-0 left-0 z-0"
                style={{
                  backgroundImage: `url(${balancePng})`,
                }}
              />
              <Image
                className="twinkling1"
                position={"absolute"}
                left={"0%"}
                top={"-49%"}
                width={["30px", "30px", "30px", "52px"]}
                src={star}
              />
              <Image
                className="twinkling2"
                position={"absolute"}
                right={"2%"}
                bottom={"-27%"}
                width={["30px", "30px", "30px", "58px"]}
                src={star}
              />
              <div className=" relative z-[1] flex flex-col items-center justify-center h-full ">
                <Box
                  fontSize={["13px", "13px", "13px", "18px"]}
                  marginBottom={["10px", "10px", "10px", "16px"]}
                  className="bg-transparent text-white rounded-[50px] flex items-center justify-center px-2 py-1 w-[70%]"
                  style={{
                    colorScheme: "yellow",
                  }}
                >
                  <Text className="p-1 flex justify-around items-center w-full">
                    {gameHistory
                      ? gameHistory.map((item, index) => {
                        return (
                          <Text
                            key={index}
                            fontWeight={700}
                            color={
                              index !== 0 && index !== 4
                                ? "white"
                                : index == 0
                                  ? "red"
                                  : "green"
                            }
                          >
                            {item}
                          </Text>
                        );
                      })
                      : "Waiting..."}
                  </Text>
                </Box>
              </div>
            </Box>
          </div>
        </div>

        <Box
          alignItems={["flex-start", "flex-start", "flex-start", "center"]}
          className="user_details w-full flex justify-between"
        >
          {" "}
          {/* This is the outer Box for the first pair of left/right sections */}
          <Box
            alignItems={["flex-start", "flex-start", "flex-start", "center"]}
            className="user_details w-full flex justify-between"
          >
            <div>
              {/* Coin Text */}
              <Box
                display={["none", "none", "block"]} // Hide on base and sm, show as block on md and up
                width={["239px", "239px", "239px", "300px"]}
                className=""
              // justifyContent="space-between"
              >
                <div className="betcoins flex-col w-[100%] flex">
                  {/* Coins on top */}
                  <Box
                    width={["84%", "84%", "84%", "100%"]}
                    marginBottom={["0rem", "0rem", "0rem", "1rem"]}
                    className="coins flex justify-between z-[9]"
                  >
                    {!showCoinTwo && (
                      <div
                        className="flex flex-col w-[100%] fade-slide-in"
                        id="coinone"
                        style={{
                          cursor: timer < 10 ? "not-allowed" : "pointer",
                        }}
                      >
                        <Box
                          gap={["0rem", "0rem", "0rem", "0.75rem"]}
                          className="flex w-[100%] flex-col justify-between"
                        >
                          <Box
                            width={"100%"}
                            className="anek-malayalam flex justify-around items-center h-[50px] bg-transparent rounded-r-[30px] p-2"
                          >
                            {[
                              {
                                value: 1,
                                color: "#08A105",
                                imageSrc: red_coin,
                              },
                              {
                                value: 5,
                                color: "#2a42a5",
                                imageSrc: blue_coin,
                              },
                              {
                                value: 10,
                                color: "#B010C2",
                                imageSrc: green_coin,
                              },
                              {
                                value: 50,
                                color: "#C51814",
                                imageSrc: purple_coin,
                              },
                            ].map((amount) => (
                              <Button
                                border={
                                  selectedCoin === amount.value
                                    ? "3px solid white"
                                    : ""
                                }
                                shadow={
                                  selectedCoin === amount.value
                                    ? "0px 0px 13px 0px white"
                                    : ""
                                }
                                key={amount.value}
                                width={["40px", "40px", "40px", "55px"]}
                                height={["40px", "40px", "40px", "55px"]}
                                transition={"transform 0.5s"}
                                _hover={{
                                  transform: timer < 10 ? "" : "scale(1.3)",
                                  border: timer < 10 ? "" : "3px solid white",
                                }}
                                background={`url(${amount.imageSrc})`}
                                backgroundPosition={"center"}
                                backgroundSize={"cover"}
                                color={"white"}
                                fontSize={["12px", "12px", "12px", "16px"]}
                                fontWeight="bold"
                                borderRadius="50%"
                                display="flex"
                                justifyContent="center"
                                alignItems="center"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  if (timer >= 10) {
                                    handleBetSelection(amount.value);
                                    setShowCoinTwo(true); // Show cointwo panel
                                  }
                                }}
                                style={{
                                  cursor:
                                    timer < 10 ? "not-allowed" : "pointer",
                                  opacity: timer < 10 ? 0.5 : 1,
                                }}
                                disabled={timer < 10}
                              >
                                {amount.value}
                              </Button>
                            ))}
                          </Box>
                          <Box
                            width={"100%"}
                            className="flex justify-around items-center anek-malayalam h-[50px] bg-transparent rounded-r-[30px] p-2"
                          >
                            {[
                              {
                                value: 100,
                                color: "#08A105",
                                imageSrc: red_coin,
                              },
                              {
                                value: 500,
                                color: "#2a42a5",
                                imageSrc: blue_coin,
                              },
                              {
                                value: 1000,
                                color: "#B010C2",
                                imageSrc: green_coin,
                              },
                              {
                                value: 5000,
                                color: "#C51814",
                                imageSrc: purple_coin,
                              },
                            ].map((amount) => (
                              <Button
                                border={
                                  selectedCoin === amount.value
                                    ? "3px solid white"
                                    : ""
                                }
                                shadow={
                                  selectedCoin === amount.value
                                    ? "0px 0px 13px 0px white"
                                    : ""
                                }
                                key={amount.value}
                                width={["40px", "40px", "40px", "55px"]}
                                height={["40px", "40px", "40px", "55px"]}
                                transition={"transform 0.5s"}
                                _hover={{
                                  transform: timer < 10 ? "" : "scale(1.3)",
                                  border: timer < 10 ? "" : "3px solid white",
                                }}
                                background={`url(${amount.imageSrc})`}
                                backgroundPosition={"center"}
                                backgroundSize={"cover"}
                                color={"white"}
                                fontSize={["12px", "12px", "12px", "16px"]}
                                fontWeight="bold"
                                borderRadius="50%"
                                display="flex"
                                justifyContent="center"
                                alignItems="center"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  if (timer >= 10) {
                                    handleBetSelection(amount.value);
                                    setShowCoinTwo(true); // Show cointwo panel
                                  }
                                }}
                                style={{
                                  cursor:
                                    timer < 10 ? "not-allowed" : "pointer",
                                  opacity: timer < 10 ? 0.5 : 1,
                                }}
                                disabled={timer < 10}
                              >
                                {amount.value}
                              </Button>
                            ))}
                          </Box>
                        </Box>
                      </div>
                    )}
                  </Box>

                  {/* Container for the Cancel Specific Bet button */}
                  <Box
                    width={["209px", "209px", "209px", "300px"]}
                    className="flex items-center justify-center mb-[13px]"
                  >
                    <div className="  w-[100%]  ">
                      {/* Background Image for Cancel Specific Bet */}
                      <Box
                        height={["39px", "39px", "39px", "59px"]}
                        className=" bg-cover rotate-180 bg-center w-full z-0"
                        style={{
                          backgroundImage: `url(${timerPng})`,
                        }}
                      >
                        <Image
                          className="twinkling1"
                          position={"absolute"}
                          left={"2%"}
                          top={"-49%"}
                          width={["38px", "38px", "38px", "52px"]}
                          src={star}
                        />
                        <Image
                          className="twinkling2"
                          position={"absolute"}
                          right={"2%"}
                          bottom={"-27%"}
                          width={["36px", "36px", "36px", "58px"]}
                          src={star}
                        />
                        <Box
                          fontSize={["10px", "10px", "10px", "14px"]}
                          paddingBottom={["5px", "5px", "5px", "8px"]}
                          className="rotate-180 bg-transparent text-white rounded-[50px] px-3"
                          style={{
                            colorScheme: "yellow",
                          }}
                        >
                          {userAmount}
                        </Box>
                      </Box>
                    </div>
                  </Box>
                  <Box
                    width={["209px", "209px", "209px", "300px"]}
                    className="flex items-center justify-center"
                  >
                    <div className="  w-[100%]  ">
                      {/* Background Image for Cancel Specific Bet */}
                      <Box
                        height={["39px", "39px", "39px", "59px"]}
                        className=" bg-cover relative bg-center w-[98%] z-0"
                        style={{
                          backgroundImage: `url(${timerPng})`,
                        }}
                      >
                        <Image
                          className="twinkling1"
                          position={"absolute"}
                          left={"2%"}
                          top={"-49%"}
                          width={["38px", "38px", "38px", "52px"]}
                          src={star}
                        />
                        <Image
                          className="twinkling2"
                          position={"absolute"}
                          right={"2%"}
                          bottom={"-27%"}
                          width={["36px", "36px", "36px", "58px"]}
                          src={star}
                        />
                        <Box
                          fontSize={["14px", "14px", "14px", "21px"]}
                          className="bg-transparent text-white rounded-[50px] pt-[3px] mb-2 px-3 py-1"
                          style={{
                            colorScheme: "yellow",
                          }}
                        >
                          {userID}
                        </Box>
                      </Box>
                    </div>
                  </Box>
                </div>
              </Box>
            </div>

            {/* winner section */}
            <Box
              height={["146px", "146px", "146px", "223px"]}
              width={["220px", "220px", "182px", "300px"]}
              marginBottom={["19px", "19px", "19px", "40px"]}
              marginTop={["1.8rem", "1.8rem", "1.8rem", "10px"]}
              className="Wheel89 playfair-display flex flex-col justify-between items-center"
            >
              {/* Row 1: Wheel Zoom button */}
              <Box
                width={["193px", "193px", "193px", "300px"]}
                marginBottom={["0rem", "0rem", "0rem", "2rem"]}
                height={["50px", "50px", "50px", "36px"]}
                className="playfair-display relative"
              >
                <Box
                  height={["42px", "42px", "42px", "59px"]}
                  className=" bg-cover rotate-180 bg-center w-full absolute top-0 left-0 z-0"
                  style={{
                    backgroundImage: `url(${timerPng})`,
                  }}
                >
                  <Image
                    className="twinkling2"
                    position={"absolute"}
                    left={["4%", "4%", "4%", "2%"]}
                    top={["-27%", "-27%", "-27%", "-49%"]}
                    width={["23px", "23px", "23px", "52px"]}
                    src={star}
                  />
                  <Image
                    className="twinkling1"
                    position={"absolute"}
                    right={["4%", "4%", "4%", "2%"]}
                    bottom={["-12%", "-12%", "-12%", "-27%"]}
                    width={["29px", "29px", "29px", "58px"]}
                    src={star}
                  />
                  <Box
                    paddingBottom={["19px", "19px", "19px", "23px"]}
                    className="relative z-[1] flex items-center justify-center h-full pb-[23px]"
                  >
                    <Button
                      fontSize={["0.7rem", "0.7rem", "0.7rem", "1rem"]}
                      // isDisabled={timer > 30 || timer === 0} // Keep timer-based disabling
                      colorScheme="yellow"
                      backgroundColor="transparent"
                      color="white"
                      border="none"
                      _hover={{ background: "none", border: "none" }}
                      borderRadius="50px"
                      transform="rotate(180deg)"
                      onClick={() => {
                        // if (isLargeScreen) {
                        //   setZoomOn((prev) => !prev); // Only toggle zoom on lg and larger
                        // }
                        setZoomOn((prev) => !prev); // Toggle zoom on all screen sizes
                        // Always trigger handleCointwoClick
                      }}
                      outline="none"
                      className="playfair-display"
                    >
                      Wheel Zoom: {zoomOn ? "ON" : "OFF"}
                    </Button>
                  </Box>
                </Box>
              </Box>

              <Box className="playfair-display flex flex-col sm:flex-row items-center justify-center gap-4 w-full mb-5">
                {/* Take Button */}
                <Box
                  position="relative"
                  w={["100px", "120px", "140px", "162px"]}
                  h={["28px", "30px", "34px", "36px"]}
                >
                  <Box
                    className="absolute top-0 left-0 w-full h-full bg-cover bg-center z-0"
                    style={{ backgroundImage: `url(${takePng})` }}
                  />
                  <Box
                    className="relative z-[1] flex items-center justify-center text-white text-center mt-1"
                    fontSize={["10px", "11px", "13px", "16px"]}
                    px={2}
                    w="100%"
                    h="100%"
                  >
                    Take
                  </Box>
                </Box>

                {/* Bet Ok Button */}
                <Box
                  position="relative"
                  w={["100px", "115px", "130px", "147px"]}
                  h={["28px", "30px", "32px", "34px"]}
                >
                  <Box
                    className="absolute top-0 left-0 w-full h-full bg-cover bg-center z-0"
                    style={{ backgroundImage: `url(${betOkPng})` }}
                  />
                  <Box
                    className="relative z-[1] flex items-center justify-center text-white text-center mt-[2px]"
                    fontSize={["10px", "11px", "12px", "14px"]}
                    px={2}
                    w="100%"
                    h="100%"
                  >
                    Bet Ok
                  </Box>
                </Box>
              </Box>

              {/* Row 3: Cancel Bet button */}
              <Box
                width={["199px", "199px", "199px", "280px"]}
                className="relative sm:h-[25px] mb-[5px] mt-[11px]"
              >
                {" "}
                {/* Custom width and height */}
                <Box
                  height={["43px", "43px", "43px", "64px"]}
                  className="bg-cover relative w-full bg-center top-0 left-0 z-0 "
                  style={{
                    backgroundImage: `url(${timerPng})`,
                  }}
                >
                  <Image
                    className="twinkling2"
                    position={"absolute"}
                    left={["4%", "4%", "4%", "-1%"]}
                    top={"-42%"}
                    width={["29px", "29px", "29px", "52px"]}
                    src={star}
                  />
                  <Image
                    className="twinkling1"
                    position={"absolute"}
                    right={["3%", "3%", "3%", "-1%"]}
                    bottom={["-21%", "-21%", "-21%", "-23%"]}
                    width={["32px", "32px", "32px", "58px"]}
                    src={star}
                  />
                  <div className="relative z-[1] flex items-center justify-center h-full">
                    <Box
                      fontSize={["14px", "14px", "14px", "18px"]}
                      paddingBottom={["0rem", "0rem", "0rem", "0.5rem"]}
                      paddingTop={["0.5rem", "0.5rem", "0.5rem", "0.5rem"]}
                      className="playfair-display cursor-not-allowed bg-transparent text-white rounded-[50px] px-4 py-2 mb-6"
                      style={{
                        colorScheme: "blue",
                      }}
                      onClick={handleCancelBet}
                    >
                      Cancel Bet
                    </Box>
                  </div>
                </Box>
              </Box>
            </Box>
          </Box>
          \
        </Box>
        {/* coins appear in the spiinie  */}
        <Box
          width={["230px", "230px", "170px", "460px"]}
          height={["230px", "230px", "170px", "250px"]}
          position="absolute"
          top="28%"
          left="50%"
          transform="translateX(-50%)"
          zIndex={9}
          className="coins flex justify-between"
        >
          {/* rest of coin UI */}
          {showCoinTwo && (
            <Box
              id="cointwo"
              width={["84%", "84%", "84%", "100%"]}
              marginBottom={["0rem", "0rem", "0rem", "1rem"]}
              className="coins flex justify-between z-[9] transition-opacity duration-500 ease-in-out opacity-100"
            >
              <div className="flex flex-col w-[100%] fade-slide-in ">
                <Box
                  gap={["0rem", "0rem", "0rem", "0.75rem"]}
                  className="flex w-[100%] flex-col justify-between"
                >
                  <Box
                    width={"100%"}
                    // background="rgb(245 222 167 / 70%)"
                    className="anek-malayalam flex justify-around items-center h-[50px] bg-transparent rounded-r-[30px] p-2"
                  >
                    {[
                      { value: 1, color: "#08A105", imageSrc: red_coin },
                      { value: 5, color: "#2a42a5", imageSrc: blue_coin },
                      { value: 10, color: "#B010C2", imageSrc: green_coin },
                      {
                        value: 50,
                        color: "#C51814",
                        imageSrc: purple_coin,
                      },
                    ].map((amount) => (
                      <Button
                        border={
                          selectedCoin === amount.value ? "3px solid white" : ""
                        }
                        shadow={
                          selectedCoin === amount.value
                            ? "0px 0px 13px 0px white"
                            : ""
                        }
                        key={amount.value}
                        // boxShadow={"5px 5px 8px -4px white inset,-4px -3px 6px -4px black inset"}
                        width={["40px", "40px", "40px", "55px"]}
                        height={["40px", "40px", "40px", "55px"]}
                        transition={"transform 0.5s"}
                        _hover={{
                          transform: "scale(1.3)",
                          border: "3px solid white",
                        }}
                        background={`url(${amount.imageSrc})`}
                        backgroundPosition={"center"}
                        backgroundSize={"cover"}
                        color={"white"}
                        fontSize={["12px", "12px", "12px", "16px"]}
                        fontWeight="bold"
                        borderRadius="50%"
                        display="flex"
                        justifyContent="center"
                        alignItems="center"
                        onClick={() => handleBetSelection(amount.value)}
                      >
                        {amount.value}
                      </Button>
                    ))}
                  </Box>
                  <Box
                    width={"100%"}
                    // background="rgb(245 222 167 / 70%)"
                    className="flex justify-around items-center anek-malayalam h-[50px] bg-transparent rounded-r-[30px] p-2"
                  >
                    {[
                      { value: 100, color: "#08A105", imageSrc: red_coin },
                      { value: 500, color: "#2a42a5", imageSrc: blue_coin },
                      {
                        value: 1000,
                        color: "#B010C2",
                        imageSrc: green_coin,
                      },
                      {
                        value: 5000,
                        color: "#C51814",
                        imageSrc: purple_coin,
                      },
                    ].map((amount) => (
                      <Button
                        border={
                          selectedCoin === amount.value ? "3px solid white" : ""
                        }
                        shadow={
                          selectedCoin === amount.value
                            ? "0px 0px 13px 0px white"
                            : ""
                        }
                        key={amount.value}
                        // boxShadow={"5px 5px 8px -4px white inset,-4px -3px 6px -4px black inset"}
                        width={["40px", "40px", "40px", "55px"]}
                        height={["40px", "40px", "40px", "55px"]}
                        transition={"transform 0.5s"}
                        _hover={{
                          transform: "scale(1.3)",
                          border: "3px solid white",
                        }}
                        background={`url(${amount.imageSrc})`}
                        backgroundPosition={"center"}
                        backgroundSize={"cover"}
                        color={"white"}
                        fontSize={["12px", "12px", "12px", "16px"]}
                        fontWeight="bold"
                        borderRadius="50%"
                        display="flex"
                        justifyContent="center"
                        alignItems="center"
                        onClick={() => handleBetSelection(amount.value)}
                      >
                        {amount.value}
                      </Button>
                    ))}
                  </Box>
                </Box>
              </div>
            </Box>
          )}
        </Box>

        {/* Spinner Component */}

        <Box height={["10px", "10px", "160px", "180px"]}>

          {!showCoinTwo && (
            <div
              // padd
              className={`absolute left-1/2 top-[10%] z-[11] translate-x-[-50%] transition-all duration-[500ms] ease-linear md:ml-[-25%] lg:ml-[-15%] md:mt-[-70px] lg:mt-[-50px] 
                ${isSpinning ? "Mainspinner active1" : "Mainspinner"} `}
              style={{

                transform: zoomOn && isSpinning ? "scale(2)" : "scale(1)",
                width: "min(90vw, 460px)",
                height: "min(82vw, 422px)",
              }}
            >
              {/* Zoomed Tilted Image */}
              <div
                style={{

                  transition: "transform 0.5s linear",
                }}
              >
                <img
                  className="absolute left-1/2 mb-2"
                  style={{
                    width: "499px",
                    maxWidth: "250%",
                    transform: "translateX(-50%)",
                    top: "80px",
                  }}
                  src={tiltedWheel}
                  alt="spinnerwheel"
                />

                {/* Spinning Wheel */}
                <div
                  className="absolute w-full h-full rounded-full bg-cover bg-center z-[2]"
                  style={{
                    backgroundImage: `url(${rouletteImage})`,
                    transform: isSpinning
                      ? `rotateX(-60deg) rotateZ(${finalRotation - alignmentOffset
                      }deg)`
                      : "rotateX(-60deg)",
                    transition: isSpinning
                      ? "transform 11s cubic-bezier(0.33, 0.7, 0.68, 1) 1.5s"
                      : "none",
                  }}
                ></div>

                {/* Diamond Center */}
                <div
                  className="absolute bg-cover bg-center rounded-full"
                  style={{
                    width: "85px",
                    height: "85px",
                    top: "45%",
                    left: "50%",
                    transform: "translate(-50%, -50%)",
                    backgroundImage: `url(${diamond})`,
                    zIndex: 16,
                  }}
                ></div>

                {/* Outer Ring */}
                <div
                  className="absolute w-full h-full rounded-full bg-cover bg-center z-[6]"
                  style={{
                    transform: "rotateX(60deg)",
                    backgroundImage: `url(${rouletteOuterRing})`,
                  }}
                ></div>

                {/* Balls */}
                <div
                  className="ball absolute bg-white rounded-full top-2/4 left-2/4 z-[10] hidden lg:block"
                  style={{
                    width: "14px",
                    height: "15px",
                    transform: `translate(-50%, -50%) rotateX(-60deg) rotateZ(${isSpinning ? ballRotation() : 0
                      }deg) translate(0px,-730%)`,
                    transition: isSpinning
                      ? "transform 11s cubic-bezier(0.33, 0.5, 0.68, 1) 1.5s"
                      : "none",
                  }}
                ></div>

                <div
                  className="ball absolute bg-white rounded-full top-2/4 left-2/4 z-[10] hidden md:block lg:hidden"
                  style={{
                    width: "10px",
                    height: "11px",
                    transform: `translate(-50%, -50%) rotateX(-60deg) rotateZ(${isSpinning ? ballRotation() : 0
                      }deg) translate(0px,-1055%)`,
                    transition: isSpinning
                      ? "transform 11s cubic-bezier(0.33, 0.5, 0.68, 1) 1.5s"
                      : "none",
                  }}
                ></div>

                {/* Inner Image */}
                <div
                  className="absolute bg-cover bg-center z-[4]"
                  style={{
                    width: "186px",
                    height: "242px",
                    top: "50%",
                    left: "50%",
                    transform: "translate(-50%, -50%) rotateX(-60deg)",
                    backgroundImage: `url(${rouletteInnerImage})`,
                  }}
                ></div>

                {/* Inner Background */}
                <div
                  className="absolute w-full h-full top-2/4 left-2/4 bg-cover bg-center z-[5]"
                  style={{
                    backgroundImage: `url(${rouletteInnerBackground})`,
                    transform: `translate(-50%, -50%) rotateX(-60deg) rotateZ(${isSpinning ? finalRotation - alignmentOffset : 0
                      }deg)`,
                    transition: isSpinning
                      ? "transform 11s cubic-bezier(0.33, 0.7, 0.68, 1) 1.5s"
                      : "none",
                  }}
                ></div>
              </div>
            </div>
          )}
        </Box>

        <Box className="md:mt-[-80px] lg:mt-[-10px] xl:mt-[-140px] 2xl:mt-[-140px] mt-[10px]  ">
          {/* <BettingBoard /> */}

          <div className="px-6 py-1 rounded-md mx-auto">
            {/* Roulette Table Layout */}
            <div className="flex justify-center">
              {/* Main Betting Board Container */}
              <Box
                height={["153px", "153px", "153px", "150px"]}
                className="grid grid-cols-14 grid-rows-1 w-full border-2 border-[#DDDA7D]"
              >
                {/* Zeros Column */}
                <div className="flex flex-col justify-evenly items-center col-span-1 h-full border-r-2 border-[#DDDA7D]">
                  {/* "0" Cell */}
                  <div
                    className="flex items-center justify-center h-full w-full relative"
                    onMouseDown={() => {
                      if (!btnDisable && timer >= 10) startHoldZeroBet();
                    }}
                    onMouseUp={stopHoldZeroBet}
                    onMouseLeave={stopHoldZeroBet}
                    style={
                      btnDisable || timer < 10
                        ? { opacity: 0.5, cursor: "not-allowed" }
                        : { opacity: 1, cursor: "pointer" }
                    }
                  >
                    <Box
                      width={["2.5rem", "2.5rem", "2.5rem", "3rem"]}
                      height={["1.5rem", "1.5rem", "1.5rem", "2.25rem"]}
                      className="bg-[#117605] text-[#F7B86A] flex items-center border-2 lg:border-[4px] border-[#FFC47B] justify-center h-7 w-6 lg:h-9 lg:w-12 font-bold rounded-[50%] shadow-[4px_3px_6px_-4px_white_inset,-4px_-3px_6px_-4px_black_inset]"
                    >
                      0
                    </Box>
                    {/* Bet Amount Display */}
                    <Box
                      position={"absolute"}
                      display={zeroBetAmount > 0 ? "flex" : "none"}
                      top={"50%"}
                      left={"50%"}
                      transform={"translate(-50%, -50%)"}
                      height={["20px", "20px", "20px", "24px"]}
                      minWidth={["20px", "20px", "20px", "24px"]}
                      borderRadius={"50%"}
                      fontSize={["10px", "10px", "10px", "12px"]}
                      background={
                        "linear-gradient(180.61deg, #FFF9DC 0.53%, #847218 99.47%)"
                      }
                      className="flex justify-center items-center text-black font-bold p-1"
                      zIndex={5}
                      style={
                        btnDisable || timer < 10
                          ? { opacity: 0.5, cursor: "not-allowed" }
                          : { opacity: 1 }
                      }
                    >
                      {zeroBetAmount}
                    </Box>
                  </div>
                </div>

                {/* Main Grid for Numbers 1-36 */}
                <div
                  className="grid grid-cols-12 col-span-12 h-full"
                  style={{
                    cursor:
                      btnDisable || timer < 10 ? "not-allowed" : "pointer",
                  }}
                >
                  {rouletteNumber.map((row, rowIndex) =>
                    row.map((number, colIndex) => (
                      <div key={`${rowIndex}-${colIndex}`} className="relative">
                        {/* Number Cell Click Area */}
                        <div
                          className="flex items-center justify-center h-[50px] lg:h-[49px] border border-[#DDDA7D]"
                          onMouseDown={() =>
                            !btnDisable &&
                            timer >= 10 &&
                            startHoldBet(
                              parseInt(number[0]),
                              rowIndex,
                              colIndex
                            )
                          }
                          onMouseUp={stopHoldBet}
                          onMouseLeave={stopHoldBet}
                          style={
                            btnDisable || timer < 10
                              ? { opacity: 0.5, cursor: "not-allowed" }
                              : { opacity: 1, cursor: "pointer" }
                          }
                        >
                          <Box
                            width={["2.5rem", "2.5rem", "2.5rem", "3rem"]}
                            height={["1.5rem", "1.5rem", "1.5rem", "2.25rem"]}
                            className={`flex items-center justify-center border-2 lg:border-[4px] border-[#FFC47B] lg:h-9 font-bold rounded-[50%] shadow-[4px_3px_6px_-4px_white_inset,-4px_-3px_6px_-4px_black_inset] ${number[1] === "red"
                                ? "bg-[#E53935] text-[#F7B86A] border-[#666666]"
                                : "bg-black text-[#F7B86A] border-[#FFC47B]"
                              }`}
                          >
                            {number[0]}
                          </Box>
                        </div>

                        {/* --- MOVED SPECIAL BET ELEMENTS START --- */}
                        {/* Split Bet Horizontal (Between this cell and the one to the right) */}
                        {colIndex < 11 && !btnDisable && ( // Check colIndex bounds and btnDisable
                          <div
                            className="absolute top-1/2 right-0 transform translate-x-1/2 -translate-y-1/2 w-3 h-3 bg-transparent rounded-full z-10 cursor-pointer hover:bg-transparent" // Added hover effect
                            title={`Split ${number[0]} / ${roulette_numbers[rowIndex][colIndex + 1][0]}`} // Dynamic title
                            onClick={(e) => e.stopPropagation()} // Prevent triggering the number cell click
                            onMouseDown={(e) => {
                              e.stopPropagation();
                              startHoldSplitBet("horizontal", rowIndex, colIndex);
                            }}
                            onMouseUp={() => stopHoldSplitBet()}
                            onMouseLeave={() => stopHoldSplitBet()}
                          ></div>
                        )}

                        {/* Split Bet Vertical (Between this cell and the one below) */}
                        {rowIndex < 2 && !btnDisable && ( // Check rowIndex bounds and btnDisable
                          <div
                            className="absolute bottom-0 left-1/2 transform -translate-x-1/2 translate-y-1/2 w-3 h-3 bg-transparent rounded-full z-10 hover:bg-transparent cursor-pointer" // Already has hover effect
                            title={`Split ${number[0]} / ${roulette_numbers[rowIndex + 1][colIndex][0]}`} // Dynamic title
                            onClick={(e) => e.stopPropagation()} // Prevent triggering the number cell click
                            onMouseDown={(e) => {
                              e.stopPropagation();
                              startHoldSplitBet("vertical", rowIndex, colIndex);
                            }}
                            onMouseUp={() => stopHoldSplitBet()}
                            onMouseLeave={() => stopHoldSplitBet()}
                          ></div>
                        )}

                        {/* Corner Bet */}
                        {rowIndex < 2 && colIndex < 11 && (
                          <div
                            className="absolute bottom-0 right-0 transform translate-x-1/2 translate-y-1/2 w-4 h-4 bg-transparent rounded-md z-10"
                            title={`Corner: ${number[0]} / ${roulette_numbers[rowIndex][colIndex + 1][0]
                              } / ${roulette_numbers[rowIndex + 1][colIndex][0]
                              } / ${roulette_numbers[rowIndex + 1][colIndex + 1][0]
                              }`}
                            onMouseDown={(e) => {
                              e.stopPropagation();
                              if (!btnDisable && timer >= 10)
                                startHoldCornerBet(rowIndex, colIndex);
                            }}
                            onMouseUp={(e) => {
                              e.stopPropagation();
                              stopHoldCornerBet();
                            }}
                            onMouseLeave={(e) => {
                              e.stopPropagation();
                              stopHoldCornerBet();
                            }}
                            style={{
                              cursor:
                                btnDisable || timer < 10
                                  ? "not-allowed"
                                  : "pointer",
                            }}
                          />
                        )}

                        {/* Bet Amount Display */}
                        <Box
                          position={"absolute"}
                          display={number[2] > 0 ? "flex" : "none"}
                          top={"50%"}
                          left={"50%"}
                          transform={"translate(-50%, -50%)"}
                          height={["20px", "20px", "20px", "24px"]}
                          minWidth={["20px", "20px", "20px", "24px"]}
                          borderRadius={"50%"}
                          fontSize={["10px", "10px", "10px", "12px"]}
                          background={
                            "linear-gradient(180.61deg, #FFF9DC 0.53%, #847218 99.47%)"
                          }
                          className="flex justify-center items-center text-black font-bold p-1"
                          zIndex={5}
                          onMouseDown={(e) => {
                            e.stopPropagation();
                            if (!btnDisable && timer >= 10 && number[2] > 0) {
                              startHoldBet(
                                parseInt(number[0]),
                                rowIndex,
                                colIndex
                              );
                            }
                          }}
                          onMouseUp={(e) => {
                            e.stopPropagation();
                            stopHoldBet();
                          }}
                          onMouseLeave={(e) => {
                            e.stopPropagation();
                            stopHoldBet();
                          }}
                          style={{
                            cursor:
                              number[2] > 0 && !btnDisable && timer >= 10
                                ? "pointer"
                                : "not-allowed",
                          }}
                        >
                          {number[2]}
                        </Box>
                      </div>
                    ))
                  )}
                </div>

                {/* "2 To 1" Column */}
                <div
                  className="flex flex-col justify-evenly items-center col-span-1 h-full"
                  style={{
                    cursor:
                      btnDisable || timer < 10 ? "not-allowed" : "pointer",
                  }}
                >
                  {rowBet[0].map((label, index) => (
                    <div
                      key={index}
                      className="relative text-xs lg:text-base bg-transparent text-white flex items-center justify-center h-1/3 w-full font-bold border border-[#DDDA7D]"
                      style={
                        btnDisable || timer < 10
                          ? { opacity: 0.5, cursor: "not-allowed" }
                          : { opacity: 1, cursor: "pointer" }
                      }
                      onMouseDown={() => {
                        if (btnDisable || timer < 10) return;
                        let type;
                        if (index === 0) type = "thirdRow";
                        else if (index === 1) type = "secondRow";
                        else type = "firstRow";
                        startHoldBetExtra(type, 0, index);
                      }}
                      onMouseUp={stopHoldBetExtra}
                      onMouseLeave={stopHoldBetExtra}
                    >
                      <div className="p-1">{label[0]}</div>
                      <Box
                        display={label[1] > 0 ? "flex" : "none"}
                        position={"absolute"}
                        top={"50%"}
                        left={"50%"}
                        transform={"translate(-50%, -50%)"}
                        height={["20px", "20px", "20px", "24px"]}
                        minWidth={["20px", "20px", "20px", "24px"]}
                        borderRadius={"50%"}
                        fontSize={["10px", "10px", "10px", "12px"]}
                        background={
                          "linear-gradient(180.61deg, #FFF9DC 0.53%, #847218 99.47%)"
                        }
                        className="flex justify-center items-center text-black font-bold p-1"
                        zIndex={5}
                      >
                        {label[1]}
                      </Box>
                    </div>
                  ))}
                </div>
              </Box>
            </div>

            {/* Footer Rows (Dozen Bets) */}
            <div
              className="grid grid-cols-12 gap-0 ml-[calc(100%/14)] mr-[calc(100%/14)] border border-[#DDDA7D] border-t-0 relative"
              style={{
                cursor: btnDisable || timer < 10 ? "not-allowed" : "pointer",
              }}
            >
              {rowBet[1].map((label, index) => (
                <div
                  key={index}
                  className="col-span-4 bg-transparent text-sm md:text-base lg:text-lg font-semibold text-[#37CD25] flex items-center justify-center border border-[#DDDA7D] relative h-[40px] lg:h-[50px]"
                  style={
                    btnDisable || timer < 10
                      ? { opacity: 0.5, cursor: "not-allowed" }
                      : { opacity: 1, cursor: "pointer" }
                  }
                  onMouseDown={() => {
                    if (btnDisable || timer < 10) return;
                    let type;
                    if (label[0] === "1st 12") type = "first12";
                    else if (label[0] === "2nd 12") type = "second12";
                    else type = "third12";
                    startHoldBetExtra(type, 1, index);
                  }}
                  onMouseUp={stopHoldBetExtra}
                  onMouseLeave={stopHoldBetExtra}
                >
                  <div className="p-1">{label[0]}</div>
                  <Box
                    display={label[1] > 0 ? "flex" : "none"}
                    position={"absolute"}
                    top={"50%"}
                    left={"50%"}
                    transform={"translate(-50%, -50%)"}
                    height={["20px", "20px", "20px", "24px"]}
                    minWidth={["20px", "20px", "20px", "24px"]}
                    borderRadius={"50%"}
                    fontSize={["10px", "10px", "10px", "12px"]}
                    background={
                      "linear-gradient(180.61deg, #FFF9DC 0.53%, #847218 99.47%)"
                    }
                    className="flex justify-center items-center text-black font-bold p-1"
                    zIndex={5}
                  >
                    {label[1]}
                  </Box>
                </div>
              ))}
            </div>

            {/* Bottom Footer (Even/Odd, Red/Black, Halves) */}
            <div
              className="grid grid-cols-6 gap-0 ml-[calc(100%/14)] mr-[calc(100%/14)] border border-[#DDDA7D] border-t-0 font-bold relative"
              style={{
                cursor: btnDisable || timer < 10 ? "not-allowed" : "pointer",
              }}
            >
              {rowBet[2].map((label, index) => (
                <div
                  key={index}
                  className="col-span-1 bg-transparent text-white flex items-center justify-center text-xs md:text-sm lg:text-base border border-[#DDDA7D] relative h-[40px] lg:h-[50px]"
                  style={
                    btnDisable || timer < 10
                      ? { opacity: 0.5, cursor: "not-allowed" }
                      : { opacity: 1, cursor: "pointer" }
                  }
                  onMouseDown={() => {
                    if (btnDisable || timer < 10) return;
                    const betType = label[0].toLowerCase().replace("to", "to");
                    startHoldBetExtra(betType, 2, index);
                  }}
                  onMouseUp={stopHoldBetExtra}
                  onMouseLeave={stopHoldBetExtra}
                >
                  <div className="p-1 flex items-center justify-center w-full h-full">
                    {label[0] === "red" || label[0] === "black" ? (
                      label[0] === "red" ? (
                        <Image
                          width={["50%", "50%", "40%"]}
                          src={Red_btn}
                          alt="Red Bet"
                        />
                      ) : (
                        <Image
                          width={["50%", "50%", "40%"]}
                          src={Black_btn}
                          alt="Black Bet"
                        />
                      )
                    ) : (
                      label[0]
                    )}
                  </div>
                  <Box
                    display={label[1] > 0 ? "flex" : "none"}
                    position={"absolute"}
                    top={"50%"}
                    left={"50%"}
                    transform={"translate(-50%, -50%)"}
                    height={["20px", "20px", "20px", "24px"]}
                    minWidth={["20px", "20px", "20px", "24px"]}
                    borderRadius={"50%"}
                    fontSize={["10px", "10px", "10px", "12px"]}
                    background={
                      "linear-gradient(180.61deg, #FFF9DC 0.53%, #847218 99.47%)"
                    }
                    className="flex justify-center items-center text-black font-bold p-1"
                    zIndex={5}
                  >
                    {label[1]}
                  </Box>
                </div>
              ))}
            </div>
          </div>

          <div className="flex relative items-center justify-center cursor-default">
            <Image height="50px" src={minBetPng} />
            <Box
              position={"absolute"}
              background={"black"}
              minWidth={"67%"}
              height={"53%"}
              letterSpacing={"3px"}
              fontSize={"19px"}
              top={["30%", "30%", "30%", "29%"]}
              color={message[1]}
              className="playfair-display"
            >
              {message[0]}
            </Box>
          </div>
          {/* Please Bet to Start Game. Minimum Bet=5 */}
          <div className="flex items-center justify-between relative">
            <Box
              height={["32px", "32px", "32px", "48px"]}
              className="bg-cover relative w-[200px] bg-center top-0 left-0 right-5 z-0 mt-[15px]"
              style={{
                backgroundImage: `url(${betOkPng})`,
              }}
            >
              <div className="relative z-[1] flex items-center justify-center h-full">
                <Box
                  fontSize={["12px", "12px", "12px", "14px"]}
                  paddingBottom={["0rem", "0rem", "0rem", "0.2rem"]}
                  paddingTop={["0.2rem", "0.2rem", "0.2rem", "1.3rem"]}
                  className="playfair-display m cursor-not-allowed bg-transparent text-white rounded-[50px] px-2 py-1 mb-4 flex justify-center items-center text-center w-full ml-[-5px] mt-4 lg:mt-0 "
                  style={{
                    colorScheme: "blue",
                  }}
                >
                  {amount}
                </Box>
              </div>
            </Box>
            <img
              src={exitPng}
              className="w-[16%] md:w-[16%] cursor-pointer"
              onClick={handleExit}
            />

            {/* Custom width and height */}
          </div>
        </Box>
      </Box>
      <ToastContainer
        position="top-center"
        autoClose={5000}
        hideProgressBar={false}
        newestOnTop={false}
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
        theme="dark"
        limit={1}
      />
    </>
  );
};

export default FunRoulette;