#cr-chatbot-container {
    border: 1px solid #ccc;
    border-radius: 8px;
    max-width: 600px;
    margin: 20px auto;
    display: flex;
    flex-direction: column;
    min-height: 200px; /* Minimum height to start with */
    max-height: 70vh; /* Maximum height as a percentage of viewport */
    overflow: hidden;
}

/* Styling for the Upload and Reset buttons */
#cr-chatbot-upload-btn,
#cr-chatbot-reset-btn {
    /* Add your own styles here */
    background-color: #5cb85c;
    color: white;
    border: none;
    padding: 8px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    margin-left: 5px;
}

/* Ensure the text within the popup content is a readable color */
#cr-privacy-popup .cr-privacy-content,
#cr-privacy-popup .cr-privacy-content p,
#cr-privacy-popup .cr-privacy-content h3 {
    color: #333333 !important; /* A dark gray for good readability */
}

/* Ensure the link to the privacy policy is also readable */
#cr-privacy-popup .cr-privacy-content a {
    color: #0073aa !important; /* A standard blue for links */
}

/* Styles for the privacy policy pop-up and overlay */
#cr-privacy-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 1000; /* Must be on top of everything */
}

#cr-privacy-popup {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    z-index: 1001; /* Must be on top of the overlay */
    max-width: 400px;
    text-align: center;
}

.cr-privacy-content h3 {
    margin-top: 0;
}

#cr-privacy-agree-btn {
    margin-top: 15px;
    padding: 10px 20px;
    background-color: #0073aa;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

#cr-chatbot-upload-btn:hover,
#cr-chatbot-reset-btn:hover {
    background-color: #4cae4c;
}


#cr-chatbot-messages {
    flex: 1;
    padding: 10px;
    overflow-y: auto; /* This is the key for scrolling */
    display: flex;
    flex-direction: column;
}

.cr-chatbot-message {
    padding: 8px 12px;
    border-radius: 12px;
    margin-bottom: 10px;
    word-wrap: break-word;
    max-width: 80%;
}
.cr-chatbot-user {
    background-color: #0073aa;
    color: #fff;
    align-self: flex-end;
}
.cr-chatbot-assistant {
    background-color: #f1f1f1;
    color: #333;
    align-self: flex-start;
}
#cr-chatbot-input-area {
    display: flex;
    padding: 10px;
    border-top: 1px solid #ccc;
}
#cr-chatbot-input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 20px;
    margin-right: 10px;
}
#cr-chatbot-send {
    padding: 10px 20px;
    border: none;
    background-color: #0073aa;
    color: white;
    border-radius: 20px;
    cursor: pointer;
}
#cr-review-summary-display {
    max-width: 600px;
    margin: 20px auto;
    padding: 20px;
    background-color: #f9f9f9;
    border: 1px solid #eee;
    border-radius: 8px;
}
.cr-summary-content {
    white-space: pre-wrap;
}

jQuery(document).ready(function($) {
    const chatboxMessages = $('#cr-chatbot-messages');
    const userInput = $('#cr-chatbot-input');
    const sendButton = $('#cr-chatbot-send');
    const summaryDisplay = $('#cr-review-summary-display');

    const conversationKey = 'crChatbotConversation';
    const stateKey = 'crChatbotState';
    const states = [
        'greeting', 'privacy_ack', 'ask_name', 'ask_email', 'ask_location_age',
        'ask_product_name', 'ask_product_likes', 'ask_product_dislikes',
        'ask_product_improvements', 'ask_testing_details', 'ask_recommendation',
        'ask_star_rating', 'summarize', 'finished'
    ];

    let conversationHistory = JSON.parse(localStorage.getItem(conversationKey) || '[]');
    let currentState = localStorage.getItem(stateKey) || 'greeting';

    if (conversationHistory.length > 0 && currentState !== 'finished') {
        conversationHistory.forEach(msg => addMessage(msg.content, msg.role, false));
        const lastAssistantMessage = conversationHistory.slice().reverse().find(msg => msg.role === 'assistant');
        if (lastAssistantMessage) {
            setTimeout(() => addMessage(lastAssistantMessage.content, 'assistant', false), 500);
        }
    } else {
        setTimeout(() => addMessage("Hello! I'm your AI review assistant. To begin, please confirm that you have read and agree to our privacy policy regarding the collection of your data for this review.", 'assistant'), 500);
    }

    function addMessage(text, sender, save = true) {
        const message = $('<div>').addClass(`cr-chatbot-message cr-chatbot-${sender}`).text(text);
        chatboxMessages.append(message);
        chatboxMessages.scrollTop(chatboxMessages.prop('scrollHeight'));
        if (save) {
            conversationHistory.push({ role: sender === 'user' ? 'user' : 'assistant', content: text });
            localStorage.setItem(conversationKey, JSON.stringify(conversationHistory));
        }
    }

    function sendMessage() {
        const message = userInput.val().trim();
        if (message === '' && currentState !== 'privacy_ack') {
            addMessage("Please provide a response to continue.", 'assistant');
            return;
        }
        if (message === '' && currentState === 'privacy_ack') {
            addMessage("I agree", 'user');
        } else {
            addMessage(message, 'user');
        }
        userInput.val('');

        if (currentState === 'summarize') {
            sendForSummary();
        } else {
            const originalState = currentState;
            $.ajax({
                url: crChatbot.ajax_url,
                type: 'POST',
                data: {
                    action: 'cr_handle_chat',
                    nonce: crChatbot.nonce,
                    state: originalState, // Send the original state
                    user_message: message,
                },
                success: function(response) {
                    if (response.success) {
                        const nextState = response.data.next_state;
                        if (nextState && nextState !== originalState) {
                            currentState = nextState;
                            localStorage.setItem(stateKey, currentState);
                        }
                        addMessage(response.data.message, 'assistant');
                    } else {
                        addMessage('Error: ' + response.data, 'assistant');
                    }
                },
                error: function() {
                    addMessage('An error occurred. Please try again.', 'assistant');
                }
            });
        }
    }

    function sendForSummary() {
        addMessage("Thank you for providing the details. Please wait while I generate a summary.", 'assistant');
        $.ajax({
            url: crChatbot.ajax_url,
            type: 'POST',
            data: {
                action: 'cr_handle_summary',
                nonce: crChatbot.nonce,
                history: conversationHistory,
            },
            success: function(response) {
                if (response.success) {
                    summaryDisplay.html(
                        `<h3>Review Summary</h3><div class="cr-summary-content">${response.data.summary}</div>`
                    );
                    addMessage("Here is the summary of your review. Thank you, goodbye!", 'assistant');
                    currentState = 'finished';
                    localStorage.setItem(stateKey, currentState);
                    // Hide the input field after finishing
                    $('#cr-chatbot-input-area').hide();
                } else {
                    addMessage('Error: ' + response.data, 'assistant');
                }
            },
            error: function() {
                addMessage('An error occurred during summarization.', 'assistant');
            }
        });
    }

    sendButton.on('click', sendMessage);
    userInput.on('keypress', function(e) {
        if (e.which === 13) {
            sendMessage();
        }
    });
});
