// ==UserScript==
// @name         EnhancedChatality
// @version      9000.1
// @description  Handles Unhandlablaments
// @match        *://yuntian-deng-chatgpt.hf.space/*
// @grant        none
// @require      https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js
// ==/UserScript==

/* global JSZip */
(function () {
    'use strict';

    const SESSION_PRESET_KEY = 'enhancedChat_preResetHistory';
    const SESSION_POSTSET_KEY = 'enhancedChat_postResetHistory';

    // Load previous states from session storage
    let preResetHistory = JSON.parse(sessionStorage.getItem(SESSION_PRESET_KEY)) || [];
    let postResetHistory = JSON.parse(sessionStorage.getItem(SESSION_POSTSET_KEY)) || [];

    // Adjust selector based on original HTML structure for the chat message container
    const messageWrapSelector = '.bubble-wrap.svelte-1e1jlin'; // Adjust this selector based on actual HTML
    const inputBoxSelector = 'textarea[data-testid="textbox"]'; // Ensure this selector points to the input box

    // Initialize MutationObserver to monitor messages
    initializeObservers();

    function initializeObservers() {
        const messageWrap = document.querySelector(messageWrapSelector);
        if (messageWrap) {
            const observer = new MutationObserver(mutations => {
                for (const mutation of mutations) {
                    if (mutation.addedNodes.length) {
                        mutation.addedNodes.forEach(node => {
                            if (node.nodeType === 1 && node.classList.contains('message-row')) {
                                handleNewMessage(node.innerText.trim());
                            }
                        });
                    }
                }
            });
            observer.observe(messageWrap, { childList: true, subtree: true });
        } else {
            console.error("Message wrap not found. Ensure the selector matches the chat structure.");
        }

        const inputBox = document.querySelector(inputBoxSelector);
        if (inputBox) {
            inputBox.addEventListener('keydown', handleUserCommand);
        } else {
            console.error("Input box not found. Ensure the selector matches the input field structure.");
        }
    }

    function handleNewMessage(messageText) {
        console.log('New message detected:', messageText);
        postResetHistory.push(messageText);  // Keep track of new messages
        storeChatHistory();  // Save the updated history to session storage
    }

    function handleUserCommand(event) {
        const inputBox = document.querySelector(inputBoxSelector);
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault();  // Prevent adding a new line
            const command = inputBox.value.trim().toLowerCase();
            if (command === 'sve') {
                saveChatHistory(); // Execute save command
                inputBox.value = ''; // Clear input field
            } else if (command === 'svr') {
                copyChatHistoryToClipboard(); // Execute copy command
                inputBox.value = ''; // Clear input field
            }
        }
    }

    function storeChatHistory() {
        sessionStorage.setItem(SESSION_PRESET_KEY, JSON.stringify(preResetHistory));
        sessionStorage.setItem(SESSION_POSTSET_KEY, JSON.stringify(postResetHistory));
        console.log('Chat history stored successfully:', { preResetHistory, postResetHistory });
    }

    function saveChatHistory() {
        console.log("Saving chat history...");

        const zip = new JSZip();
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
        
        // Save both histories into the zip
        zip.file('pre_reset_history.txt', preResetHistory.join('\n'));
        zip.file('post_reset_history.txt', postResetHistory.join('\n'));

        zip.generateAsync({ type: 'blob' }).then(content => {
            const blobURL = URL.createObjectURL(content);
            const a = document.createElement('a');
            a.href = blobURL;
            a.download = `chat_histories_${timestamp}.zip`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            console.log('Chat histories saved successfully.');
        });
    }

    function copyChatHistoryToClipboard() {
        console.log("Copying chat history to clipboard...");
        const chatContent = postResetHistory.join('\n');
        navigator.clipboard.writeText(chatContent).then(() => {
            console.log('Post-reset chat history copied to clipboard.');
        }).catch(err => {
            console.error('Failed to copy chat history:', err);
        });
    }

    // Load any initial state on page load if necessary
    window.addEventListener('load', () => {
        console.log('Chat monitor script loaded and initialized.');
    });
})();