{% extends "base.html" %}

{% block title %}{{ page_title }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div>
                    <h1><i class="fas fa-cogs me-2"></i>Extraction Management</h1>
                    <p class="mb-0">Configure outcome associations for extraction results and manage game settings.</p>
                </div>
                <div>
                    <button type="button" class="btn btn-primary" id="save-associations-btn">
                        <i class="fas fa-save me-1"></i>Save Associations
                    </button>
                </div>
            </div>

            <!-- Game Configuration -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5><i class="fas fa-cogs me-2"></i>Game Configuration</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <label for="time-limit-input" class="form-label">Time Limit Between UNDER and OVER (seconds)</label>
                            <div class="input-group">
                                <input type="number" class="form-control" id="time-limit-input" min="1" max="300" value="90">
                                <button class="btn btn-outline-primary" type="button" id="update-time-limit-btn">
                                    <i class="fas fa-save me-1"></i>Update
                                </button>
                            </div>
                            <small class="form-text text-muted">Default: 90 seconds. Range: 1-300 seconds.</small>
                        </div>
                        <div class="col-md-6">
                            <label for="cap-input" class="form-label">CAP of Redistributed Bets (%)</label>
                            <div class="input-group">
                                <input type="number" class="form-control" id="cap-input" min="20" max="90" step="1" value="70">
                                <button class="btn btn-outline-primary" type="button" id="update-cap-btn">
                                    <i class="fas fa-save me-1"></i>Update
                                </button>
                            </div>
                            <small class="form-text text-muted">Default: 70%. Range: 20-90%.</small>
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-12">
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i>
                                <strong>UNDER/OVER Outcomes:</strong> These outcomes appear separately above the main extraction area and are not included in the drag-and-drop associations below.
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- UNDER/OVER Outcomes Display -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5><i class="fas fa-layer-group me-2"></i>UNDER/OVER Outcomes</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="outcome-item under-over-item" data-outcome="UNDER">
                                <span class="badge bg-warning fs-6 p-2">UNDER</span>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="outcome-item under-over-item" data-outcome="OVER">
                                <span class="badge bg-warning fs-6 p-2">OVER</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Extraction Layout -->
            <div class="row">
                <!-- Available Outcomes Pool -->
                <div class="col-md-4">
                    <div class="card h-100">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5><i class="fas fa-list me-2"></i>Available Outcomes</h5>
                            <span class="badge bg-secondary" id="available-count">0</span>
                        </div>
                        <div class="card-body">
                            <div id="available-outcomes" class="outcomes-container">
                                <!-- Available outcomes will be loaded here -->
                            </div>
                            <small class="text-muted">Outcomes not associated with all 3 results</small>
                        </div>
                    </div>
                </div>

                <!-- Extraction Result Columns -->
                <div class="col-md-8">
                    <div class="row">
                        <!-- WIN1 Column -->
                        <div class="col-md-4 mb-3">
                            <div class="card h-100">
                                <div class="card-header text-center bg-primary text-white">
                                    <h5 class="mb-0">
                                        <i class="fas fa-trophy me-2"></i>WIN1
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div id="win1-column" class="extraction-column outcomes-container" data-result="WIN1">
                                        <!-- WIN1 associated outcomes will be loaded here -->
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- X Column -->
                        <div class="col-md-4 mb-3">
                            <div class="card h-100">
                                <div class="card-header text-center bg-info text-white">
                                    <h5 class="mb-0">
                                        <i class="fas fa-balance-scale me-2"></i>X
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div id="x-column" class="extraction-column outcomes-container" data-result="X">
                                        <!-- X associated outcomes will be loaded here -->
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- WIN2 Column -->
                        <div class="col-md-4 mb-3">
                            <div class="card h-100">
                                <div class="card-header text-center bg-success text-white">
                                    <h5 class="mb-0">
                                        <i class="fas fa-medal me-2"></i>WIN2
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div id="win2-column" class="extraction-column outcomes-container" data-result="WIN2">
                                        <!-- WIN2 associated outcomes will be loaded here -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Trash Bin -->
                    <div class="row mt-3">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body text-center">
                                    <div id="trash-bin" class="trash-bin outcomes-container">
                                        <i class="fas fa-trash-alt fa-2x text-danger"></i>
                                        <p class="mb-0 mt-2">Drop outcomes here to remove associations</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Statistics -->
            <div class="row mt-4">
                <div class="col-md-3">
                    <div class="card text-center">
                        <div class="card-body">
                            <h5 class="card-title text-primary">
                                <i class="fas fa-list me-2"></i>Total Outcomes
                            </h5>
                            <h3 id="total-outcomes" class="text-primary">0</h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-center">
                        <div class="card-body">
                            <h5 class="card-title text-info">
                                <i class="fas fa-link me-2"></i>Associated
                            </h5>
                            <h3 id="associated-outcomes" class="text-info">0</h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-center">
                        <div class="card-body">
                            <h5 class="card-title text-warning">
                                <i class="fas fa-clock me-2"></i>Available
                            </h5>
                            <h3 id="available-outcomes-count" class="text-warning">0</h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-center">
                        <div class="card-body">
                            <h5 class="card-title text-success">
                                <i class="fas fa-save me-2"></i>Last Saved
                            </h5>
                            <h6 id="last-saved" class="text-success">--</h6>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.outcomes-container {
    min-height: 200px;
    border: 2px dashed #dee2e6;
    border-radius: 0.375rem;
    padding: 1rem;
    background-color: #f8f9fa;
    transition: all 0.3s ease;
}

.outcomes-container:hover {
    border-color: #adb5bd;
    background-color: #e9ecef;
}

.outcome-item {
    display: inline-block;
    margin: 0.25rem;
    cursor: move;
    user-select: none;
    transition: all 0.2s ease;
}

.outcome-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.outcome-item.dragging {
    opacity: 0.5;
    transform: rotate(5deg);
}

.extraction-column {
    min-height: 300px;
}

.extraction-column .outcome-item {
    display: block;
    margin-bottom: 0.5rem;
}

.trash-bin {
    border: 2px dashed #dc3545;
    border-radius: 0.5rem;
    padding: 2rem;
    background-color: #f8d7da;
    transition: all 0.3s ease;
}

.trash-bin:hover {
    background-color: #f5c6cb;
    border-color: #c82333;
}

.trash-bin.drag-over {
    background-color: #dc3545;
    border-color: #bd2130;
    color: white;
}

.under-over-item {
    text-align: center;
    pointer-events: none;
}

.under-over-item .badge {
    font-size: 1.1em;
    padding: 0.5rem 1rem;
}
</style>

<script>
let allOutcomes = [];
let associations = {};
let draggedElement = null;

document.addEventListener('DOMContentLoaded', function() {
    loadData();
    setupEventListeners();
    setupDragAndDrop();
});

function loadData() {
    // Load outcomes and associations
    Promise.all([
        fetch('/api/extraction/outcomes').then(r => r.json()),
        fetch('/api/extraction/associations').then(r => r.json()),
        fetch('/api/extraction/config').then(r => r.json())
    ]).then(([outcomesData, associationsData, configData]) => {
        if (outcomesData.success) {
            allOutcomes = outcomesData.outcomes;
        }

        if (associationsData.success) {
            associations = {};
            associationsData.associations.forEach(assoc => {
                if (!associations[assoc.extraction_result]) {
                    associations[assoc.extraction_result] = [];
                }
                associations[assoc.extraction_result].push(assoc.outcome_name);
            });
        }

        if (configData.success && configData.config) {
            document.getElementById('time-limit-input').value = configData.config.under_over_time_limit || 90;
            document.getElementById('cap-input').value = configData.config.redistributed_bets_cap || 70;
        }

        renderOutcomes();
        updateStatistics();
    }).catch(error => {
        console.error('Error loading data:', error);
        alert('Failed to load extraction data');
    });
}

function setupEventListeners() {
    // Save associations button
    document.getElementById('save-associations-btn').addEventListener('click', saveAssociations);

    // Update time limit button
    document.getElementById('update-time-limit-btn').addEventListener('click', updateTimeLimit);

    // Update CAP button
    document.getElementById('update-cap-btn').addEventListener('click', updateCap);
}

function setupDragAndDrop() {
    // Make outcome items draggable
    document.addEventListener('dragstart', handleDragStart);
    document.addEventListener('dragend', handleDragEnd);

    // Setup drop zones
    const dropZones = document.querySelectorAll('.outcomes-container');
    dropZones.forEach(zone => {
        zone.addEventListener('dragover', handleDragOver);
        zone.addEventListener('dragleave', handleDragLeave);
        zone.addEventListener('drop', handleDrop);
    });
}

function handleDragStart(e) {
    if (e.target.classList.contains('outcome-item')) {
        draggedElement = e.target;
        e.target.classList.add('dragging');
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/html', e.target.outerHTML);
        e.dataTransfer.setData('text/plain', e.target.dataset.outcome);
    }
}

function handleDragEnd(e) {
    if (draggedElement) {
        draggedElement.classList.remove('dragging');
        draggedElement = null;
    }

    // Remove drag-over class from all zones
    document.querySelectorAll('.outcomes-container').forEach(zone => {
        zone.classList.remove('drag-over');
    });
}

function handleDragOver(e) {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';

    if (e.target.classList.contains('outcomes-container') || e.target.closest('.outcomes-container')) {
        const container = e.target.closest('.outcomes-container');
        container.classList.add('drag-over');

        // Special handling for trash bin
        if (container.id === 'trash-bin') {
            container.classList.add('drag-over');
        }
    }
}

function handleDragLeave(e) {
    if (e.target.classList.contains('outcomes-container') || e.target.closest('.outcomes-container')) {
        const container = e.target.closest('.outcomes-container');
        container.classList.remove('drag-over');
    }
}

function handleDrop(e) {
    e.preventDefault();

    if (!draggedElement) return;

    const dropZone = e.target.closest('.outcomes-container');
    if (!dropZone) return;

    const outcomeName = draggedElement.dataset.outcome;
    const sourceContainer = draggedElement.closest('.outcomes-container');

    // Determine source and destination types
    const isFromResultColumn = sourceContainer && sourceContainer.classList.contains('extraction-column');
    const isFromAvailable = sourceContainer && sourceContainer.id === 'available-outcomes';
    const isToResultColumn = dropZone.classList.contains('extraction-column');
    const isToAvailable = dropZone.id === 'available-outcomes';
    const isToTrash = dropZone.id === 'trash-bin';

    if (isToTrash) {
        if (isFromResultColumn) {
            // Remove from specific result when dragged from result column to trash
            const sourceResult = sourceContainer.dataset.result;
            removeAssociation(outcomeName, sourceResult);
        } else {
            // Remove from all associations when dragged from available to trash
            removeAssociation(outcomeName);
        }
        renderOutcomes();
    } else if (isToAvailable) {
        // Remove all associations when dragged to available outcomes
        removeAssociation(outcomeName);
        renderOutcomes();
    } else if (isToResultColumn) {
        const destinationResult = dropZone.dataset.result;

        // Always add the association - allow multiple associations
        addAssociation(outcomeName, destinationResult);
        renderOutcomes();
    }

    dropZone.classList.remove('drag-over');
    updateStatistics();

    // Auto-save associations after each drop (no alerts for drag & drop)
    saveAssociations(false);
}

function addAssociation(outcomeName, extractionResult) {
    // Add to association (allow multiple associations)
    if (!associations[extractionResult]) {
        associations[extractionResult] = [];
    }

    // Only add if not already associated with this result
    if (!associations[extractionResult].includes(outcomeName)) {
        associations[extractionResult].push(outcomeName);
    }
}

function removeAssociation(outcomeName, specificResult = null) {
    if (specificResult) {
        // Remove from specific result only
        if (associations[specificResult]) {
            associations[specificResult] = associations[specificResult].filter(outcome => outcome !== outcomeName);
        }
    } else {
        // Remove from all associations
        Object.keys(associations).forEach(result => {
            associations[result] = associations[result].filter(outcome => outcome !== outcomeName);
        });
    }
}

function renderOutcomes() {
    const availableContainer = document.getElementById('available-outcomes');
    const win1Container = document.getElementById('win1-column');
    const xContainer = document.getElementById('x-column');
    const win2Container = document.getElementById('win2-column');

    // Clear containers
    availableContainer.innerHTML = '';
    win1Container.innerHTML = '';
    xContainer.innerHTML = '';
    win2Container.innerHTML = '';

    // Separate UNDER/OVER from regular outcomes
    const regularOutcomes = allOutcomes.filter(outcome => !['UNDER', 'OVER'].includes(outcome));
    const underOverOutcomes = allOutcomes.filter(outcome => ['UNDER', 'OVER'].includes(outcome));

    // Render regular outcomes
    regularOutcomes.forEach(outcome => {
        const outcomeElement = createOutcomeElement(outcome);

        // Count how many results this outcome is associated with
        const associatedResults = Object.keys(associations).filter(result =>
            associations[result].includes(outcome)
        );

        // Always show outcome in available outcomes unless associated with ALL 3 results
        if (associatedResults.length < 3) {
            availableContainer.appendChild(outcomeElement.cloneNode(true));
        }

        // Show outcome in each associated result column
        associatedResults.forEach(result => {
            const container = getContainerForResult(result);
            if (container) {
                container.appendChild(outcomeElement.cloneNode(true));
            }
        });
    });
}

function createOutcomeElement(outcome) {
    const element = document.createElement('div');
    element.className = 'outcome-item';
    element.dataset.outcome = outcome;
    element.draggable = true;

    // All outcome labels should be red
    let badgeClass = 'bg-danger';

    element.innerHTML = `<span class="badge ${badgeClass}">${outcome}</span>`;
    return element;
}

function getContainerForResult(result) {
    switch (result) {
        case 'WIN1': return document.getElementById('win1-column');
        case 'X': return document.getElementById('x-column');
        case 'WIN2': return document.getElementById('win2-column');
        default: return null;
    }
}

function updateStatistics() {
    const totalOutcomes = allOutcomes.filter(outcome => !['UNDER', 'OVER'].includes(outcome)).length;
    const associatedCount = Object.values(associations).reduce((sum, outcomes) => sum + outcomes.length, 0);

    // Count outcomes that are NOT associated with all 3 results (these appear in available)
    const availableCount = allOutcomes.filter(outcome => {
        if (['UNDER', 'OVER'].includes(outcome)) return false;
        const associatedResults = Object.keys(associations).filter(result =>
            associations[result].includes(outcome)
        );
        return associatedResults.length < 3;
    }).length;

    document.getElementById('total-outcomes').textContent = totalOutcomes;
    document.getElementById('associated-outcomes').textContent = associatedCount;
    document.getElementById('available-outcomes-count').textContent = availableCount;
    document.getElementById('available-count').textContent = availableCount;
}

function saveAssociations(showAlerts = true) {
    const saveBtn = document.getElementById('save-associations-btn');
    const originalText = saveBtn.innerHTML;

    if (showAlerts) {
        saveBtn.disabled = true;
        saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving...';
    }

    // Convert associations to API format
    const associationsData = [];
    Object.keys(associations).forEach(result => {
        associations[result].forEach(outcome => {
            associationsData.push({
                outcome_name: outcome,
                extraction_result: result
            });
        });
    });

    fetch('/api/extraction/associations', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ associations: associationsData })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('last-saved').textContent = new Date().toLocaleTimeString();
            if (showAlerts) {
                alert('Associations saved successfully!');
            }
        } else {
            if (showAlerts) {
                alert('Error saving associations: ' + (data.error || 'Unknown error'));
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        if (showAlerts) {
            alert('Failed to save associations: ' + error.message);
        }
    })
    .finally(() => {
        if (showAlerts) {
            saveBtn.disabled = false;
            saveBtn.innerHTML = originalText;
        }
    });
}

function updateTimeLimit() {
    const timeLimitInput = document.getElementById('time-limit-input');
    const timeLimit = parseInt(timeLimitInput.value);

    if (timeLimit < 1 || timeLimit > 300) {
        alert('Time limit must be between 1 and 300 seconds');
        return;
    }

    const updateBtn = document.getElementById('update-time-limit-btn');
    const originalText = updateBtn.innerHTML;

    updateBtn.disabled = true;
    updateBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Updating...';

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

function updateCap() {
    const capInput = document.getElementById('cap-input');
    const cap = parseInt(capInput.value);

    if (cap < 20 || cap > 90) {
        alert('CAP must be between 20 and 90 percent');
        return;
    }

    const updateBtn = document.getElementById('update-cap-btn');
    const originalText = updateBtn.innerHTML;

    updateBtn.disabled = true;
    updateBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Updating...';

    fetch('/api/extraction/config', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            config_key: 'redistributed_bets_cap',
            config_value: cap.toString(),
            value_type: 'int'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('CAP updated successfully!');
        } else {
            alert('Error updating CAP: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to update CAP: ' + error.message);
    })
    .finally(() => {
        updateBtn.disabled = false;
        updateBtn.innerHTML = originalText;
    });
}
</script>
{% endblock %}