"use client";

import { useEffect, useState, useMemo, useRef } from "react";
import OgBox from "@/app/components/mystery-packs/OgBox";
import PokemonBoxSpinner from "@/app/components/spin/PokemonBoxSpinner";
import { useSearchParams } from "next/navigation";
import { BOXES } from "@/app/components/data/dummyData";
import "./home.css";
import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import NotAvailable from "@/app/components/ui/NotAvailable";
import { fetchSpinPrices } from "@/app/lib/api/spin";

type SpinPrices = Record<string, string | number>;
const clampMode = (n: number) => Math.min(6, Math.max(1, n));

const Home = () => {
  const [boltMode, setBoltMode] = useState(false);
  const [selectedMode, setSelectedMode] = useState(1);

  const [spinPrices, setSpinPrices] = useState<SpinPrices>({});

  const searchParams = useSearchParams();
  const boxId = searchParams.get("boxId");

  const user = useSelector((state: any) => state.auth.user) as User | null;
  const isRun = useRef(false);
  const getSpinPrices = async () => {
    try {
      const res = await fetchSpinPrices();
      const prices = (res?.data ?? res) as SpinPrices; // api response shape
      setSpinPrices(prices || {});
    } catch (e: any) {
      console.log(e);
    }
  };

  // ✅ if URL has boxId, set initial selectedMode to that
  useEffect(() => {
    if (isRun.current) return;
    isRun.current = true;
    getSpinPrices();
    const n = Number(boxId);
    if (!boxId || !Number.isFinite(n)) return;
    setSelectedMode(clampMode(n));
  }, [boxId]);

  // ✅ OgBox always driven by selectedMode (not boxId)

  // ✅ FIX: price ko string hi rakho (number aaye to string bana do)

  // Home page me displayBox useMemo ka REPLACE version:
  const displayBox = useMemo(() => {
    const b = BOXES.find((x) => x.id === selectedMode);
    if (!b) return b;

    const idToSlug: Record<number, string> = {
      1: "og-box",
      2: "fyre-box",
      3: "ice-cold",
      4: "silver-box",
      5: "ice-cold-1",
      6: "silver-box-1",
    };

    const slug = idToSlug[b.id];
    const apiPrice = slug ? spinPrices?.[slug] : undefined;

    // ✅ always string
    const finalPrice =
      apiPrice === undefined || apiPrice === null ? b.price : String(apiPrice);

    return { ...b, price: finalPrice };
  }, [selectedMode, spinPrices]);

  return (
    <div className="text-white">
      {user?.activeMode === "gems" ? (
        <NotAvailable />
      ) : (
        <>
          <div>
            <OgBox
              box={displayBox}
              checked={boltMode}
              setBoltMode={(next) => setBoltMode(next)}
            />

            <PokemonBoxSpinner
              box={displayBox}
              boltMode={boltMode}
              boxId={boxId}
              selectedMode={selectedMode}
              setSelectedMode={setSelectedMode}
            />
          </div>
        </>
      )}
    </div>
  );
};

export default Home;
