import * as React from 'react';
import { getAgentUserIdForStorageKey } from '../utils/user-utils';
import { buildAgentVisibilityStorageKey, readAgentVisibilityFromStorage, writeAgentVisibilityToStorage, } from '../utils/agent-visibility-storage';
import { resolveAgentTableId } from '../utils/resolve-agent-table-id';
function computeInitialVisible(options) {
    const { resolvedTableId, userId: userIdProp, defaultVisible = true, enablePersistence = true, } = options;
    if (typeof window === 'undefined' || !enablePersistence || !resolvedTableId) {
        return defaultVisible;
    }
    const uid = getAgentUserIdForStorageKey(userIdProp);
    if (uid == null)
        return defaultVisible;
    const key = buildAgentVisibilityStorageKey(uid, resolvedTableId);
    const stored = readAgentVisibilityFromStorage(key);
    return stored !== null ? stored : defaultVisible;
}
/**
 * AI 助理显隐按 `userId_tableId_agent` 持久化到 localStorage。
 * 与 CnAiFilter 通过事件总线切换时，请将返回值作为 `agentVisible` / `onAgentVisibleChange` 传入页面与 CnAiAgent。
 * 第三项 `resolvedTableId` 与 CnAiAgent 的 `id` 一致；无显式 id 时可传 `tablePluginId`（来自表格插件总线）。
 */
export function usePersistedAgentVisibility(options) {
    const { tableId: tableIdProp, innerProps, tablePluginId, userId: userIdProp, defaultVisible = true, enablePersistence = true, } = options;
    const resolvedTableId = React.useMemo(() => {
        if (tableIdProp != null && String(tableIdProp).trim() !== '') {
            return String(tableIdProp).trim();
        }
        return resolveAgentTableId(innerProps, tablePluginId);
    }, [tableIdProp, innerProps, tablePluginId]);
    const storageKey = React.useMemo(() => {
        if (!enablePersistence || !resolvedTableId)
            return null;
        const uid = getAgentUserIdForStorageKey(userIdProp);
        if (uid == null)
            return null;
        return buildAgentVisibilityStorageKey(uid, resolvedTableId);
    }, [enablePersistence, resolvedTableId, userIdProp]);
    const [visible, setVisible] = React.useState(() => computeInitialVisible({
        resolvedTableId,
        userId: userIdProp,
        defaultVisible,
        enablePersistence,
    }));
    // tableId / userId 变化（如从 A 表路由到 B 表）时按新 key 重读，避免沿用上一张表的显隐。
    React.useEffect(() => {
        if (!enablePersistence || !resolvedTableId) {
            setVisible(defaultVisible);
            return;
        }
        if (!storageKey) {
            setVisible(defaultVisible);
            return;
        }
        const stored = readAgentVisibilityFromStorage(storageKey);
        setVisible(stored !== null ? stored : defaultVisible);
    }, [storageKey, defaultVisible, enablePersistence, resolvedTableId]);
    const setVisiblePersisted = React.useCallback((value) => {
        setVisible((prev) => {
            const next = typeof value === 'function' ? value(prev) : value;
            if (storageKey) {
                writeAgentVisibilityToStorage(storageKey, next);
            }
            return next;
        });
    }, [storageKey]);
    return [visible, setVisiblePersisted, resolvedTableId];
}
