"use client";
import Image from "next/image";
import { useEffect, useState } from "react";
import DetailSidebar from "../components/fairness/DetailSidebar";
import { ImplementContent } from "../components/fairness/ImplementContent";
import OverviewContent from "../components/fairness/OverviewContent";
import ConversationContent from "../components/fairness/ConversationContent";
import CalculationContent from "../components/fairness/CalculationContent";
import CardPoolContent from "../components/fairness/CardPoolContent";
import OddsContent from "../components/fairness/OddsContent";
import "./style.css";
import { useSearchParams } from "next/navigation";
type TabId =
  | "odds"
  | "overview"
  | "implementation"
  | "conversions"
  | "calculation"
  | "card pool";

type TabItem = {
  id: TabId;
  label: string;
  component: React.ReactNode;
};
type CardDrop = {
  id: string;
  title: string;
  subtitle: string;
  brand: Brand;
  date: string;
  price: number;
  image: string;
};

type Brand = "magic" | "pokemon" | "lorcana";
type ChildTab = "all" | Brand;

type PackItem = {
  id: string;
  title: string; // Scarlet & Violet
  subtitle: string; // Journey Together
  brand: Brand;
};

const BRAND_IMAGES: Record<Brand, string> = {
  magic: "/images/inventory/magic.svg",
  pokemon: "/images/inventory/pokemon.svg",
  lorcana: "/images/inventory/lorcana.svg",
};

const TAB_DESCRIPTIONS: Record<TabId, string> = {
  odds: "Showing dummy odds data for all packs in this view.",
  overview: "Inventory overview across the selected brand(s).",
  implementation: "Implementation demo data for sealed products.",
  conversions: "Conversion demo data for sealed products.",
  calculation: "Calculation demo data for expected value and payouts.",
  "card pool": "Card pool demo data for each pack configuration.",
};

// Base dummy pack data per brand
const PACKS_BY_BRAND: Record<Brand, PackItem[]> = {
  pokemon: Array.from({ length: 12 }).map((_, i) => ({
    id: `pkm-${i}`,
    title: "Scarlet & Violet",
    subtitle: "Journey Together",
    brand: "pokemon",
  })),
  magic: Array.from({ length: 12 }).map((_, i) => ({
    id: `mtg-${i}`,
    title: "Wilds of Eldraine",
    subtitle: "Draft Booster",
    brand: "magic",
  })),
  lorcana: Array.from({ length: 12 }).map((_, i) => ({
    id: `lor-${i}`,
    title: "Rise of the Floodborn",
    subtitle: "Booster Pack",
    brand: "lorcana",
  })),
};

// Split items into N columns
const buildColumns = (items: PackItem[], cols: number): PackItem[][] => {
  const columns: PackItem[][] = Array.from({ length: cols }, () => []);
  items.forEach((item, index) => {
    columns[index % cols].push(item);
  });
  return columns;
};

const Page = () => {
  const [activeTab, setActiveTab] = useState<TabId>("overview");
  const [childTab, setChildTab] = useState<ChildTab>("all");
  const [detailCard, setDetailCard] = useState<CardDrop | null>(null);

  const searchParams = useSearchParams();
  // params data
  const serverSeed = searchParams.get("serverSeed");
  const clientSeed = searchParams.get("clientSeed");
  const nonce = Number(searchParams.get("nonce"));
  const paramsData = {
    serverSeed,
    clientSeed,
    nonce,
  };

  const TABS: TabItem[] = [
    { id: "odds", label: "Odds", component: <OddsContent /> },
    { id: "overview", label: "Overview", component: <OverviewContent /> },
    {
      id: "implementation",
      label: "Implementation",
      component: <ImplementContent />,
    },
    {
      id: "conversions",
      label: "Conversions",
      component: <ConversationContent />,
    },
    {
      id: "calculation",
      label: "Calculation",
      component: <CalculationContent paramsData={paramsData} />,
    },
    { id: "card pool", label: "Card Pool", component: <CardPoolContent /> },
  ];

  useEffect(() => {
    if (serverSeed && clientSeed && nonce) {
      setActiveTab("calculation");
    }
  }, []);

  const activeTabItem = TABS.find((t) => t.id === activeTab);

  // Data based on child tab
  const items: PackItem[] =
    childTab === "all"
      ? (Object.values(PACKS_BY_BRAND).flat() as PackItem[])
      : PACKS_BY_BRAND[childTab];

  const columns = buildColumns(items, 4); // 4 vertical columns like your screenshot

  return (
    <main className="min-h-screen text-white">
        {/* Top bar */}
        <div className="container mx-auto py-4">
          <div className="flex items-center mb-2 gap-4">
            <button className="cursor-pointer text-xs md:text-sm p-2 px-4 font-extrabold text-white bg-[var(--color-gray)] hover:text-white italic font-sofia transition">
              &lt; BACK
            </button>
            <h1 className="text-sm md:text-xl 2xl:text-2xl font-sofia  font-extrabold italic">
              FAIRNESS
            </h1>
          </div>

        {/* Parent tabs */}
        <nav className="flex flex-wrap gap-1 sm:gap-4">
          {TABS.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`font-sofia font-extrabold px-3 py-1.5 text-xs md:text-base 2xl:text-xl uppercase tracking-wide ${
                activeTab === tab.id
                  ? "bg-[var(--color-blue)]  text-white"
                  : "hover:bg-[#141728] hover:text-white text-slate-300"
              }`}
            >
              {tab.label}
            </button>
          ))}
        </nav>
        {/* Tab content */}
        <div className="">{activeTabItem?.component}</div>
      </div>
      <DetailSidebar card={detailCard} onClose={() => setDetailCard(null)} />
    </main>
  );
};

export default Page;
