{% 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 Bets -->
        <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 Bets
                </h5>
                <small class="text-muted">Drag bets to UNDER/OVER or Results associations area</small>
            </div>
            <div class="card-body">
                <!-- Add New Bet Form -->
                <div class="mb-3">
                    <div class="input-group">
                        <input type="text" class="form-control" id="new-bet-name" placeholder="Enter new bet name (e.g., WIN1, DRAW)"
                               maxlength="50">
                        <button class="btn btn-outline-success" id="btn-add-bet">
                            <i class="fas fa-plus me-1"></i>Add Bet
                        </button>
                    </div>
                    <small class="text-muted">Add a new betting option to the available bets list</small>
                </div>

                <div id="outcomes-pool" class="outcomes-pool">
                    <div class="text-center text-muted">
                        <i class="fas fa-spinner fa-spin me-2"></i>Loading bets...
                    </div>
                </div>
            </div>
        </div>

        <!-- Results Area -->
        <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-target me-2"></i>Results
                    </h5>
                </div>
                <div class="btn-group btn-group-sm" role="group">
                    <button type="button" class="btn btn-outline-success btn-sm" id="btn-add-result-option">
                        <i class="fas fa-plus me-1"></i>Add
                    </button>
                    <button type="button" class="btn btn-outline-danger btn-sm" id="btn-delete-result-option">
                        <i class="fas fa-trash me-1"></i>Delete
                    </button>
                </div>
            </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>Result Associations
                    </h5>
                    <small class="text-muted">Each result option from the Results area gets its own column for bet 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>

<!-- Add Bet Modal -->
<div class="modal fade" id="addBetModal" tabindex="-1" aria-labelledby="addBetModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addBetModalLabel">Add Available Bet</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="add-bet-form">
                    <div class="mb-3">
                        <label for="bet-name" class="form-label">Bet Name</label>
                        <input type="text" class="form-control" id="bet-name" placeholder="e.g., WIN1, DRAW, X" required maxlength="50">
                        <div class="form-text">Enter the bet option name (max 50 characters)</div>
                    </div>
                    <div class="mb-3">
                        <label for="bet-description" class="form-label">Description (Optional)</label>
                        <input type="text" class="form-control" id="bet-description" placeholder="Description of the bet option" maxlength="255">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="btn-save-bet">Add Bet</button>
            </div>
        </div>
    </div>
</div>

<!-- Add Result Option Modal -->
<div class="modal fade" id="addResultOptionModal" tabindex="-1" aria-labelledby="addResultOptionModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addResultOptionModalLabel">Add Result Option</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="add-result-option-form">
                    <div class="mb-3">
                        <label for="result-option-name" class="form-label">Result Option Name</label>
                        <input type="text" class="form-control" id="result-option-name" placeholder="e.g., DRAW, DKO, WIN1" required maxlength="50">
                        <div class="form-text">Enter the result option name (max 50 characters)</div>
                    </div>
                    <div class="mb-3">
                        <label for="result-option-description" class="form-label">Description (Optional)</label>
                        <input type="text" class="form-control" id="result-option-description" placeholder="Description of the result option" maxlength="255">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="btn-save-result-option">Add Result Option</button>
            </div>
        </div>
    </div>
</div>

<!-- Delete Result Option Modal -->
<div class="modal fade" id="deleteResultOptionModal" tabindex="-1" aria-labelledby="deleteResultOptionModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteResultOptionModalLabel">Delete Result Option</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>Select a result option to delete:</p>
                <select class="form-select" id="delete-result-option-select" size="5">
                    <option value="">Loading result options...</option>
                </select>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="btn-confirm-delete-result-option">Delete</button>
            </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;
}

