{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-12">
        <h1 class="mb-4">
            <i class="fas fa-cogs me-2"></i>Extraction Management
            <small class="text-muted">Associate outcomes with each other using drag-and-drop</small>
        </h1>
    </div>
</div>

<!-- UNDER/OVER Configuration -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-clock me-2"></i>UNDER/OVER Time Configuration
                </h5>
            </div>
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-md-6">
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="fas fa-stopwatch me-2"></i>Time Limit
                            </span>
                            <input type="number" class="form-control" id="under-over-time-limit"
                                   placeholder="90" min="1" max="300" step="1" value="90">
                            <span class="input-group-text">seconds</span>
                            <button class="btn btn-outline-primary" id="btn-save-time-limit">
                                <i class="fas fa-save me-1"></i>Save
                            </button>
                        </div>
                        <small class="text-muted mt-1 d-block">
                            Time limit between UNDER and OVER outcomes (1-300 seconds)
                        </small>
                    </div>
                    <div class="col-md-6">
                        <!-- UNDER/OVER Drop Zones -->
                        <div class="row">
                            <div class="col-6">
                                <div class="under-over-zone" data-outcome="UNDER">
                                    <div class="under-over-header">UNDER</div>
                                    <div class="under-over-drop" id="under-drop-zone">
                                        <i class="fas fa-arrow-down me-2"></i>
                                        <span class="drop-text">Drop UNDER here</span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="under-over-zone" data-outcome="OVER">
                                    <div class="under-over-header">OVER</div>
                                    <div class="under-over-drop" id="over-drop-zone">
                                        <i class="fas fa-arrow-up me-2"></i>
                                        <span class="drop-text">Drop OVER here</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Redistribution CAP Configuration (Admin Only) -->
{% if current_user.is_admin %}
<div class="row mb-4">
    <div class="col-12">
        <div class="card border-warning">
            <div class="card-header bg-warning text-dark">
                <h5 class="card-title mb-0">
                    <i class="fas fa-percent me-2"></i>Redistribution CAP Configuration
                    <small class="badge bg-dark ms-2">Admin Only</small>
                </h5>
            </div>
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-md-6">
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="fas fa-chart-pie me-2"></i>CAP Percentage
                            </span>
                            <input type="number" class="form-control" id="redistribution-cap"
                                   placeholder="70" min="10" max="100" step="0.1" value="70">
                            <span class="input-group-text">%</span>
                            <button class="btn btn-outline-warning" id="btn-save-redistribution-cap">
                                <i class="fas fa-save me-1"></i>Save
                            </button>
                        </div>
                        <small class="text-muted mt-1 d-block">
                            Maximum redistribution percentage (10% - 100%)
                        </small>
                    </div>
                    <div class="col-md-6">
                        <div class="alert alert-info mb-0">
                            <i class="fas fa-info-circle me-2"></i>
                            <strong>Redistribution CAP</strong><br>
                            Controls the maximum percentage of winnings that can be redistributed during extraction.
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endif %}

