import { useMemo, useState } from "react";

function useGameObjectState(gameObjects) {
    const [selectedObject, setSelectedObject] = useState(null);
    const [readyObjects, setReadyObjects] = useState([]);
    const [hoveredObjectId, setHoveredObjectId] = useState(null);

    const objectById = useMemo(() => {
        const map = {};
        Object.values(gameObjects).forEach((object) => {
            if (!map[object.id]) {
                map[object.id] = object;
            }
        });
        return map;
    }, [gameObjects]);

    const doneObjectIds = useMemo(
        () => new Set(readyObjects.map((object) => object.id)),
        [readyObjects]
    );

    const handleObjectSelect = (objectId) => {
        setSelectedObject(objectById[objectId] ?? null);
    };

    const handleObjectMouseEnter = (objectId) => {
        setHoveredObjectId(objectId);
    };

    const handleObjectMouseLeave = () => {
        setHoveredObjectId(null);
    };

    const handleReadyButtonClick = () => {
        if (!selectedObject) return;
        if (doneObjectIds.has(selectedObject.id)) {
            setSelectedObject(null);
            return;
        }

        setReadyObjects((prev) => [...prev, selectedObject]);
        setSelectedObject(null);
    };

    const cancelObject = () => {
        if (!selectedObject) return;
        setReadyObjects((prev) =>
            prev.filter((object) => object.id !== selectedObject.id)
        );
        setSelectedObject(null);
    };

    const isPrepared = (objectId) => doneObjectIds.has(objectId);

    return {
        selectedObject,
        setSelectedObject,
        readyObjects,
        hoveredObjectId,
        doneObjectIds,
        handleObjectSelect,
        handleObjectMouseEnter,
        handleObjectMouseLeave,
        handleReadyButtonClick,
        cancelObject,
        isPrepared,
    };
}

export default useGameObjectState;
