// Partial: _cookie-persistence.js.j2 — Unified state save/load (both modes)
// Implements: REQ-p00006-A
// Single cookie shared between edit and view modes for seamless state transfer

const COOKIE_NAME = 'elspais_trace_state';
const COOKIE_DAYS = 30;
const COOKIE_VERSION = 10;  // v10: remove codeRefs + indirectCoverage filters

function saveState() {
    const stateToSave = {
        _v: COOKIE_VERSION,
        editEnabled: editState.enabled,
        openCardIds: editState.openCardOrder,
        activeNavTab: editState.activeNavTab,
        collapsedTreeNodes: Array.from(editState.collapsedTreeNodes),
        collapsedCards: [],
        activeFilters: editState.activeFilters,
        filterStatus: editState.filterStatus,
        filterCoverage: editState.filterCoverage,
        fontSize: editState.fontSize,
        theme: editState.theme,
        toolbarHidden: editState.toolbarHidden,
        navPanelWidth: document.getElementById('nav-panel').style.width || null,
        fileViewerWidth: document.getElementById('file-viewer-panel').style.width || null
    };
    // Track which cards are collapsed
    editState.openCards.forEach(function(info, id) {
        if (info.collapsed) stateToSave.collapsedCards.push(id);
    });
    var expires = new Date(Date.now() + COOKIE_DAYS * 864e5).toUTCString();
    document.cookie = COOKIE_NAME + '=' + encodeURIComponent(JSON.stringify(stateToSave)) +
        '; expires=' + expires + '; path=/; SameSite=Lax';
}

function loadState() {
    var match = document.cookie.match(new RegExp('(^| )' + COOKIE_NAME + '=([^;]+)'));
    if (!match) return null;
    try {
        var saved = JSON.parse(decodeURIComponent(match[2]));
        if (!saved._v || saved._v < COOKIE_VERSION) return null;  // discard stale cookie
        return saved;
    } catch (e) {
        return null;
    }
}

function clearState() {
    document.cookie = COOKIE_NAME + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Lax';
}