<!-- Main Extraction Interface -->
<div class="row">
    <!-- Left Column: Available Outcomes and Results -->
    <div class="col-md-4">
        <!-- Available Outcomes -->
        <div class="card mb-3">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-grip-vertical me-2"></i>Available Outcomes
                </h5>
                <small class="text-muted">Drag outcomes to UNDER/OVER or Results areas</small>
            </div>
            <div class="card-body">
                <div id="outcomes-pool" class="outcomes-pool">
                    <div class="text-center text-muted">
                        <i class="fas fa-spinner fa-spin me-2"></i>Loading outcomes...
                    </div>
                </div>
            </div>
        </div>

        <!-- Results Area -->
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-target me-2"></i>Results
                </h5>
                <small class="text-muted">Drop outcomes here to create association columns</small>
            </div>
            <div class="card-body">
                <div id="results-pool" class="results-pool">
                    <div class="text-center text-muted p-3">
                        <i class="fas fa-arrow-down me-2"></i>
                        Drop outcomes here to create columns for associations
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Right Column: Dynamic Outcome Columns -->
    <div class="col-md-8">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div>
                    <h5 class="card-title mb-0">
                        <i class="fas fa-columns me-2"></i>Outcome Associations
                    </h5>
                    <small class="text-muted">Each outcome gets its own column for associations</small>
                </div>
                <button id="btn-clear-all" class="btn btn-outline-danger btn-sm">
                    <i class="fas fa-trash me-1"></i>Clear All
                </button>
            </div>
            <div class="card-body">
                <div id="outcome-columns" class="outcome-columns">
                    <div class="text-center text-muted p-4">
                        <i class="fas fa-arrow-left me-2"></i>
                        Outcomes will appear here as columns when loaded
                    </div>
                </div>
            </div>
        </div>

        <!-- Trash Bin -->
        <div class="card mt-3">
            <div class="card-body text-center">
                <div id="trash-bin" class="trash-bin">
                    <i class="fas fa-trash-alt fa-2x text-danger"></i>
                    <div class="mt-2">
                        <strong>Drop to Remove Association</strong>
                        <small class="d-block text-muted">Drag associated outcomes here to remove them</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Current Associations Summary -->
<div class="row mt-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-link me-2"></i>Current Associations Summary
                </h5>
            </div>
            <div class="card-body">
                <div id="associations-summary">
                    <div class="text-center text-muted">
                        <i class="fas fa-spinner fa-spin me-2"></i>Loading associations...
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<!-- Pass admin status to JavaScript via data attribute -->
<div id="admin-data" data-is-admin="{% if current_user.is_admin %}true{% else %}false{% endif %}" style="display: none;"></div>

<style>
/* UNDER/OVER Configuration */
.under-over-zone {
    border: 2px solid #e9ecef;
    border-radius: 0.5rem;
    overflow: hidden;
    transition: all 0.3s ease;
}

