import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useRef, useEffect } from "react";
import styles from "./style.module.css";
import { MdKeyboardArrowUp, MdKeyboardArrowDown } from "react-icons/md";
import { MAIN_BLUE } from "../styles/colors";
export default function BlockSelector3({ gameRef, staticBlock, staticBlockItem, posterItems, }) {
    const containerRef = useRef(null);
    const scrollContainerRef = useRef(null);
    const [extendedItems, setExtendedItems] = useState([...posterItems, ...posterItems, ...posterItems, ...posterItems, ...posterItems, ...posterItems, ...posterItems, ...posterItems, ...posterItems, ...posterItems, ...posterItems, ...posterItems]);
    const itemHeight = 50; // We might want to compute this dynamically.
    const staticBlockRef = useRef(null);
    let scrollTimeout = null;
    // On mount, set the initial scroll to the middle copy.
    useEffect(() => {
        if (scrollContainerRef.current) {
            scrollContainerRef.current.scrollTop = posterItems.length * itemHeight;
        }
    }, [posterItems, itemHeight]);
    const onBlockChange = (item) => {
        if (!gameRef.current || !gameRef.current.scene)
            return;
        switch (staticBlock) {
            case "left":
                gameRef.current.scene.selectedCogTiltLeftBlock = item;
                break;
            case "right":
                gameRef.current.scene.selectedCogTiltRightBlock = item;
                break;
        }
        ;
    };
    // Use the DOM to determine which poster item is centered under the static block.
    const getSnappedItem = () => {
        if (!staticBlockRef.current || !scrollContainerRef.current)
            return null;
        // Get the static block's bounding rectangle.
        const staticRect = staticBlockRef.current.getBoundingClientRect();
        const staticCenterY = staticRect.top + staticRect.height / 2;
        // Query all poster items.
        const items = scrollContainerRef.current.querySelectorAll(`.${styles.carouselItem}`);
        let closestItem = null;
        let minDistance = Infinity;
        items.forEach((el) => {
            const rect = el.getBoundingClientRect();
            const itemCenterY = rect.top + rect.height / 2;
            const distance = Math.abs(staticCenterY - itemCenterY);
            if (distance < minDistance) {
                minDistance = distance;
                closestItem = el;
            }
        });
        if (closestItem) {
            // Get the index from the data attribute.
            const indexStr = closestItem.getAttribute("data-index");
            if (indexStr !== null) {
                const extendedIndex = parseInt(indexStr, 10);
                return extendedItems[extendedIndex];
            }
        }
        return null;
    };
    // Handle scroll event to simulate infinite scrolling.
    const handleScroll = () => {
        // append or prepend items in the extendedItems array based on scroll position
        const scrollEl = scrollContainerRef.current;
        if (!scrollEl)
            return;
        const scrollTop = scrollEl.scrollTop;
        const scrollHeight = scrollEl.scrollHeight;
        const clientHeight = scrollEl.clientHeight;
        const scrollBottom = scrollTop + clientHeight;
        const scrollThreshold = itemHeight * 2;
        if (scrollTop < scrollThreshold) {
            const newItems = extendedItems.slice(-posterItems.length);
            setExtendedItems((prev) => [...newItems, ...prev]);
            scrollEl.scrollTop += itemHeight * posterItems.length;
        }
        else if (scrollBottom > scrollHeight - scrollThreshold) {
            const newItems = extendedItems.slice(0, posterItems.length);
            setExtendedItems((prev) => [...prev, ...newItems]);
            scrollEl.scrollTop -= itemHeight * posterItems.length;
        }
        // Determine the snapped item.
        if (scrollTimeout) {
            clearTimeout(scrollTimeout);
        }
        scrollTimeout = setTimeout(() => {
            const snappedItem = getSnappedItem();
            if (snappedItem) {
                onBlockChange(snappedItem);
            }
        }, 200);
    };
    const scrollByItem = (direction) => {
        const scrollEl = scrollContainerRef.current;
        if (!scrollEl)
            return;
        const delta = direction === "up" ? -itemHeight : itemHeight;
        scrollEl.scrollBy({ top: delta, behavior: "smooth" });
    };
    const handleArrowUpClick = () => {
        scrollByItem("up");
    };
    const handleArrowDownClick = () => {
        scrollByItem("down");
    };
    return (_jsxs("div", { className: styles.outerContainer, children: [_jsx("div", { className: styles.upArrowContainer, onClick: handleArrowUpClick, children: _jsx(MdKeyboardArrowUp, { color: MAIN_BLUE, size: 40 }) }), _jsxs("div", { ref: containerRef, className: styles.carouselBody, children: [_jsx("div", { ref: staticBlockRef, className: styles.staticBlockItem, children: _jsx(staticBlockItem.icon, { className: styles.staticBlockItemIcon }) }), _jsx("div", { ref: scrollContainerRef, className: styles.scrollContainer, onScroll: handleScroll, children: extendedItems.map((item, index) => (_jsx("div", { "data-index": index, className: styles.carouselItem, children: _jsx(item.icon, { className: styles.carouselItemIcon }) }, index + item.block))) })] }), _jsx("div", { className: styles.downArrowContainer, onClick: handleArrowDownClick, children: _jsx(MdKeyboardArrowDown, { color: MAIN_BLUE, size: 40 }) })] }));
}
