// (C) 2022-2026 GoodData Corporation
import { useCallback } from "react";
import { areObjRefsEqual } from "@gooddata/sdk-model";
import { selectIsInEditMode } from "../store/renderMode/renderModeSelectors.js";
import { uiActions } from "../store/ui/index.js";
import { selectConfigurationPanelOpened, selectSelectedWidgetRef } from "../store/ui/uiSelectors.js";
import { useDashboardDispatch, useDashboardSelector } from "./DashboardStoreProvider.js";
/**
 * @internal
 */
export function useWidgetSelection(widgetRef) {
    const dispatch = useDashboardDispatch();
    const isConfigPanelOpen = useDashboardSelector(selectConfigurationPanelOpened);
    const isSelectable = useDashboardSelector(selectIsInEditMode);
    const selectedWidget = useDashboardSelector(selectSelectedWidgetRef);
    const isSelected = Boolean(isSelectable && selectedWidget && widgetRef && areObjRefsEqual(selectedWidget, widgetRef));
    const closeConfigPanel = useCallback(() => {
        dispatch(uiActions.setConfigurationPanelOpened(false));
    }, [dispatch]);
    const onSelected = useCallback((e) => {
        let processedDuringWidgetSelectOriginal = false;
        if (e) {
            /**
             * Do not stop propagation, just mark event as processed here so that in case come other element
             * up the tree uses the deselectWidgets function. Without this mark such element would immediately
             * deselect the widget we just selected with the same click.
             */
            processedDuringWidgetSelectOriginal = e.processedDuringWidgetSelect;
            e.processedDuringWidgetSelect = true;
        }
        if (isSelectable && widgetRef && !processedDuringWidgetSelectOriginal) {
            dispatch(uiActions.selectWidget(widgetRef));
            dispatch(uiActions.setConfigurationPanelOpened(true));
        }
    }, [isSelectable, widgetRef, dispatch]);
    const deselectWidgets = useCallback((e) => {
        // Avoid deselect widget when the click event was triggered by selecting text
        // (eg. selecting markdown text in rich text widget and releasing mouse outside of the widget)
        const isSelection = window.getSelection()?.type === "Range";
        if (!e?.processedDuringWidgetSelect && selectedWidget && !isSelection) {
            dispatch(uiActions.clearWidgetSelection());
        }
    }, [dispatch, selectedWidget]);
    return {
        isSelectable,
        isSelected,
        onSelected,
        hasConfigPanelOpen: isConfigPanelOpen && isSelected,
        closeConfigPanel,
        deselectWidgets,
    };
}