.under-over-header {
    background: linear-gradient(135deg, #6c757d, #495057);
    color: white;
    padding: 0.5rem;
    text-align: center;
    font-weight: 600;
    font-size: 0.9rem;
}

.under-over-drop {
    padding: 1rem;
    text-align: center;
    background: #f8f9fa;
    min-height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.under-over-drop .badge {
    font-size: 0.8rem;
    padding: 0.4rem 0.6rem;
}

.under-over-drop .btn-close {
    font-size: 0.6em;
    opacity: 0.8;
}

.under-over-drop .btn-close:hover {
    opacity: 1;
}

.under-over-zone.drag-over {
    border-color: #28a745;
    transform: scale(1.02);
}

.under-over-zone.drag-over .under-over-drop {
    background: #d4edda;
    color: #155724;
}

.under-over-zone.has-outcome {
    border-color: #28a745;
}

.under-over-zone.has-outcome .under-over-header {
    background: linear-gradient(135deg, #28a745, #20c997);
}

/* Outcomes Pool */
.outcomes-pool {
    min-height: 400px;
    border: 2px dashed #dee2e6;
    border-radius: 0.5rem;
    padding: 1rem;
    background: #f8f9fa;
}

/* Results Pool */
.results-pool {
    min-height: 120px;
    border: 2px dashed #dee2e6;
    border-radius: 0.5rem;
    padding: 1rem;
    background: #f8f9fa;
    transition: all 0.3s ease;
}

.results-pool.drag-over {
    border-color: #007bff;
    background: #e7f1ff;
}

.results-pool .badge {
    font-size: 0.8rem;
    padding: 0.4rem 0.6rem;
}

.results-pool .btn-close {
    font-size: 0.6em;
    opacity: 0.8;
}

.results-pool .btn-close:hover {
    opacity: 1;
}

.outcome-item {
    display: inline-block;
    background: linear-gradient(135deg, #ffffff, #f8f9fa);
    border: 2px solid #dee2e6;
    border-radius: 0.4rem;
    padding: 0.6rem 1rem;
    margin: 0.25rem;
    cursor: move;
    user-select: none;
    font-weight: 500;
    transition: all 0.3s ease;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    position: relative;
}

.outcome-item:hover {
    background: linear-gradient(135deg, #e3f2fd, #bbdefb);
    border-color: #2196f3;
    transform: translateY(-2px);
    box-shadow: 0 3px 6px rgba(0,0,0,0.15);
}

.outcome-item.dragging {
    opacity: 0.7;
    transform: rotate(3deg) scale(0.95);
    z-index: 1000;
}

.outcome-item.under-over {
    background: linear-gradient(135deg, #fff3cd, #ffeaa7);
    border-color: #ffc107;
}

.outcome-item.under-over:hover {
    background: linear-gradient(135deg, #fff3cd, #ffecb5);
    border-color: #ff9800;
}

/* Outcome Columns */
.outcome-columns {
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
    min-height: 300px;
}

.outcome-column {
    flex: 1;
    min-width: 200px;
    max-width: 250px;
    border: 2px solid #e9ecef;
    border-radius: 0.5rem;
    background: white;
    transition: all 0.3s ease;
}

.outcome-column-header {
    background: linear-gradient(135deg, #007bff, #0056b3);
    color: white;
    padding: 0.75rem;
    text-align: center;
    font-weight: 600;
    border-radius: 0.5rem 0.5rem 0 0;
}

.outcome-column-body {
    padding: 1rem;
    min-height: 120px;
    border: 2px dashed transparent;
    border-radius: 0 0 0.5rem 0.5rem;
    transition: all 0.3s ease;
}

.outcome-column.drag-over .outcome-column-body {
    border-color: #28a745;
    background: #f8fff9;
}

.outcome-column.drag-invalid .outcome-column-body {
    border-color: #dc3545;
    background: #f8d7da;
}

/* Associated Outcome Items */
.associated-outcome {
    background: linear-gradient(135deg, #28a745, #20c997);
    color: white;
    border: none;
    border-radius: 0.3rem;
    padding: 0.4rem 0.8rem;
    margin: 0.2rem;
    display: inline-block;
    font-size: 0.85rem;
    font-weight: 500;
    position: relative;
    cursor: move;
    transition: all 0.2s ease;
}

.associated-outcome:hover {
    background: linear-gradient(135deg, #20c997, #17a2b8);
    transform: scale(1.05);
}

.associated-outcome .remove-btn {
    position: absolute;
    top: -6px;
    right: -6px;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    background: #dc3545;
    color: white;
    border: none;
    font-size: 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
}

.associated-outcome .remove-btn:hover {
    background: #c82333;
    transform: scale(1.1);
}

/* Trash Bin */
.trash-bin {
    border: 3px dashed #dc3545;
    border-radius: 0.75rem;
    padding: 2rem;
    background: #f8d7da;
    transition: all 0.3s ease;
    min-height: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.trash-bin.drag-over {
    border-color: #c82333;
    background: #f5c6cb;
    transform: scale(1.02);
}

/* Empty States */
.empty-column-message {
    text-align: center;
    color: #6c757d;
    font-size: 0.9rem;
    margin-top: 1rem;
}

/* Responsive Design */
@media (max-width: 768px) {
    .outcome-columns {
        flex-direction: column;
    }
    
    .outcome-column {
        max-width: none;
    }
}

/* Animation */
@keyframes slideIn {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.outcome-column.new {
    animation: slideIn 0.4s ease;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    let draggedElement = null;
    let availableOutcomes = [];
    let currentAssociations = [];
    let underOutcomes = []; // Outcomes assigned to UNDER
    let overOutcomes = [];  // Outcomes assigned to OVER
    let resultsOutcomes = []; // Outcomes in Results area that create columns

    // Get admin status from data attribute
    const isAdmin = document.getElementById('admin-data').dataset.isAdmin === 'true';

    // Initialize the page
    loadTimeLimitConfig();
    loadAvailableOutcomes();
    loadCurrentAssociations();
    loadUnderOverConfig();
    loadResultsConfig();
    
    // Load redistribution cap if admin
    if (isAdmin) {
        loadRedistributionCap();
    }

    // Event listeners
    document.getElementById('btn-save-time-limit').addEventListener('click', saveTimeLimitConfig);
    document.getElementById('btn-clear-all').addEventListener('click', clearAllAssociations);
    
    // Redistribution CAP listeners (admin only)
    if (isAdmin) {
        document.getElementById('btn-save-redistribution-cap').addEventListener('click', saveRedistributionCap);
    }

    // Setup drag and drop
    setupDragAndDrop();

    function loadAvailableOutcomes() {
        fetch('/api/extraction/outcomes')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                availableOutcomes = data.outcomes;
                displayOutcomesPool();
                createOutcomeColumns();
            } else {
                showError('outcomes-pool', 'Failed to load outcomes');
            }
        })
        .catch(error => {
            console.error('Error loading outcomes:', error);
            showError('outcomes-pool', 'Error loading outcomes');
        });
    }

    function displayOutcomesPool() {
        const pool = document.getElementById('outcomes-pool');
        pool.innerHTML = '';

        // Add header
        const header = document.createElement('div');
        header.className = 'mb-3';
        header.innerHTML = `
            <h6 class="text-muted mb-2">
                <i class="fas fa-hand-rock me-2"></i>Drag outcomes to associate them
            </h6>
        `;
        pool.appendChild(header);

        // Create outcome items
        availableOutcomes.forEach(outcome => {
            const outcomeElement = document.createElement('div');
            outcomeElement.className = 'outcome-item';
            outcomeElement.draggable = true;
            outcomeElement.dataset.outcome = outcome;
            outcomeElement.textContent = outcome;

            // Mark UNDER/OVER outcomes
            if (outcome === 'UNDER' || outcome === 'OVER') {
                outcomeElement.classList.add('under-over');
            }

            pool.appendChild(outcomeElement);
        });
    }

    function createOutcomeColumns() {
        const container = document.getElementById('outcome-columns');
        container.innerHTML = '';

        // Show columns for outcomes that are in Results area
        if (resultsOutcomes.length === 0) {
            container.innerHTML = `
                <div class="text-center text-muted p-4">
                    <i class="fas fa-info-circle me-2"></i>
                    Drag outcomes to the "Results" area on the left to create association columns here
                </div>
            `;
            return;
        }

        resultsOutcomes.forEach(outcome => {
            const column = document.createElement('div');
            column.className = 'outcome-column new';
            column.dataset.outcome = outcome;

            column.innerHTML = `
                <div class="outcome-column-header">
                    ${outcome}
                    <button type="button" class="btn btn-sm btn-outline-light ms-2"
                            onclick="removeFromResults('${outcome}')"
                            style="font-size: 0.7em; padding: 0.1rem 0.3rem;">×</button>
                </div>
                <div class="outcome-column-body" data-drop-target="${outcome}">
                    <div class="empty-column-message">
                        <i class="fas fa-arrow-down me-2"></i>
                        Drop outcomes here to associate with ${outcome}
                    </div>
                </div>
            `;

            container.appendChild(column);
        });
    }

    function loadCurrentAssociations() {
        fetch('/api/extraction/associations')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                currentAssociations = data.associations;
                displayAssociations();
                updateAssociationsSummary();
                updateUnderOverZones();
            } else {
                showError('associations-summary', 'Failed to load associations');
            }
        })
        .catch(error => {
            console.error('Error loading associations:', error);
            showError('associations-summary', 'Error loading associations');
        });
    }

    function displayAssociations() {
        // Clear all column bodies
        document.querySelectorAll('.outcome-column-body').forEach(body => {
            const message = body.querySelector('.empty-column-message');
            body.innerHTML = '';
            if (message) body.appendChild(message);
        });

        // Group associations by outcome
        const associationsByOutcome = {};
        currentAssociations.forEach(assoc => {
            if (!associationsByOutcome[assoc.outcome_name]) {
                associationsByOutcome[assoc.outcome_name] = [];
            }
            associationsByOutcome[assoc.outcome_name].push(assoc.extraction_result);
        });

        // Display associations in columns
        Object.keys(associationsByOutcome).forEach(outcome => {
            const column = document.querySelector(`[data-outcome="${outcome}"] .outcome-column-body`);
            if (column) {
                // Remove empty message
                const emptyMessage = column.querySelector('.empty-column-message');
                if (emptyMessage) emptyMessage.remove();

                // Add associated outcomes
                associationsByOutcome[outcome].forEach(associatedOutcome => {
                    const associatedElement = document.createElement('div');
                    associatedElement.className = 'associated-outcome';
                    associatedElement.draggable = true;
                    associatedElement.dataset.outcome = outcome;
                    associatedElement.dataset.associated = associatedOutcome;
                    associatedElement.textContent = associatedOutcome;

                    // Add remove button
                    const removeBtn = document.createElement('button');
                    removeBtn.className = 'remove-btn';
                    removeBtn.innerHTML = '×';
                    removeBtn.onclick = (e) => {
                        e.stopPropagation();
                        removeAssociation(outcome, associatedOutcome);
                    };
                    associatedElement.appendChild(removeBtn);

                    column.appendChild(associatedElement);
                });
            }
        });
    }

    function updateUnderOverZones() {
        const underZone = document.getElementById('under-drop-zone');
        const overZone = document.getElementById('over-drop-zone');

        // Update UNDER zone
        underZone.parentElement.classList.toggle('has-outcome', underOutcomes.length > 0);
        
        if (underOutcomes.length > 0) {
            underZone.innerHTML = `
                <div class="d-flex flex-wrap gap-1">
                    ${underOutcomes.map(outcome => `
                        <span class="badge bg-warning text-dark position-relative">
                            ${outcome}
                            <button type="button" class="btn-close btn-close-white ms-1"
                                    onclick="removeFromUnderOver('UNDER', '${outcome}')"
                                    style="font-size: 0.7em;"></button>
                        </span>
                    `).join('')}
                </div>
            `;
        } else {
            underZone.innerHTML = '<i class="fas fa-arrow-down me-2"></i><span class="drop-text">Drop outcomes for UNDER here</span>';
        }

        // Update OVER zone
        overZone.parentElement.classList.toggle('has-outcome', overOutcomes.length > 0);
        
        if (overOutcomes.length > 0) {
            overZone.innerHTML = `
                <div class="d-flex flex-wrap gap-1">
                    ${overOutcomes.map(outcome => `
                        <span class="badge bg-info text-white position-relative">
                            ${outcome}
                            <button type="button" class="btn-close btn-close-white ms-1"
                                    onclick="removeFromUnderOver('OVER', '${outcome}')"
                                    style="font-size: 0.7em;"></button>
                        </span>
                    `).join('')}
                </div>
            `;
        } else {
            overZone.innerHTML = '<i class="fas fa-arrow-up me-2"></i><span class="drop-text">Drop outcomes for OVER here</span>';
        }
    }

    function setupDragAndDrop() {
        // Drag start
        document.addEventListener('dragstart', function(e) {
            if (e.target.classList.contains('outcome-item') || e.target.classList.contains('associated-outcome')) {
                draggedElement = e.target;
                e.target.classList.add('dragging');
                e.dataTransfer.effectAllowed = 'copy';
            }
        });

        // Drag end
        document.addEventListener('dragend', function(e) {
            if (e.target.classList.contains('outcome-item') || e.target.classList.contains('associated-outcome')) {
                e.target.classList.remove('dragging');
                draggedElement = null;
            }
        });

        // Drag over
        document.addEventListener('dragover', function(e) {
            const target = getDropTarget(e.target);
            if (target) {
                e.preventDefault();
                e.dataTransfer.dropEffect = 'copy';
                target.classList.add('drag-over');
                
                // Validate drop for outcome columns
                if (target.classList.contains('outcome-column') && draggedElement) {
                    const isValid = validateDrop(draggedElement, target);
                    target.classList.toggle('drag-invalid', !isValid);
                }
            }
        });

        // Drag leave
        document.addEventListener('dragleave', function(e) {
            const target = getDropTarget(e.target);
            if (target && !target.contains(e.relatedTarget)) {
                target.classList.remove('drag-over', 'drag-invalid');
            }
        });

        // Drop
        document.addEventListener('drop', function(e) {
            const target = getDropTarget(e.target);
            if (target) {
                e.preventDefault();
                target.classList.remove('drag-over', 'drag-invalid');
                handleDrop(target, draggedElement);
            }
        });
    }

    function getDropTarget(element) {
        // Check for outcome column body
        if (element.hasAttribute('data-drop-target')) {
            return element.closest('.outcome-column');
        }
        
        // Check for UNDER/OVER zones
        if (element.classList.contains('under-over-drop') || element.closest('.under-over-zone')) {
            return element.closest('.under-over-zone');
        }
        
        // Check for Results pool
        if (element.classList.contains('results-pool') || element.closest('.results-pool')) {
            return element.classList.contains('results-pool') ? element : element.closest('.results-pool');
        }
        
        // Check for trash bin
        if (element.classList.contains('trash-bin') || element.closest('.trash-bin')) {
            return element.classList.contains('trash-bin') ? element : element.closest('.trash-bin');
        }
        
        return null;
    }

    function validateDrop(draggedElement, target) {
        if (!draggedElement || !target.classList.contains('outcome-column')) return false;
        
        const draggedOutcome = draggedElement.dataset.outcome;
        const targetOutcome = target.dataset.outcome;
        
        // Can't associate outcome with itself
        if (draggedOutcome === targetOutcome) return false;
        
        // For outcome columns, target must be in Results area
        if (!resultsOutcomes.includes(targetOutcome)) return false;
        
        // Dragged outcome must be from the available outcomes
        if (!availableOutcomes.includes(draggedOutcome)) return false;
        
        // Check if association already exists
        return !currentAssociations.some(assoc =>
            assoc.outcome_name === targetOutcome && assoc.extraction_result === draggedOutcome
        );
    }

    function handleDrop(target, draggedElement) {
        if (!draggedElement) return;

        const draggedOutcome = draggedElement.dataset.outcome;

        if (target.classList.contains('outcome-column')) {
            // Drop on outcome column
            const targetOutcome = target.dataset.outcome;
            if (validateDrop(draggedElement, target)) {
                addAssociation(targetOutcome, draggedOutcome);
            }
        } else if (target.classList.contains('under-over-zone')) {
            // Drop on UNDER/OVER zone - any outcome can be assigned
            const targetZone = target.dataset.outcome; // 'UNDER' or 'OVER'
            addToUnderOverZone(targetZone, draggedOutcome);
        } else if (target.classList.contains('results-pool')) {
            // Drop on Results area - creates a new column
            addToResults(draggedOutcome);
        } else if (target.classList.contains('trash-bin')) {
            // Drop on trash bin
            if (draggedElement.classList.contains('associated-outcome')) {
                const outcome = draggedElement.dataset.outcome;
                const associated = draggedElement.dataset.associated;
                removeAssociation(outcome, associated);
            }
        }
    }

    function addAssociation(outcome, associatedOutcome) {
        fetch('/api/extraction/associations/add', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                outcome_name: outcome,
                extraction_result: associatedOutcome
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadCurrentAssociations();
            } else {
                alert('Failed to add association: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error adding association:', error);
            alert('Error adding association');
        });
    }

    function removeAssociation(outcome, associatedOutcome) {
        fetch('/api/extraction/associations/remove', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                outcome_name: outcome,
                extraction_result: associatedOutcome
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadCurrentAssociations();
            } else {
                alert('Failed to remove association: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error removing association:', error);
            alert('Error removing association');
        });
    }

    function addToUnderOverZone(zone, outcome) {
        // Allow any outcome (including UNDER/OVER) to be assigned for time extraction
        if (zone === 'UNDER') {
            if (!underOutcomes.includes(outcome)) {
                // Remove from OVER if it's there
                const overIndex = overOutcomes.indexOf(outcome);
                if (overIndex !== -1) {
                    overOutcomes.splice(overIndex, 1);
                }
                underOutcomes.push(outcome);
            }
        } else if (zone === 'OVER') {
            if (!overOutcomes.includes(outcome)) {
                // Remove from UNDER if it's there
                const underIndex = underOutcomes.indexOf(outcome);
                if (underIndex !== -1) {
                    underOutcomes.splice(underIndex, 1);
                }
                overOutcomes.push(outcome);
            }
        }

        updateUnderOverZones();
        saveUnderOverConfig(); // Persist changes
    }

    function addToResults(outcome) {
        if (!resultsOutcomes.includes(outcome)) {
            resultsOutcomes.push(outcome);
            updateResultsPool();
            createOutcomeColumns(); // Create new column for this outcome
            displayAssociations(); // Refresh associations display
            saveResultsConfig(); // Persist changes
        }
    }

    function updateResultsPool() {
        const pool = document.getElementById('results-pool');
        
        if (resultsOutcomes.length === 0) {
            pool.innerHTML = `
                <div class="text-center text-muted p-3">
                    <i class="fas fa-arrow-down me-2"></i>
                    Drop outcomes here to create columns for associations
                </div>
            `;
            return;
        }

        pool.innerHTML = `
            <div class="d-flex flex-wrap gap-2 mb-2">
                ${resultsOutcomes.map(outcome => `
                    <span class="badge bg-primary position-relative">
                        ${outcome}
                        <button type="button" class="btn-close btn-close-white ms-1"
                                onclick="removeFromResults('${outcome}')"
                                style="font-size: 0.6em;"></button>
                    </span>
                `).join('')}
            </div>
            <div class="text-center text-muted">
                <small><i class="fas fa-plus me-1"></i>Drop more outcomes to add columns</small>
            </div>
        `;
    }

    // Global function to remove outcomes from UNDER/OVER zones
    window.removeFromUnderOver = function(zone, outcome) {
        if (zone === 'UNDER') {
            const index = underOutcomes.indexOf(outcome);
            if (index !== -1) {
                underOutcomes.splice(index, 1);
            }
        } else if (zone === 'OVER') {
            const index = overOutcomes.indexOf(outcome);
            if (index !== -1) {
                overOutcomes.splice(index, 1);
            }
        }

        updateUnderOverZones();
        saveUnderOverConfig(); // Persist changes
    };

    // Global function to remove outcomes from Results
    window.removeFromResults = function(outcome) {
        const index = resultsOutcomes.indexOf(outcome);
        if (index !== -1) {
            resultsOutcomes.splice(index, 1);
        }

        updateResultsPool();
        createOutcomeColumns(); // Recreate columns
        displayAssociations(); // Refresh associations display
        saveResultsConfig(); // Persist changes
    };

    function clearAllAssociations() {
        if (!confirm('Are you sure you want to clear all associations?')) return;

        // Remove all associations one by one
        const removePromises = currentAssociations.map(assoc =>
            fetch('/api/extraction/associations/remove', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    outcome_name: assoc.outcome_name,
                    extraction_result: assoc.extraction_result
                })
            })
        );

        Promise.all(removePromises)
        .then(() => loadCurrentAssociations())
        .catch(error => {
            console.error('Error clearing associations:', error);
            alert('Error clearing associations');
        });
    }

    function updateAssociationsSummary() {
        const summary = document.getElementById('associations-summary');
        
        if (currentAssociations.length === 0) {
            summary.innerHTML = '<div class="text-center text-muted">No associations configured</div>';
            return;
        }

        // Group by outcome
        const grouped = {};
        currentAssociations.forEach(assoc => {
            if (!grouped[assoc.outcome_name]) {
                grouped[assoc.outcome_name] = [];
            }
            grouped[assoc.outcome_name].push(assoc.extraction_result);
        });

        let html = '<div class="row">';
        Object.keys(grouped).sort().forEach(outcome => {
            html += `
                <div class="col-md-3 mb-2">
                    <div class="card border-primary">
                        <div class="card-header bg-primary text-white py-2">
                            <strong>${outcome}</strong>
                        </div>
                        <div class="card-body py-2">
                            ${grouped[outcome].map(result => 
                                `<span class="badge bg-success me-1 mb-1">${result}</span>`
                            ).join('')}
                        </div>
                    </div>
                </div>
            `;
        });
        html += '</div>';

        summary.innerHTML = html;
    }

    function loadTimeLimitConfig() {
        fetch('/api/extraction/config')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.config && data.config.under_over_time_limit) {
                document.getElementById('under-over-time-limit').value = data.config.under_over_time_limit;
            }
        })
        .catch(error => console.error('Error loading time limit config:', error));
    }

    function saveTimeLimitConfig() {
        const timeLimitInput = document.getElementById('under-over-time-limit');
        const timeLimitValue = parseInt(timeLimitInput.value);

        if (!timeLimitValue || timeLimitValue < 1 || timeLimitValue > 300) {
            alert('Please enter a valid time limit between 1 and 300 seconds');
            return;
        }

        const saveBtn = document.getElementById('btn-save-time-limit');
        const originalText = saveBtn.innerHTML;
        saveBtn.disabled = true;
        saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving...';

        fetch('/api/extraction/config', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                config_key: 'under_over_time_limit',
                config_value: timeLimitValue,
                value_type: 'int'
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Time limit saved successfully!');
            } else {
                alert('Failed to save time limit: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => alert('Error saving time limit: ' + error.message))
        .finally(() => {
            saveBtn.disabled = false;
            saveBtn.innerHTML = originalText;
        });
    }

    // Persistence functions for UNDER/OVER configuration
    function loadUnderOverConfig() {
        fetch('/api/extraction/under-over-config')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                underOutcomes = data.under_outcomes || [];
                overOutcomes = data.over_outcomes || [];
                updateUnderOverZones();
            }
        })
        .catch(error => console.error('Error loading UNDER/OVER config:', error));
    }

    function saveUnderOverConfig() {
        fetch('/api/extraction/under-over-config', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                under_outcomes: underOutcomes,
                over_outcomes: overOutcomes
            })
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                console.error('Failed to save UNDER/OVER config:', data.error);
            }
        })
        .catch(error => console.error('Error saving UNDER/OVER config:', error));
    }

    // Persistence functions for Results configuration
    function loadResultsConfig() {
        fetch('/api/extraction/results-config')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                resultsOutcomes = data.results_outcomes || [];
                updateResultsPool();
                createOutcomeColumns();
                displayAssociations();
            }
        })
        .catch(error => console.error('Error loading Results config:', error));
    }

    function saveResultsConfig() {
        fetch('/api/extraction/results-config', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                results_outcomes: resultsOutcomes
            })
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                console.error('Failed to save Results config:', data.error);
            }
        })
        .catch(error => console.error('Error saving Results config:', error));
    }

    function showError(elementId, message) {
        document.getElementById(elementId).innerHTML =
            `<div class="alert alert-danger">${message}</div>`;
    }

    // Redistribution CAP functions (admin only)
    function loadRedistributionCap() {
        if (!isAdmin) return;
        
        fetch('/api/extraction/redistribution-cap')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('redistribution-cap').value = data.redistribution_cap;
            }
        })
        .catch(error => console.error('Error loading redistribution cap:', error));
    }

    function saveRedistributionCap() {
        if (!isAdmin) return;
        
        const capInput = document.getElementById('redistribution-cap');
        const capValue = parseFloat(capInput.value);

        if (!capValue || capValue < 10 || capValue > 100) {
            alert('Please enter a valid redistribution CAP between 10% and 100%');
            return;
        }

        const saveBtn = document.getElementById('btn-save-redistribution-cap');
        const originalText = saveBtn.innerHTML;
        saveBtn.disabled = true;
        saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving...';

        fetch('/api/extraction/redistribution-cap', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                redistribution_cap: capValue
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(`Redistribution CAP saved successfully: ${capValue}%`);
            } else {
                alert('Failed to save redistribution CAP: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => alert('Error saving redistribution CAP: ' + error.message))
        .finally(() => {
            saveBtn.disabled = false;
            saveBtn.innerHTML = originalText;
        });
    }
});
</script>
{% endblock %}