/**
 * ExcludedStore - Persists "Mark not needed" (excluded) node IDs to localStorage.
 * Keyed by connectionId + platformType. Later will wire to DB.
 */
const ExcludedStore = {
    getStorageKey(connectionId, platformType) {
        return `chameleonExcluded_${platformType || 'Unknown'}_${connectionId || 0}`;
    },
    getExcludedIds(connectionId, platformType) {
        try {
            const key = this.getStorageKey(connectionId, platformType);
            const raw = localStorage.getItem(key);
            if (!raw) return new Set();
            const arr = JSON.parse(raw);
            return new Set(Array.isArray(arr) ? arr : []);
        } catch (e) {
            console.warn('ExcludedStore.getExcludedIds:', e);
            return new Set();
        }
    },
    setExcluded(connectionId, platformType, nodeId, excluded) {
        const ids = this.getExcludedIds(connectionId, platformType);
        if (excluded) {
            ids.add(nodeId);
        } else {
            ids.delete(nodeId);
        }
        const key = this.getStorageKey(connectionId, platformType);
        localStorage.setItem(key, JSON.stringify([...ids]));
        return ids;
    },
    toggleExcluded(connectionId, platformType, nodeId) {
        const ids = this.getExcludedIds(connectionId, platformType);
        const excluded = !ids.has(nodeId);
        return this.setExcluded(connectionId, platformType, nodeId, excluded);
    },
    isExcluded(connectionId, platformType, nodeId) {
        return this.getExcludedIds(connectionId, platformType).has(nodeId);
    },
    getExcludedCount(connectionId, platformType) {
        return this.getExcludedIds(connectionId, platformType).size;
    },
    /** After a Custom JSON file is removed from disk: drop exclusions for that file and any virtual JSON tree nodes under it (<c>j|sameRel|…</c>). */
    removeStaleAfterCustomJsonFileDeleted(connectionId, platformType, physicalFileNodeId) {
        const nid = String(physicalFileNodeId || '');
        if (!nid.startsWith('f|')) return;
        const rel = nid.slice(2);
        if (!rel) return;
        const ids = this.getExcludedIds(connectionId, platformType);
        const jPrefix = 'j|' + rel + '|';
        let changed = false;
        for (const id of [...ids]) {
            const s = String(id);
            if (s === nid || s.startsWith(jPrefix)) {
                ids.delete(id);
                changed = true;
            }
        }
        if (changed) {
            const key = this.getStorageKey(connectionId, platformType);
            localStorage.setItem(key, JSON.stringify([...ids]));
        }
    }
};
