// Undo + Redo stack with action labels
window.undoStack = window.undoStack || [];
window.redoStack = window.redoStack || [];

window.pushUndo = function(label) {
    const snapshot = {
        label: label || 'Edit',
        timestamp: Date.now(),
        vmoState: window.vmoState || { blocks: [] },
        lastContent: window.lastContent || '',
        chat: window.vmoChatHistory || [],
        images: window.vmoImages || []
    };
    // Deep copy so later mutations don't leak into history
    window.undoStack.push(JSON.stringify(snapshot));
    if (window.undoStack.length > 20) window.undoStack.shift();
    // Clear redo stack on new action (standard behavior)
    window.redoStack = [];
};
window.popUndo = function() {
    if (window.undoStack.length > 1) {
        // Push current state to redo stack before restoring
        const currentSnapshot = {
            label: 'Before undo',
            timestamp: Date.now(),
            vmoState: window.vmoState || { blocks: [] },
            lastContent: window.lastContent || '',
            chat: window.vmoChatHistory || [],
            images: window.vmoImages || []
        };
        window.redoStack.push(JSON.stringify(currentSnapshot));
        if (window.redoStack.length > 20) window.redoStack.shift();

        // Pop and restore
        window.undoStack.pop(); // remove current state
        const snapshot = JSON.parse(window.undoStack[window.undoStack.length - 1]);
        if (snapshot && snapshot.vmoState) {
            window.vmoState = snapshot.vmoState;
        }
        if (snapshot && typeof snapshot.lastContent === 'string') {
            window.lastContent = snapshot.lastContent;
        } else if (window.vmoState && Array.isArray(window.vmoState.blocks)) {
            window.lastContent = window.vmoState.blocks.map(b => b.html).join('\n');
        }
        if (snapshot && Array.isArray(snapshot.chat)) {
            window.vmoChatHistory = snapshot.chat;
        }
        if (snapshot && Array.isArray(snapshot.images)) {
            window.vmoImages = snapshot.images;
        }

        if (typeof window.renderBlocks === 'function') window.renderBlocks();
        const actionLabel = snapshot.label ? (' — ' + snapshot.label) : '';
        window.showToast('Undo successful' + actionLabel + ' ✅', 'success');
        window.isUnsaved = true;
    } else if (window.undoStack.length === 1) {
        // Restore to initial state
        const snapshot = JSON.parse(window.undoStack[0]);
        if (snapshot && snapshot.vmoState) window.vmoState = snapshot.vmoState;
        if (snapshot && typeof snapshot.lastContent === 'string') window.lastContent = snapshot.lastContent;
        if (typeof window.renderBlocks === 'function') window.renderBlocks();
        window.showToast('Restored to initial state ✅', 'success');
    } else {
        window.showToast('Nothing to undo.', 'error');
    }
};
window.popRedo = function() {
    if (window.redoStack.length) {
        // Push current state back to undo stack
        const currentSnapshot = {
            label: 'Before redo',
            timestamp: Date.now(),
            vmoState: window.vmoState || { blocks: [] },
            lastContent: window.lastContent || '',
            chat: window.vmoChatHistory || [],
            images: window.vmoImages || []
        };
        window.undoStack.push(JSON.stringify(currentSnapshot));
        if (window.undoStack.length > 20) window.undoStack.shift();

        const snapshot = JSON.parse(window.redoStack.pop());
        if (snapshot && snapshot.vmoState) {
            window.vmoState = snapshot.vmoState;
        }
        if (snapshot && typeof snapshot.lastContent === 'string') {
            window.lastContent = snapshot.lastContent;
        } else if (window.vmoState && Array.isArray(window.vmoState.blocks)) {
            window.lastContent = window.vmoState.blocks.map(b => b.html).join('\n');
        }
        if (snapshot && Array.isArray(snapshot.chat)) {
            window.vmoChatHistory = snapshot.chat;
        }
        if (snapshot && Array.isArray(snapshot.images)) {
            window.vmoImages = snapshot.images;
        }

        if (typeof window.renderBlocks === 'function') window.renderBlocks();
        const actionLabel = snapshot.label ? (' — ' + snapshot.label) : '';
        window.showToast('Redo successful' + actionLabel + ' 🔄', 'success');
        window.isUnsaved = true;
    } else {
        window.showToast('Nothing to redo.', 'error');
    }
};
window.primeUndoStackOnLoad = function(loadedState) {
    window.undoStack = [];
    window.redoStack = [];
    const snapshot = {
        label: 'Initial state',
        timestamp: Date.now(),
        vmoState: loadedState || window.vmoState || { blocks: [] },
        lastContent: window.lastContent || '',
        chat: window.vmoChatHistory || [],
        images: window.vmoImages || []
    };
    window.undoStack.push(JSON.stringify(snapshot));
};

// Keyboard shortcuts: Ctrl+Z for undo, Ctrl+Shift+Z / Ctrl+Y for redo
document.addEventListener('keydown', function(e) {
    // Don't intercept when typing in inputs/textareas
    if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.isContentEditable) return;
    
    if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
        e.preventDefault();
        if (typeof window.popUndo === 'function') window.popUndo();
    }
    if ((e.ctrlKey || e.metaKey) && ((e.key === 'z' && e.shiftKey) || e.key === 'y')) {
        e.preventDefault();
        if (typeof window.popRedo === 'function') window.popRedo();
    }
});