import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useRef, useEffect, useState, useCallback } from "react";
import styles from "./style.module.css";
import { MdKeyboardArrowUp, MdKeyboardArrowDown } from "react-icons/md";
import { MAIN_BLUE } from "../styles/colors";
export default function BlockSelector4({ gameRef, staticBlock, staticBlockItem, posterItems, onSelectedBlockChange, initialSelectedIndex, }) {
    const scrollContainerRef = useRef(null);
    const staticBlockRef = useRef(null);
    const scrollTimeoutRef = useRef(null);
    const getInitialSelectedIndex = useCallback(() => {
        const maxIndex = Math.max(posterItems.length - 1, 0);
        const requestedIndex = initialSelectedIndex ?? Math.floor(posterItems.length / 2);
        return Math.min(Math.max(requestedIndex, 0), maxIndex);
    }, [initialSelectedIndex, posterItems.length]);
    const [selectedIndex, setSelectedIndex] = useState(getInitialSelectedIndex);
    const writeSelectedBlockToScene = useCallback((item) => {
        const scene = gameRef.current?.scene;
        if (!scene)
            return;
        if (staticBlock === "left") {
            scene.selectedCogTiltLeftBlock = item;
        }
        else {
            scene.selectedCogTiltRightBlock = item;
        }
    }, [gameRef, staticBlock]);
    const onBlockChange = useCallback((item, index) => {
        setSelectedIndex(index);
        onSelectedBlockChange?.(item);
        writeSelectedBlockToScene(item);
    }, [onSelectedBlockChange, writeSelectedBlockToScene]);
    const scrollItemToStaticCenter = useCallback((index, behavior = "auto") => {
        if (!staticBlockRef.current || !scrollContainerRef.current)
            return;
        const item = scrollContainerRef.current.querySelector(`[data-index="${index}"]`);
        if (!(item instanceof HTMLElement))
            return;
        const staticRect = staticBlockRef.current.getBoundingClientRect();
        const itemRect = item.getBoundingClientRect();
        const staticCenterY = staticRect.top + staticRect.height / 2;
        const itemCenterY = itemRect.top + itemRect.height / 2;
        const nextScrollTop = scrollContainerRef.current.scrollTop + itemCenterY - staticCenterY;
        scrollContainerRef.current.scrollTo({
            top: Math.max(0, nextScrollTop),
            behavior,
        });
    }, []);
    useEffect(() => {
        const selectedIndex = getInitialSelectedIndex();
        const animationFrame = window.requestAnimationFrame(() => {
            scrollItemToStaticCenter(selectedIndex, "auto");
            if (posterItems[selectedIndex]) {
                onBlockChange(posterItems[selectedIndex], selectedIndex);
            }
        });
        return () => {
            window.cancelAnimationFrame(animationFrame);
            if (scrollTimeoutRef.current) {
                clearTimeout(scrollTimeoutRef.current);
            }
        };
    }, [getInitialSelectedIndex, onBlockChange, posterItems, scrollItemToStaticCenter]);
    const getSnappedItem = () => {
        if (!staticBlockRef.current || !scrollContainerRef.current)
            return null;
        const staticRect = staticBlockRef.current.getBoundingClientRect();
        const staticCenterY = staticRect.top + staticRect.height / 2;
        const items = scrollContainerRef.current.querySelectorAll(`.${styles.carouselItem}`);
        let closestEl = null;
        let minDist = Infinity;
        items.forEach(el => {
            const r = el.getBoundingClientRect();
            const dist = Math.abs(staticCenterY - (r.top + r.height / 2));
            if (dist < minDist) {
                minDist = dist;
                closestEl = el;
            }
        });
        if (closestEl) {
            const idx = parseInt(closestEl.getAttribute("data-index") || "", 10);
            return { item: posterItems[idx], index: idx };
        }
        return null;
    };
    const handleScroll = () => {
        if (scrollTimeoutRef.current) {
            clearTimeout(scrollTimeoutRef.current);
        }
        scrollTimeoutRef.current = setTimeout(() => {
            const snapped = getSnappedItem();
            if (snapped?.item)
                onBlockChange(snapped.item, snapped.index);
        }, 150);
    };
    const scrollByItem = (dir) => {
        const maxIndex = Math.max(posterItems.length - 1, 0);
        const nextIndex = Math.min(Math.max(selectedIndex + (dir === "up" ? -1 : 1), 0), maxIndex);
        if (nextIndex === selectedIndex || !posterItems[nextIndex])
            return;
        if (scrollTimeoutRef.current) {
            clearTimeout(scrollTimeoutRef.current);
        }
        scrollItemToStaticCenter(nextIndex, "auto");
        onBlockChange(posterItems[nextIndex], nextIndex);
    };
    return (_jsxs("div", { className: styles.outerContainer, children: [_jsx("button", { type: "button", "aria-label": "Previous action", onClick: () => scrollByItem("up"), className: styles.upArrowContainer, children: _jsx(MdKeyboardArrowUp, { color: MAIN_BLUE, size: 40 }) }), _jsxs("div", { className: styles.commandRail, children: [_jsx("div", { ref: staticBlockRef, className: styles.staticBlockItem, children: _jsx(staticBlockItem.icon, { className: styles.staticBlockItemIcon }) }), _jsx("div", { className: styles.commandConnector }), _jsx("div", { className: styles.carouselBody, children: _jsx("div", { ref: scrollContainerRef, className: styles.scrollContainer, onScroll: handleScroll, style: {
                                overflowY: "auto",
                                paddingTop: 114,
                                paddingBottom: 114,
                            }, children: posterItems.map((item, index) => (_jsx("div", { "data-index": index, className: `${styles.carouselItem} ${selectedIndex === index ? styles.carouselItemSelected : ""}`, style: { height: 58 }, children: _jsx(item.icon, { className: styles.carouselItemIcon }) }, index + item.block))) }) })] }), _jsx("button", { type: "button", "aria-label": "Next action", onClick: () => scrollByItem("down"), className: styles.downArrowContainer, children: _jsx(MdKeyboardArrowDown, { color: MAIN_BLUE, size: 40 }) })] }));
}
