document.addEventListener('DOMContentLoaded', () => {
    // DOM Elements
    const jsonFileInput = document.getElementById('jsonFileInput');
    const responsesListEl = document.getElementById('responses-list');
    const noDataMessageEl = document.getElementById('no-data-message');
    const summaryStatsEl = document.getElementById('summary-stats');

    // State variables
    let responseData = [];
    let currentPage = 1;
    const itemsPerPage = 5;

    // Event Listeners
    jsonFileInput.addEventListener('change', handleFileUpload);
    
    // Function to handle file uploads
    function handleFileUpload(event) {
        const file = event.target.files[0];
        if (!file) return;
        
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                responseData = JSON.parse(e.target.result);
                if (Array.isArray(responseData) && responseData.length > 0) {
                    // Hide no data message and show responses
                    noDataMessageEl.style.display = 'none';
                    responsesListEl.style.display = 'block';
                    
                    // Display data
                    displaySummaryStats(responseData);
                    displayResponses(responseData, currentPage);
                } else {
                    throw new Error('Invalid data format: Expected an array of responses');
                }
            } catch (error) {
                console.error('Error parsing JSON file:', error);
                alert(`Error parsing JSON file: ${error.message}`);
            }
        };
        reader.readAsText(file);
    }
    
    // Function to display summary statistics
    function displaySummaryStats(data) {
        const totalResponses = data.length;
        const modelCounts = {};
        let correctCount = 0;
        let skippedCount = 0;
        
        data.forEach(item => {
            // Count models
            if (item.model) {
                modelCounts[item.model] = (modelCounts[item.model] || 0) + 1;
            }
            
            // Count correct responses
            if (item.answer1 === item.resolution) {
                correctCount++;
            }
            
            // Count skipped questions
            if (item.skipped) {
                skippedCount++;
            }
        });
        
        // Create and sort model stats
        const modelStats = Object.entries(modelCounts)
            .map(([model, count]) => ({ model, count }))
            .sort((a, b) => b.count - a.count);
        
        // Build the HTML for summary stats
        let statsHTML = `
            <h2>Summary Statistics</h2>
            <p><strong>Total Responses:</strong> ${totalResponses}</p>
            <p><strong>Correct Responses:</strong> ${correctCount} (${((correctCount / totalResponses) * 100).toFixed(2)}%)</p>
            <p><strong>Skipped Questions:</strong> ${skippedCount} (${((skippedCount / totalResponses) * 100).toFixed(2)}%)</p>
        `;
        
        if (modelStats.length > 0) {
            statsHTML += '<h3>Models</h3><ul class="stats-list">';
            modelStats.forEach(stat => {
                statsHTML += `<li>${stat.model}: ${stat.count} responses</li>`;
            });
            statsHTML += '</ul>';
        }
        
        summaryStatsEl.innerHTML = statsHTML;
    }
    
    // Function to display responses with pagination
    function displayResponses(data, page) {
        // Calculate pagination
        const startIndex = (page - 1) * itemsPerPage;
        const endIndex = Math.min(startIndex + itemsPerPage, data.length);
        const pageData = data.slice(startIndex, endIndex);
        
        // Clear responses list
        responsesListEl.innerHTML = '';
        
        // Add response items
        pageData.forEach((item, index) => {
            const responseEl = createResponseElement(item, startIndex + index + 1);
            responsesListEl.appendChild(responseEl);
        });
        
        // Add pagination controls
        addPaginationControls(data.length, page);
        
        // Add toggle functionality to expandable content
        addToggleability();
    }
    
    // Function to create a response element
    function createResponseElement(item, number) {
        // Create container
        const responseEl = document.createElement('div');
        responseEl.className = 'response-item';
        
        // Parse question and metadata from prompt if available
        let mainQuestion = 'Question not available';
        let background = '';
        let resolutionCriteria = '';
        let closeDate = '';
        let options = [];
        
        if (item.prompt) {
            // Extract the main question
            const questionMatch = item.prompt.match(/Question:(.*?)(?=Background:|Resolution Criteria:|Question close date:|$)/s);
            if (questionMatch && questionMatch[1]) {
                mainQuestion = questionMatch[1].trim();
            }
            
            // Extract background info
            const backgroundMatch = item.prompt.match(/Background:(.*?)(?=Resolution Criteria:|Question close date:|$)/s);
            if (backgroundMatch && backgroundMatch[1]) {
                background = backgroundMatch[1].trim();
            }
            
            // Extract resolution criteria
            const resolutionMatch = item.prompt.match(/Resolution Criteria:(.*?)(?=Question close date:|$)/s);
            if (resolutionMatch && resolutionMatch[1]) {
                resolutionCriteria = resolutionMatch[1].trim();
            }
            
            // Extract close date
            const closeDateMatch = item.prompt.match(/Question close date:(.*?)(?=$)/s);
            if (closeDateMatch && closeDateMatch[1]) {
                closeDate = closeDateMatch[1].trim();
            }
            
            // Extract options (A, B, C, etc.) if present
            const optionRegex = /([A-F])\.\s+(.*?)(?=[A-F]\.|Background:|Resolution Criteria:|Question close date:|$)/gs;
            let match;
            while ((match = optionRegex.exec(item.prompt)) !== null) {
                options.push({ letter: match[1], text: match[2].trim() });
            }
        }
        
        // Extract correct answer and status
        const isCorrect = item.answer1 === item.resolution;
        const wasSkipped = item.skipped === true;
        
        // Create HTML for the response header
        responseEl.innerHTML = `
            <div class="response-header">
                <div>
                    <h2>Response #${number}</h2>
                    <span class="model-name">${item.model || 'Unknown Model'}</span>
                </div>
                <div class="response-tags">
                    ${wasSkipped ? '<span class="tag skipped">Skipped</span>' : ''}
                    ${isCorrect ? '<span class="tag correct">Correct</span>' : '<span class="tag incorrect">Incorrect</span>'}
                </div>
            </div>
            
            <div class="question-section">
                <div class="question-main">
                    <strong>Question:</strong> ${mainQuestion}
                    ${options.length > 0 ? '<ul class="options-list">' + 
                        options.map(opt => `<li><strong>${opt.letter}.</strong> ${opt.text}</li>`).join('') + 
                        '</ul>' : ''}
                </div>
                
                ${background || resolutionCriteria || closeDate ? `
                <div class="question-details-toggle">
                    <button class="toggle-btn">Show additional details</button>
                    <div class="question-details" style="display: none;">
                        ${background ? `<div class="detail-item"><strong>Background:</strong> ${background}</div>` : ''}
                        ${resolutionCriteria ? `<div class="detail-item"><strong>Resolution Criteria:</strong> ${resolutionCriteria}</div>` : ''}
                        ${closeDate ? `<div class="detail-item"><strong>Question close date:</strong> ${closeDate}</div>` : ''}
                    </div>
                </div>` : ''}
            </div>
        `;
        
        // Parse the model response to extract the reasoning steps
        const responseContent = document.createElement('div');
        responseContent.className = 'response-content-container';
        
        if (item.response) {
            // Get initial text before first <prior> tag
            const initialTextMatch = item.response.match(/^(.*?)(?=<prior_1>|<think>)/s);
            const initialText = initialTextMatch ? initialTextMatch[1].trim() : '';
            
            // Create initial text element
            const initialTextEl = document.createElement('div');
            initialTextEl.className = 'initial-response';
            initialTextEl.innerHTML = initialText.replace(/\n/g, '<br>');
            responseContent.appendChild(initialTextEl);
            
            // Extract all think/prior pairs
            const thinkPriorRegex = /<think>(.*?)<\/think>\s*<prior_(\d+)>(.*?)<\/prior_\d+>/gs;
            const priorFinalRegex = /<prior_final>(.*?)<\/prior_final>/s;
            
            let priorMatch;
            const priorBlocks = [];
            
            // Add all intermediate thinking/prior steps
            while ((priorMatch = thinkPriorRegex.exec(item.response)) !== null) {
                const thinkContent = priorMatch[1].trim();
                const priorNumber = priorMatch[2];
                const priorContent = priorMatch[3].trim();
                
                priorBlocks.push({
                    number: priorNumber,
                    think: thinkContent,
                    prior: priorContent
                });
            }
            
            // Create reasoning steps accordion
            if (priorBlocks.length > 0) {
                const reasoningSteps = document.createElement('div');
                reasoningSteps.className = 'reasoning-steps';
                
                const reasoningHeader = document.createElement('h3');
                reasoningHeader.textContent = 'Reasoning Steps';
                reasoningSteps.appendChild(reasoningHeader);
                
                priorBlocks.forEach(block => {
                    const stepContainer = document.createElement('div');
                    stepContainer.className = 'reasoning-step';
                    
                    const stepToggle = document.createElement('div');
                    stepToggle.className = 'step-toggle';
                    stepToggle.innerHTML = `<span class="step-number">Step ${block.number}</span>`;
                    stepToggle.addEventListener('click', () => {
                        stepContent.style.display = stepContent.style.display === 'none' ? 'block' : 'none';
                        stepToggle.classList.toggle('active');
                    });
                    
                    const stepContent = document.createElement('div');
                    stepContent.className = 'step-content';
                    stepContent.style.display = 'none';
                    
                    const thinkContent = document.createElement('div');
                    thinkContent.className = 'think-content';
                    thinkContent.innerHTML = `<strong>Thinking:</strong><div class="thought-text">${block.think.replace(/\n/g, '<br>')}</div>`;
                    
                    const priorContent = document.createElement('div');
                    priorContent.className = 'prior-content';
                    
                    // Format prior content nicely
                    let formattedPrior = '<strong>Updated Probabilities:</strong><div class="probability-bars">';
                    
                    // Extract probabilities with regex
                    const probRegex = /<([A-F])>\s*([\d.]+)\s*<\/\1>/g;
                    let probMatch;
                    const probs = [];
                    
                    while ((probMatch = probRegex.exec(block.prior)) !== null) {
                        probs.push({
                            option: probMatch[1],
                            value: parseFloat(probMatch[2])
                        });
                    }
                    
                    // Add probability bars
                    probs.forEach(prob => {
                        const percentage = (prob.value * 100).toFixed(1);
                        formattedPrior += `
                            <div class="prob-item">
                                <div class="prob-label">Option ${prob.option}</div>
                                <div class="prob-bar-container">
                                    <div class="prob-bar" style="width: ${percentage}%"></div>
                                    <div class="prob-value">${percentage}%</div>
                                </div>
                            </div>
                        `;
                    });
                    
                    formattedPrior += '</div>';
                    priorContent.innerHTML = formattedPrior;
                    
                    stepContent.appendChild(thinkContent);
                    stepContent.appendChild(priorContent);
                    
                    stepContainer.appendChild(stepToggle);
                    stepContainer.appendChild(stepContent);
                    reasoningSteps.appendChild(stepContainer);
                });
                
                responseContent.appendChild(reasoningSteps);
            }
            
            // Extract final answer
            const finalMatch = priorFinalRegex.exec(item.response);
            if (finalMatch) {
                const finalPrior = finalMatch[1].trim();
                
                const finalAnswerEl = document.createElement('div');
                finalAnswerEl.className = 'final-probabilities';
                
                // Format final probabilities
                let formattedFinal = '<h3>Final Probabilities</h3><div class="probability-bars final">';
                
                // Extract probabilities with regex
                const probRegex = /<([A-F])>\s*([\d.]+)\s*<\/\1>/g;
                let probMatch;
                const finalProbs = [];
                
                while ((probMatch = probRegex.exec(finalPrior)) !== null) {
                    finalProbs.push({
                        option: probMatch[1],
                        value: parseFloat(probMatch[2])
                    });
                }
                
                // Find highest probability
                let maxProb = 0;
                let maxOption = '';
                finalProbs.forEach(prob => {
                    if (prob.value > maxProb) {
                        maxProb = prob.value;
                        maxOption = prob.option;
                    }
                });
                
                // Add probability bars
                finalProbs.forEach(prob => {
                    const percentage = (prob.value * 100).toFixed(1);
                    const isHighest = prob.option === maxOption;
                    
                    formattedFinal += `
                        <div class="prob-item ${isHighest ? 'highest' : ''}">
                            <div class="prob-label">Option ${prob.option}</div>
                            <div class="prob-bar-container">
                                <div class="prob-bar" style="width: ${percentage}%"></div>
                                <div class="prob-value">${percentage}%</div>
                            </div>
                        </div>
                    `;
                });
                
                formattedFinal += '</div>';
                finalAnswerEl.innerHTML = formattedFinal;
                
                responseContent.appendChild(finalAnswerEl);
            }
        }
        
        responseEl.appendChild(responseContent);
        
        // Add final answer comparison section
        const finalAnswerComparisonEl = document.createElement('div');
        finalAnswerComparisonEl.className = 'final-answer';
        finalAnswerComparisonEl.innerHTML = `
            <div>
                <strong>Model's Answer:</strong> 
                <span class="${isCorrect ? 'correct' : 'incorrect'}">
                    ${item.answer1 || 'Not available'}
                </span>
            </div>
            <div>
                <strong>Correct Answer:</strong> 
                <span class="correct">${item.resolution || 'Not available'}</span>
            </div>
        `;
        responseEl.appendChild(finalAnswerComparisonEl);
        
        // Add confidence display if values are available
        if (item.values && Array.isArray(item.values) && item.values.length > 0) {
            const probDiv = document.createElement('div');
            probDiv.className = 'probabilities';
            
            // Find highest probability
            const maxProb = Math.max(...item.values);
            
            // Add probability items
            options.forEach((opt, i) => {
                if (i < item.values.length) {
                    const probItem = document.createElement('div');
                    probItem.className = 'probability-item';
                    
                    if (item.values[i] === maxProb) {
                        probItem.classList.add('highest-probability');
                    }
                    
                    probItem.textContent = `${opt.letter}: ${(item.values[i] * 100).toFixed(1)}%`;
                    probDiv.appendChild(probItem);
                }
            });
            
            // If no options were found, just show raw probabilities
            if (options.length === 0 && item.values.length > 0) {
                item.values.forEach((val, i) => {
                    const probItem = document.createElement('div');
                    probItem.className = 'probability-item';
                    
                    if (val === maxProb) {
                        probItem.classList.add('highest-probability');
                    }
                    
                    const optionLetters = ['A', 'B', 'C', 'D', 'E', 'F'];
                    const letter = i < optionLetters.length ? optionLetters[i] : `Option ${i+1}`;
                    
                    probItem.textContent = `${letter}: ${(val * 100).toFixed(1)}%`;
                    probDiv.appendChild(probItem);
                });
            }
            
            responseEl.appendChild(probDiv);
        }
        
        return responseEl;
    }
    
    // Function to add pagination controls
    function addPaginationControls(totalItems, currentPage) {
        const totalPages = Math.ceil(totalItems / itemsPerPage);
        
        // Create pagination container
        const paginationEl = document.createElement('div');
        paginationEl.className = 'pagination';
        
        // Previous button
        const prevButton = document.createElement('button');
        prevButton.textContent = 'Previous';
        prevButton.disabled = currentPage === 1;
        prevButton.addEventListener('click', () => {
            if (currentPage > 1) {
                displayResponses(responseData, currentPage - 1);
            }
        });
        
        // Next button
        const nextButton = document.createElement('button');
        nextButton.textContent = 'Next';
        nextButton.disabled = currentPage === totalPages;
        nextButton.addEventListener('click', () => {
            if (currentPage < totalPages) {
                displayResponses(responseData, currentPage + 1);
            }
        });
        
        // Page info
        const pageInfo = document.createElement('span');
        pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;
        
        // Add elements to pagination
        paginationEl.appendChild(prevButton);
        paginationEl.appendChild(pageInfo);
        paginationEl.appendChild(nextButton);
        
        // Add pagination to responses list
        responsesListEl.appendChild(paginationEl);
    }
    
    // Function to add toggle functionality to expandable content
    function addToggleability() {
        // Add toggle for question details
        const detailToggles = document.querySelectorAll('.toggle-btn');
        detailToggles.forEach(toggle => {
            toggle.addEventListener('click', function() {
                const details = this.nextElementSibling;
                details.style.display = details.style.display === 'none' ? 'block' : 'none';
                this.textContent = details.style.display === 'none' ? 'Show additional details' : 'Hide additional details';
            });
        });
        
        // Add toggle for original toggleable content
        const toggleables = document.querySelectorAll('.toggleable');
        toggleables.forEach(toggle => {
            toggle.addEventListener('click', (e) => {
                const content = toggle.querySelector('.toggleable-content');
                content.classList.toggle('collapsed');
            });
        });
    }
}); 