import { useEffect, useRef } from 'react';
import { event as eventBus } from '@ice/stark-data';
import { useCnAiListEventNames } from '../context/cn-ai-list-event-context';
/**
 * 与 CnAiFilter 中的图标通过事件总线同步 AI 助理显隐（显隐由父组件受控）。
 */
export function useAgentVisibilityWithFilter({ agentVisible, onAgentVisibleChange, }) {
    const eventNames = useCnAiListEventNames();
    /**
     * 助理面板是否可见
     */
    const visible = agentVisible;
    const visibleRef = useRef(visible);
    visibleRef.current = visible;
    const onAgentVisibleChangeRef = useRef(onAgentVisibleChange);
    onAgentVisibleChangeRef.current = onAgentVisibleChange;
    useEffect(() => {
        const handleFromBus = (state) => {
            /**
             * 如果未启用助理显隐联动，则不订阅总线、不响应显隐变化
             */
            if (!state.enabled)
                return;
            /**
             * 如果助理面板已可见，则不响应显隐变化
             */
            if (state.visible === visibleRef.current)
                return;
            /**
             * 更新助理面板是否可见
             */
            onAgentVisibleChangeRef.current(state.visible);
        };
        /**
         * 请求助理当前状态，用于组件挂载时同步状态
         */
        const handleRequest = () => {
            eventBus.emit(eventNames.AGENT_VISIBILITY_CHANGE, {
                enabled: true,
                visible: visibleRef.current,
            });
        };
        eventBus.on(eventNames.AGENT_VISIBILITY_CHANGE, handleFromBus);
        eventBus.on(eventNames.REQUEST_AGENT_STATE, handleRequest);
        return () => {
            eventBus.off(eventNames.AGENT_VISIBILITY_CHANGE, handleFromBus);
            eventBus.off(eventNames.REQUEST_AGENT_STATE, handleRequest);
        };
    }, [eventNames]);
    useEffect(() => {
        visibleRef.current = visible;
        eventBus.emit(eventNames.AGENT_VISIBILITY_CHANGE, {
            enabled: true,
            visible,
        });
    }, [visible, eventNames]);
    const panelHidden = !visible;
    return { visible, panelHidden };
}
