"use client";
import { useCallback, useSyncExternalStore } from "react";
const STORAGE_KEY_PREFIX = "stigmer:recent-workspaces:";
const MAX_RECENT = 8;
function storageKey(scopeId) {
    return `${STORAGE_KEY_PREFIX}${scopeId}`;
}
function readEntries(scopeId) {
    try {
        const raw = localStorage.getItem(storageKey(scopeId));
        if (!raw)
            return [];
        return JSON.parse(raw);
    }
    catch {
        return [];
    }
}
function writeEntries(scopeId, entries) {
    try {
        localStorage.setItem(storageKey(scopeId), JSON.stringify(entries));
    }
    catch {
        // localStorage full or unavailable — silently degrade.
    }
}
function sortEntries(entries) {
    return [...entries].sort((a, b) => {
        if (a.pinned !== b.pinned)
            return a.pinned ? -1 : 1;
        return b.lastUsed - a.lastUsed;
    });
}
const listeners = new Set();
let snapshotVersion = 0;
function notifyListeners() {
    snapshotVersion++;
    for (const fn of listeners)
        fn();
}
function subscribe(callback) {
    listeners.add(callback);
    return () => listeners.delete(callback);
}
const EMPTY = [];
let cachedScopeId = null;
let cachedVersion = -1;
let cachedResult = EMPTY;
function getSnapshot(scopeId) {
    if (!scopeId)
        return EMPTY;
    if (scopeId === cachedScopeId && snapshotVersion === cachedVersion) {
        return cachedResult;
    }
    cachedScopeId = scopeId;
    cachedVersion = snapshotVersion;
    cachedResult = sortEntries(readEntries(scopeId));
    return cachedResult;
}
/**
 * Manages recently used workspace paths, persisted in `localStorage`.
 *
 * Entries are keyed by `scopeId` (e.g. a session ID or machine identifier)
 * so each scope maintains its own history. Pinned paths appear first,
 * then by most-recently-used.
 *
 * @param scopeId - Scope to key the history to. When `null`, returns empty.
 */
export function useRecentWorkspaces(scopeId) {
    const entries = useSyncExternalStore(subscribe, () => getSnapshot(scopeId), () => EMPTY);
    const recordSelection = useCallback((path) => {
        if (!scopeId)
            return;
        const existing = readEntries(scopeId);
        const idx = existing.findIndex((e) => e.path === path);
        const now = Date.now();
        let updated;
        if (idx >= 0) {
            updated = [...existing];
            updated[idx] = { ...updated[idx], lastUsed: now };
        }
        else {
            updated = [{ path, pinned: false, lastUsed: now }, ...existing];
        }
        if (updated.length > MAX_RECENT) {
            const unpinned = updated.filter((e) => !e.pinned);
            if (unpinned.length > 0) {
                unpinned.sort((a, b) => a.lastUsed - b.lastUsed);
                const oldest = unpinned[0];
                updated = updated.filter((e) => e !== oldest);
            }
        }
        writeEntries(scopeId, updated);
        notifyListeners();
    }, [scopeId]);
    const togglePin = useCallback((path) => {
        if (!scopeId)
            return;
        const existing = readEntries(scopeId);
        const idx = existing.findIndex((e) => e.path === path);
        if (idx < 0)
            return;
        const updated = [...existing];
        updated[idx] = { ...updated[idx], pinned: !updated[idx].pinned };
        writeEntries(scopeId, updated);
        notifyListeners();
    }, [scopeId]);
    const remove = useCallback((path) => {
        if (!scopeId)
            return;
        const updated = readEntries(scopeId).filter((e) => e.path !== path);
        writeEntries(scopeId, updated);
        notifyListeners();
    }, [scopeId]);
    return { entries, recordSelection, togglePin, remove };
}
//# sourceMappingURL=useRecentWorkspaces.js.map