.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);
    document.getElementById('btn-add-bet').addEventListener('click', addNewBet);
    document.getElementById('btn-add-result-option').addEventListener('click', showAddResultOptionModal);
    document.getElementById('btn-delete-result-option').addEventListener('click', showDeleteResultOptionModal);

    // 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/available-bets')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                availableOutcomes = data.bets.map(bet => bet.bet_name);
                displayOutcomesPool();
            } else {
                showError('outcomes-pool', 'Failed to load bets');
            }
        })
        .catch(error => {
            console.error('Error loading bets:', error);
            showError('outcomes-pool', 'Error loading bets');
        });
    }

    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 bets to associate them
            </h6>
        `;
        pool.appendChild(header);

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

            // Add the bet name
            const betText = document.createElement('span');
            betText.textContent = outcome;
            outcomeElement.appendChild(betText);

            // Add delete button
            const deleteBtn = document.createElement('button');
            deleteBtn.className = 'btn btn-sm btn-outline-danger position-absolute';
            deleteBtn.style.cssText = 'top: -8px; right: -8px; width: 20px; height: 20px; padding: 0; font-size: 10px; border-radius: 50%;';
            deleteBtn.innerHTML = '×';
            deleteBtn.title = 'Delete bet';
            deleteBtn.onclick = (e) => {
                e.stopPropagation();
                if (confirm(`Are you sure you want to delete the bet "${outcome}"?`)) {
                    deleteBet(outcome);
                }
            };
            outcomeElement.appendChild(deleteBtn);

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

        // Group associations by extraction_result (the column headers)
        const associationsByResult = {};
        currentAssociations.forEach(assoc => {
            if (!associationsByResult[assoc.extraction_result]) {
                associationsByResult[assoc.extraction_result] = [];
            }
            associationsByResult[assoc.extraction_result].push(assoc.outcome_name);
        });

        // Load ALL result options from database to create columns
        fetch('/api/extraction/result-options')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.options.length > 0) {
                data.options.forEach(resultOption => {
                    const column = document.createElement('div');
                    column.className = 'outcome-column new';
                    column.dataset.outcome = resultOption.result_name;

                    // Get associations for this result option
                    const associatedBets = associationsByResult[resultOption.result_name] || [];

                    column.innerHTML = `
                        <div class="outcome-column-header">
                            ${resultOption.result_name}
                        </div>
                        <div class="outcome-column-body" data-drop-target="${resultOption.result_name}">
                            ${associatedBets.length === 0 ?
                                `<div class="empty-column-message">
                                    <i class="fas fa-arrow-down me-2"></i>
                                    Drop bets here to associate with ${resultOption.result_name}
                                </div>` : ''
                            }
                        </div>
                    `;

                    container.appendChild(column);
                });

                // Now populate the columns with associations
                displayAssociations();
            } else {
                container.innerHTML = `
                    <div class="text-center text-muted p-4">
                        <i class="fas fa-info-circle me-2"></i>
                        No result options configured. Add result options to create association columns.
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('Error loading result options for columns:', error);
            container.innerHTML = `
                <div class="text-center text-muted p-4">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    Error loading result options.
                </div>
            `;
        });
    }

    function loadCurrentAssociations() {
        return fetch('/api/extraction/associations')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                currentAssociations = data.associations;
                // Note: createOutcomeColumns and displayAssociations are now called from loadResultsConfig
                // after resultsOutcomes is loaded
                updateUnderOverZones();
            } else {
                console.error('Failed to load associations');
            }
        })
        .catch(error => {
            console.error('Error loading associations:', error);
        });
    }

    function displayAssociations() {
        // Group associations by extraction_result (the column headers)
        const associationsByResult = {};
        currentAssociations.forEach(assoc => {
            if (!associationsByResult[assoc.extraction_result]) {
                associationsByResult[assoc.extraction_result] = [];
            }
            associationsByResult[assoc.extraction_result].push(assoc.outcome_name);
        });

        // Update each column based on current associations
        resultsOutcomes.forEach(resultOption => {
            const column = document.querySelector(`[data-outcome="${resultOption}"] .outcome-column-body`);
            if (column) {
                // Clear existing associations but keep the empty message if it exists
                const existingAssociations = column.querySelectorAll('.associated-outcome');
                existingAssociations.forEach(assoc => assoc.remove());

                const associatedBets = associationsByResult[resultOption] || [];
                const emptyMessage = column.querySelector('.empty-column-message');

                if (associatedBets.length === 0) {
                    // Show empty message if no associations
                    if (!emptyMessage) {
                        const newEmptyMessage = document.createElement('div');
                        newEmptyMessage.className = 'empty-column-message';
                        newEmptyMessage.innerHTML = `
                            <i class="fas fa-arrow-down me-2"></i>
                            Drop bets here to associate with ${resultOption}
                        `;
                        column.appendChild(newEmptyMessage);
                    }
                } else {
                    // Remove empty message and add associations
                    if (emptyMessage) emptyMessage.remove();

                    // Add associated outcomes
                    associatedBets.forEach(associatedOutcome => {
                        const associatedElement = document.createElement('div');
                        associatedElement.className = 'associated-outcome';
                        associatedElement.draggable = true;
                        associatedElement.dataset.outcome = resultOption;
                        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(resultOption, 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 (or any element inside it)
        const columnBody = element.closest('[data-drop-target]');
        if (columnBody) {
            return columnBody.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 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;

        // 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('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().then(() => {
                    displayAssociations();
                });
            } 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().then(() => {
                    displayAssociations();
                });
            } 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();
            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="deleteResultOption('${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>Use Add/Delete buttons to manage result options</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();
        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(() => {
            // Clear local associations and refresh display
            currentAssociations = [];
            displayAssociations();
            updateUnderOverZones();
        })
        .catch(error => {
            console.error('Error clearing associations:', error);
            alert('Error clearing associations');
        });
    }


    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() {
        // Load result options from database
        fetch('/api/extraction/result-options')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Convert result options to the format expected by the UI
                resultsOutcomes = data.options.map(option => option.result_name);
                updateResultsPool();
                // Recreate columns now that we have result options
                createOutcomeColumns();
                // Redisplay associations
                displayAssociations();
            } else {
                console.error('Failed to load result options:', data.error);
                // Fallback to saved config if database fails
                fetch('/api/extraction/results-config')
                .then(response => response.json())
                .then(fallbackData => {
                    if (fallbackData.success) {
                        resultsOutcomes = fallbackData.results_outcomes || [];
                        updateResultsPool();
                        // Recreate columns now that we have result options
                        createOutcomeColumns();
                        // Redisplay associations
                        displayAssociations();
                    }
                })
                .catch(error => console.error('Error loading Results config fallback:', error));
            }
        })
        .catch(error => {
            console.error('Error loading result options:', error);
            // Fallback to saved config
            fetch('/api/extraction/results-config')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    resultsOutcomes = data.results_outcomes || [];
                    updateResultsPool();
                    // Recreate columns now that we have result options
                    createOutcomeColumns();
                    // Redisplay associations
                    displayAssociations();
                }
            })
            .catch(error => console.error('Error loading Results config fallback:', 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>`;
    }

    // Available Bets CRUD functions
    function addNewBet() {
        const betNameInput = document.getElementById('new-bet-name');
        const betName = betNameInput.value.trim().toUpperCase();

        if (!betName) {
            alert('Please enter a bet name');
            return;
        }

        if (betName.length > 50) {
            alert('Bet name must be 50 characters or less');
            return;
        }

        // Check if bet already exists
        if (availableOutcomes.includes(betName)) {
            alert('This bet already exists');
            return;
        }

        const addBtn = document.getElementById('btn-add-bet');
        const originalText = addBtn.innerHTML;
        addBtn.disabled = true;
        addBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Adding...';

        fetch('/api/extraction/available-bets/add', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                bet_name: betName,
                description: `Bet option: ${betName}`
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                betNameInput.value = '';
                loadAvailableOutcomes(); // Refresh the list
                alert('Bet added successfully!');
            } else {
                alert('Failed to add bet: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error adding bet:', error);
            alert('Error adding bet');
        })
        .finally(() => {
            addBtn.disabled = false;
            addBtn.innerHTML = originalText;
        });
    }

    function deleteBet(betName) {
        fetch('/api/extraction/available-bets/delete', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                bet_name: betName
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadAvailableOutcomes(); // Refresh the list
                alert('Bet deleted successfully!');
            } else {
                alert('Failed to delete bet: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error deleting bet:', error);
            alert('Error deleting bet');
        });
    }

    // 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;
        });
    }

    // Available bets management functions
    function addAvailableBet() {
        const betName = document.getElementById('bet-name').value.trim().toUpperCase();
        const betDescription = document.getElementById('bet-description').value.trim();

        if (!betName) {
            alert('Bet name is required');
            return;
        }

        if (betName.length > 50) {
            alert('Bet name must be 50 characters or less');
            return;
        }

        fetch('/api/extraction/available-bets/add', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                bet_name: betName,
                description: betDescription
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Close modal and reset form
                const modal = bootstrap.Modal.getInstance(document.getElementById('addBetModal'));
                modal.hide();
                document.getElementById('add-bet-form').reset();

                // Reload available bets
                loadAvailableOutcomes();
                alert('Bet added successfully!');
            } else {
                alert('Failed to add bet: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error adding bet:', error);
            alert('Error adding bet');
        });
    }

    // Global function to delete available bet
    window.deleteAvailableBet = function(betName) {
        if (!confirm(`Are you sure you want to delete the bet "${betName}"?`)) {
            return;
        }

        fetch('/api/extraction/available-bets/delete', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                bet_name: betName
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Reload available bets
                loadAvailableOutcomes();
                // Reload associations since some may have been removed
                loadCurrentAssociations();
                alert(`Bet deleted successfully! ${data.associations_removed || 0} associated associations were also removed.`);
            } else {
                alert('Failed to delete bet: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error deleting bet:', error);
            alert('Error deleting bet');
        });
    };

    // Result Options management functions
    function showAddResultOptionModal() {
        document.getElementById('add-result-option-form').reset();
        const modal = new bootstrap.Modal(document.getElementById('addResultOptionModal'));
        modal.show();
    }

    function showDeleteResultOptionModal() {
        // Load result options for the select dropdown
        fetch('/api/extraction/result-options')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const select = document.getElementById('delete-result-option-select');
                select.innerHTML = '';

                if (data.options.length === 0) {
                    select.innerHTML = '<option value="">No result options available</option>';
                    document.getElementById('btn-confirm-delete-result-option').disabled = true;
                } else {
                    data.options.forEach(option => {
                        const optionElement = document.createElement('option');
                        optionElement.value = option.result_name;
                        optionElement.textContent = `${option.result_name}${option.description ? ' - ' + option.description : ''}`;
                        select.appendChild(optionElement);
                    });
                    document.getElementById('btn-confirm-delete-result-option').disabled = false;
                }

                const modal = new bootstrap.Modal(document.getElementById('deleteResultOptionModal'));
                modal.show();
            } else {
                alert('Failed to load result options: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error loading result options:', error);
            alert('Error loading result options');
        });
    }

    function addResultOption() {
        const resultName = document.getElementById('result-option-name').value.trim().toUpperCase();
        const resultDescription = document.getElementById('result-option-description').value.trim();

        if (!resultName) {
            alert('Result option name is required');
            return;
        }

        if (resultName.length > 50) {
            alert('Result option name must be 50 characters or less');
            return;
        }

        fetch('/api/extraction/result-options/add', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                result_name: resultName,
                description: resultDescription
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Close modal and reset form
                const modal = bootstrap.Modal.getInstance(document.getElementById('addResultOptionModal'));
                modal.hide();
                document.getElementById('add-result-option-form').reset();

                alert('Result option added successfully!');
            } else {
                alert('Failed to add result option: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error adding result option:', error);
            alert('Error adding result option');
        });
    }

    function deleteResultOption(resultName) {
        if (!resultName) {
            alert('Result name is required');
            return;
        }

        if (!confirm(`Are you sure you want to delete the result option "${resultName}"?`)) {
            return;
        }

        fetch('/api/extraction/result-options/delete', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                result_name: resultName
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Reload results config to remove deleted option
                loadResultsConfig();
                alert(`Result option deleted successfully! ${data.associations_removed || 0} associated associations were also removed.`);
            } else {
                alert('Failed to delete result option: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error deleting result option:', error);
            alert('Error deleting result option');
        });
    }

    // Make function globally available for onclick handlers
    window.deleteResultOption = deleteResultOption;

    function deleteResultOptionFromModal() {
        const select = document.getElementById('delete-result-option-select');
        const resultName = select.value;

        if (!resultName) {
            alert('Please select a result option to delete');
            return;
        }

        deleteResultOption(resultName);

        // Close modal
        const modal = bootstrap.Modal.getInstance(document.getElementById('deleteResultOptionModal'));
        modal.hide();
    }

    // Event listeners for result option modals
    document.getElementById('btn-save-result-option').addEventListener('click', addResultOption);
    document.getElementById('btn-confirm-delete-result-option').addEventListener('click', deleteResultOptionFromModal);
});
</script>
{% endblock %}