// ✅ InventoryModal.tsx — add selected cards to parent on "ADD CARD"
// also fix "modal behind" issue by using Portal + high z-index

import React, { useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { InventoryCard } from "@/app/lib/api/inventory";
import { User } from "@/constants/types";
import { useSelector } from "react-redux";
import { AuthState } from "@/app/wallet/page";

interface Item extends InventoryCard {
  selected?: boolean;
}

export const InventoryModal: React.FC<{
  isOpen: boolean;
  onClose: () => void;
  user: User | null;
  cardLoading: boolean;
  cardsError: string | null;
  cards: InventoryCard[] | null;

  onConfirm: (cards: InventoryCard[]) => void; // ✅
  initialSelectedIds?: number[]; // ✅ optional
  offset: number | null;
  onLoadMore: () => void;
  hasMore: boolean;
  isLoadingMore: boolean;
}> = ({
  isOpen,
  onClose,
  cards,
  cardLoading,
  cardsError,
  onConfirm,
  initialSelectedIds = [],
  offset,
  onLoadMore,
  hasMore,
  isLoadingMore,
}) => {
  const [itemList, setItemList] = useState<Item[]>([]);
  const [mounted, setMounted] = useState(false);

  // lazy loading States
  const STEP = 10; // load
  const [visibleCount, setVisibleCount] = useState(STEP);
  const [isFetchingMore, setIsFetchingMore] = useState(false);
  const scrollRef = useRef<HTMLDivElement | null>(null);
  const user = useSelector((state: { auth: AuthState }) => state.auth.user);

  useEffect(() => setMounted(true), []);

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

  setVisibleCount(STEP);
  setIsFetchingMore(false);

  // ✅ Reset only when modal opens
  setItemList(
    (cards || []).map((c: any) => ({
      ...c,
      selected: initialSelectedIds.includes(c.inv_id),
    })),
  );

  requestAnimationFrame(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  });
}, [isOpen]); // ✅ cards removed


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

  setItemList((prev) => {
    const selectedMap = new Map<number, boolean>();
    prev.forEach((p) => selectedMap.set(p.inv_id, !!p.selected));

    return (cards || []).map((c: any) => ({
      ...c,
      selected: selectedMap.get(c.inv_id) ?? false, // ✅ preserve previous selection
    }));
  });
}, [cards, isOpen]);


  const toggleItemSelection = (id: number) => {
    setItemList((prev) =>
      prev.map((item) =>
        item.inv_id === id ? { ...item, selected: !item.selected } : item,
      ),
    );
  };

  // const selectedItems = itemList.filter((i) => i.selected);
  const selectedItems = useMemo(
    () => itemList.filter((i) => i.selected),
    [itemList],
  );
  const selectedCount = selectedItems.length;
  const totalValue = selectedItems.reduce((sum, item) => sum + item.price, 0);

  // ✅ items to show right now
  const visibleItems = useMemo(
    () => itemList.slice(0, visibleCount),
    [itemList, visibleCount],
  );



  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const el = e.currentTarget;
    const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 120;

    if (!nearBottom) return;

    // pehle UI visibleCount badhao (optional)
    if (!isFetchingMore && visibleCount < itemList.length) {
      setIsFetchingMore(true);
      setTimeout(() => {
        setVisibleCount((c) => Math.min(c + STEP, itemList.length));
        setIsFetchingMore(false);
      }, 250);
      return;
    }

    // ✅ agar UI me sab items already visible hain
    // aur server pe abhi "more" hai, to API next page hit karo
    if (
      nearBottom &&
      visibleCount >= itemList.length &&
      hasMore &&
      !isLoadingMore
    ) {
      onLoadMore();
    }
  };

  if (!isOpen || !mounted) return null;

  const modalUI = (
    <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-2147483647 flex items-center justify-center p-4">
      <div className="bg-(--color-naviBlue) relative box-shadow-custom w-full max-w-274.25 max-h-100 2xl:max-h-155 flex flex-col">
        {/* Header */}
        <div className="flex flex-col gap-4 md:flex-row items-center justify-between px-6 py-3 md:py-5 2xl:py-8 border-b-4 border-[var(--color-gray)]">
          <h2 className="font-onest text-sm md:text-xl font-semibold text-white">
            Select Cards
          </h2>
          <button
            onClick={onClose}
            className="absolute top-3 right-3 cursor-pointer"
          >
            <img
              src="/images/coinFlip/modal/cross.svg"
              className="p-5"
              alt=""
            />
          </button>
        </div>

        {/* Items Grid */}
        <div
          ref={scrollRef}
          onScroll={handleScroll}
          className="no-scrollbar flex-1 overflow-y-auto p-3"
        >
          {cardLoading ? (
            <div className="flex w-full h-[260px] items-center justify-center">
              <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
            </div>
          ) : cardsError ? (
            <h1 className="text-center text-white text-sm md:text-2xl">
              {cardsError}
            </h1>
          ) : (
            <>
              {visibleItems.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-16 text-center">
                  <p className="text-base md:text-3xl font-bold text-white mb-2">
                    Open your packs to get started
                  </p>
                  <p className="text-sm md:text-2xl text-[var(--color-slate)] max-w-md">
                    Once you open a pack, your inventory cards will appear here.
                  </p>
                </div>
              ) : (
                <>
                  <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-7 gap-4">
                    {visibleItems.map((item, index) => (
                      <div
                        key={index}
                        onClick={() => toggleItemSelection(item.inv_id)}
                        className={`relative group bg-[#1F1C26] p-3 cursor-pointer transition-all border-[1.5] ${
                          item.selected
                            ? "border-[var(--color-blue)] box-shadow-custom-inset"
                            : "border-[#1F1C26]"
                        }`}
                      >
                        <div className="flex flex-col justify-center items-center">
                          <div className="text-center font-sofia mb-2">
                            <h3 className="text-xs md:text-base font-bold text-white uppercase italic tracking-wide">
                              {item.name.split(" ").slice(0, 2).join(" ")}
                            </h3>
                            <p className="text-[10px] md:text-xs text-[var(--color-slate)] uppercase mt-0.5">
                              {item.rarity}
                            </p>
                          </div>

                          <div className="mb-1">
                            <div className=" overflow-hidden">
                              <div className="w-15.2 h-22 flex items-center justify-center">
                                <img
                                  src={item.image.replace(
                                    "cardsimages",
                                    "cards/images",
                                  )}
                                  className="w-full h-full img-border-radius object-contain"
                                  alt=""
                                />
                              </div>
                            </div>

                            {item.selected && (
                              <div className="absolute bottom-0 left-0 bg-[var(--color-blue)] shadow-lg p-2">
                                <img
                                  src="/images/coinFlip/modal/tick.svg"
                                  alt=""
                                />
                              </div>
                            )}
                          </div>

                          <div className="text-center">
                            <span className="text-sm flex items-center justify-center gap-1 font-bold text-[var(--color-blue)]">
                              {user?.activeMode === "coins" ? (
                                <img
                                  src="/images/header/win.svg"
                                  alt=""
                                  className="h-4 w-4"
                                />
                              ) : (
                                <img
                                  src="/images/header/star.svg"
                                  alt=""
                                  className="h-4 w-4"
                                />
                              )}{" "}
                              {item.price}
                            </span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                  {/* ✅ lazy loading indicator */}
                  {/* {visibleCount < itemList.length ? (
                    <div className="flex justify-center py-4">
                      {isFetchingMore ? (
                        <div className="w-7 h-7 border-4 border-white/20 border-t-white rounded-full animate-spin" />
                      ) : (
                        <p className="text-xs text-white/70">
                          Scroll to load more…
                        </p>
                      )}
                    </div>
                  ) : (
                    <h1 className="mt-2 text-sm md:text-lg  text-center text-white/40">
                      All items loaded
                    </h1>
                  )} */}
                  {hasMore ? (
                    isLoadingMore ? (
                      <div className="flex justify-center py-4">
                        <div className="w-7 h-7 border-4 border-white/20 border-t-white rounded-full animate-spin" />
                      </div>
                    ) : (
                      <p className="text-xs text-white/70 text-center py-4">
                        Scroll to load more…
                      </p>
                    )
                  ) : (
                    <h1 className="mt-2 text-sm md:text-lg text-center text-white/40">
                      All items loaded
                    </h1>
                  )}
                </>
              )}
            </>
          )}
        </div>

        {/* Footer */}
        <div className="px-6 py-5 border-t-2 border-(--color-gray)">
          <div className="flex items-center justify-between">
            <div className="flex items-center text-white gap-3 md:gap-12">
              <div className="flex flex-col items-center">
                <div className="text-lg md:text-3xl font-extrabold text-(--color-blue)">
                  ${totalValue.toFixed(2)}
                </div>
                <div className="text-xs uppercase tracking-wider font-semibold md:mt-1">
                  ITEM VALUE
                </div>
              </div>

              <div className="flex flex-col items-center">
                <div className="text-lg md:text-3xl font-extrabold text-[var(--color-blue)]">
                  {selectedCount.toString().padStart(2, "0")}
                </div>
                <div className="text-xs uppercase tracking-wider font-semibold md:mt-1">
                  TOTAL ITEMS
                </div>
              </div>
            </div>

            <button
              onClick={() => onConfirm(selectedItems)} // ✅ send to parent
              className={`px-3 md:px-10 cursor-pointer py-3 text-white font-onest md:text-base font-bold bg-[var(--color-blue)] text-xs uppercase tracking-wide transition-all ${
                selectedCount === 0
                  ? "cursor-not-allowed pointer-events-none"
                  : "hover:bg-[var(--color-hoverBlue)]"
              }`}
            >
              ADD CARD
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  // ✅ Portal makes sure modal is ALWAYS on top (no "div ke pichay")
  return createPortal(modalUI, document.body);
};
