"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.usePersistedAgentVisibility = usePersistedAgentVisibility;
const React = __importStar(require("react"));
const user_utils_1 = require("../utils/user-utils");
const agent_visibility_storage_1 = require("../utils/agent-visibility-storage");
const resolve_agent_table_id_1 = require("../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 = (0, user_utils_1.getAgentUserIdForStorageKey)(userIdProp);
    if (uid == null)
        return defaultVisible;
    const key = (0, agent_visibility_storage_1.buildAgentVisibilityStorageKey)(uid, resolvedTableId);
    const stored = (0, agent_visibility_storage_1.readAgentVisibilityFromStorage)(key);
    return stored !== null ? stored : defaultVisible;
}
/**
 * AI 助理显隐按 `userId_tableId_agent` 持久化到 localStorage。
 * 与 CnAiFilter 通过事件总线切换时，请将返回值作为 `agentVisible` / `onAgentVisibleChange` 传入页面与 CnAiAgent。
 * 第三项 `resolvedTableId` 与 CnAiAgent 的 `id` 一致；无显式 id 时可传 `tablePluginId`（来自表格插件总线）。
 */
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 (0, resolve_agent_table_id_1.resolveAgentTableId)(innerProps, tablePluginId);
    }, [tableIdProp, innerProps, tablePluginId]);
    const storageKey = React.useMemo(() => {
        if (!enablePersistence || !resolvedTableId)
            return null;
        const uid = (0, user_utils_1.getAgentUserIdForStorageKey)(userIdProp);
        if (uid == null)
            return null;
        return (0, agent_visibility_storage_1.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 = (0, agent_visibility_storage_1.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) {
                (0, agent_visibility_storage_1.writeAgentVisibilityToStorage)(storageKey, next);
            }
            return next;
        });
    }, [storageKey]);
    return [visible, setVisiblePersisted, resolvedTableId];
}
