// ==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';

    // Initialize message histories
    let preResetHistory = JSON.parse(sessionStorage.getItem(SESSION_PRESET_KEY)) || [];
    let postResetHistory = JSON.parse(sessionStorage.getItem(SESSION_POSTSET_KEY)) || [];
    
    const messageWrapSelector = '.bubble-wrap.svelte-1e1jlin'; // Adjust as needed based on the chat's structure
    const inputBoxSelector = 'textarea[data-testid="textbox"]'; // Ensure this reflects the correct input field

    // Initialize the MutationObserver
    initializeObservers();

    function initializeObservers() {
        const messageWrap = document.querySelector(messageWrapSelector);
        if (!messageWrap) {
            console.error("Message wrap not found. Please verify the selector.");
            return; // Exit if the chat message wrapper is not found.
        }

        const observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                mutation.addedNodes.forEach(node => {
                    if (node.nodeType === 1 && node.classList.contains('message-row')) {
                        handleNewMessage(node.innerText.trim());
                    }
                });
            });
        });

        observer.observe(messageWrap, { childList: true, subtree: true });

        // Set up listener for user command input
        const inputBox = document.querySelector(inputBoxSelector);
        if (inputBox) {
            inputBox.addEventListener('keydown', handleUserCommand);
        } else {
            console.error("Input box not found. Please verify the selector.");
        }
    }

    function handleNewMessage(messageText) {
        console.log('New message detected:', messageText);
        postResetHistory.push(messageText); // Store new messages in post-reset history
        storeChatHistory(); // Update session storage with new data
    }

    function handleUserCommand(event) {
        const inputBox = document.querySelector(inputBoxSelector);
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault(); // Prevent new lines from being added to the chat
            const command = inputBox.value.trim().toLowerCase();

            if (command === 'sve') {
                saveChatHistory(); // Call to save histories
                inputBox.value = ''; // Clear input after saving
            } else if (command === 'svr') {
                copyChatHistoryToClipboard(); // Call to copy chat history
                inputBox.value = ''; // Clear input after copying
            }
        }
    }

    function storeChatHistory() {
        sessionStorage.setItem(SESSION_PRESET_KEY, JSON.stringify(preResetHistory));
        sessionStorage.setItem(SESSION_POSTSET_KEY, JSON.stringify(postResetHistory));
        console.log('Chat histories saved in session storage:', { 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 file
        zip.file('pre_reset_history.txt', preResetHistory.join('\n'));
        zip.file('post_reset_history.txt', postResetHistory.join('\n'));

        // Generate the zip file and trigger download
        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);
        });
    }

    // Optionally load previous state on script load
    window.addEventListener('load', () => {
        console.log('Chat monitor script loaded and initialized.');
    });
})();