{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-12">
        <h1 class="mb-4">
            <i class="fas fa-plus-circle me-2"></i>Create New Bet
            <small class="text-muted">Select matches and outcomes</small>
        </h1>
    </div>
</div>

<!-- Keyboard Input Form -->
<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-keyboard me-2"></i>Match Selection
                </h5>
            </div>
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="fas fa-hashtag"></i>
                            </span>
                            <input type="text" class="form-control form-control-lg" id="match-input"
                                   placeholder="Enter match number and press Enter" readonly
                                   style="font-size: 1.2rem; font-weight: bold;">
                            <span class="input-group-text">
                                <small class="text-muted">Press digits + Enter to select match</small>
                            </span>
                        </div>
                    </div>
                    <div class="col-md-4 text-end">
                        <small class="text-muted">
                            <i class="fas fa-info-circle me-1"></i>
                            Use keyboard navigation for faster betting
                        </small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Back Button and Submit Button -->
<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-gamepad me-2"></i>Available Matches for Betting
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <button class="btn btn-outline-secondary" onclick="window.location.href='/cashier/bets'">
                            <i class="fas fa-arrow-left me-2"></i>Back to Bets
                        </button>
                    </div>
                    <div class="col-md-6 mb-3 text-end">
                        <button class="btn btn-success" id="btn-submit-bet" disabled>
                            <i class="fas fa-check me-2"></i>Submit Bet
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Main Content Layout -->
<div class="row">
    <!-- Available Matches - Left Side -->
    <div class="col-lg-9 col-md-8">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-list me-2"></i>Today's Matches Available for Betting
                    <span class="badge bg-success ms-2" id="available-matches-count">0</span>
                </h5>
            </div>
            <div class="card-body">
                <div id="available-matches-container">
                    <div class="text-center text-muted">
                        <i class="fas fa-spinner fa-spin me-2"></i>Loading available matches...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Right Column - Current Bet Summary -->
    <div class="col-lg-3 col-md-4">
        <!-- Current Bet Summary -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-receipt me-2"></i>Bet Summary
                </h6>
            </div>
            <div class="card-body p-3">
                <div id="bet-summary-content">
                    <div class="text-center text-muted">
                        <i class="fas fa-info-circle me-2"></i>
                        <small>Enter amounts for outcomes to start building your bet</small>
                    </div>
                </div>
                <div class="border-top pt-3 mt-3" id="bet-total-section" style="display: none;">
                    <div class="d-flex justify-content-between">
                        <strong>Total Amount:</strong>
                        <strong class="text-success" id="bet-total-amount">USh 0.00</strong>
                    </div>
                </div>
            </div>
        </div>

        <!-- Session Information -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-user me-2"></i>Session Info
                </h6>
            </div>
            <div class="card-body p-3">
                <dl class="mb-0 small">
                    <dt class="text-muted">User</dt>
                    <dd>{{ current_user.username }}</dd>

                    <dt class="text-muted">Role</dt>
                    <dd>
                        <span class="badge bg-info">Cashier</span>
                    </dd>

                    <dt class="text-muted">Date</dt>
                    <dd id="current-date">{{ current_date }}</dd>
                </dl>
            </div>
        </div>

        <!-- Quick Betting Tips -->
        <div class="card">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-lightbulb me-2"></i>Betting Tips
                </h6>
            </div>
            <div class="card-body p-3">
                <ul class="small mb-0 list-unstyled">
                    <li class="mb-2">
                        <i class="fas fa-check-circle text-success me-2"></i>
                        Enter amounts for outcomes to create combination bets
                    </li>
                    <li class="mb-2">
                        <i class="fas fa-dollar-sign text-info me-2"></i>
                        Enter amounts with 2 decimal precision
                    </li>
                    <li class="mb-2">
                        <i class="fas fa-eye text-warning me-2"></i>
                        Review your selections before submitting
                    </li>
                    <li>
                        <i class="fas fa-ban text-danger me-2"></i>
                        Only pending bets can be cancelled
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>
<!-- Keyboard Shortcuts Help Panel -->
<div id="keyboard-help-panel" class="keyboard-help-panel">
    <div class="keyboard-help-header">
        <i class="fas fa-keyboard me-2"></i>
        <strong>Keyboard Shortcuts</strong>
        <button type="button" class="btn-close btn-close-white ms-auto" onclick="toggleKeyboardHelp()"></button>
    </div>
    <div class="keyboard-help-content" id="keyboard-help-content">
        <!-- Dynamic content will be updated based on page state -->
        <div class="keyboard-shortcut">
            <kbd>1-9 + Enter</kbd>
            <span>Select Match</span>
        </div>
        <div class="keyboard-shortcut">
            <kbd>Tab</kbd>
            <span>Navigate Outcomes</span>
        </div>
        <div class="keyboard-shortcut">
            <kbd>Enter</kbd>
            <span>Submit Bet</span>
        </div>
        <div class="keyboard-shortcut">
            <kbd>Esc</kbd>
            <span>Cancel/Close</span>
        </div>
    </div>
</div>

<style>
.keyboard-help-panel {
    position: fixed;
    bottom: 20px;
    right: 20px;
    background: rgba(0, 123, 255, 0.95);
    color: white;
    border-radius: 8px;
    padding: 0;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    z-index: 1050;
    min-width: 280px;
    backdrop-filter: blur(10px);
}

.keyboard-help-header {
    background: rgba(0, 0, 0, 0.2);
    padding: 10px 15px;
    border-radius: 8px 8px 0 0;
    display: flex;
    align-items: center;
    font-size: 14px;
}

.keyboard-help-content {
    padding: 15px;
}

.keyboard-shortcut {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    font-size: 13px;
}

.keyboard-shortcut:last-child {
    margin-bottom: 0;
}

.keyboard-shortcut kbd {
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    border-radius: 3px;
    padding: 2px 6px;
    font-size: 11px;
    font-weight: bold;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.keyboard-help-panel.minimized {
    width: 50px;
    height: 50px;
    min-width: auto;
    cursor: pointer;
}

.keyboard-help-panel.minimized .keyboard-help-content,
.keyboard-help-panel.minimized .keyboard-help-header .btn-close {
    display: none;
}

.keyboard-help-panel.minimized .keyboard-help-header {
    justify-content: center;
    padding: 0;
    height: 50px;
    border-radius: 50%;
}

.keyboard-help-panel.minimized .keyboard-help-header strong {
    display: none;
}

.keyboard-help-panel.minimized .keyboard-help-header i {
    font-size: 18px;
}
</style>

{% endblock %}

{% block scripts %}
<script src="{{ url_for('static', filename='js/currency.js') }}"></script>
<script>
// Update currency symbols when settings are loaded
document.addEventListener('currencySettingsLoaded', function(event) {
    const currencySymbol = event.detail.symbol;
    
    // Update all currency symbol spans
    document.querySelectorAll('.currency-symbol').forEach(span => {
        span.textContent = currencySymbol;
    });
    
    // Update all currency amounts
    document.querySelectorAll('.currency-amount').forEach(element => {
        const amount = parseFloat(element.dataset.amount || 0);
        element.textContent = formatCurrency(amount);
    });
    
    // Update bet total amount
    const totalElement = document.getElementById('bet-total-amount');
    if (totalElement && totalElement.dataset.amount) {
        const amount = parseFloat(totalElement.dataset.amount);
        totalElement.textContent = formatCurrency(amount);
    }
});
document.addEventListener('DOMContentLoaded', function() {
    // Load available matches on page load
    loadAvailableMatches();

    // Submit bet button
    document.getElementById('btn-submit-bet').addEventListener('click', function() {
        submitBet();
    });

    // Initialize keyboard navigation
    initializeKeyboardNavigation();

    // Initialize keyboard help panel
    initializeKeyboardHelp();
});

// Keyboard navigation state
let keyboardState = {
    inputBuffer: '',
    currentMatch: null,
    currentOutcomeIndex: -1,
    outcomes: []
};

function initializeKeyboardNavigation() {
    const matchInput = document.getElementById('match-input');

    // Global keyboard event listener
    document.addEventListener('keydown', function(event) {
        // Handle digit input for match selection
        if (event.key >= '0' && event.key <= '9' && !isInInputField(event.target)) {
            event.preventDefault();
            keyboardState.inputBuffer += event.key;
            matchInput.value = keyboardState.inputBuffer;
            matchInput.classList.add('is-valid');
            return;
        }

        // Handle Enter key for match selection
        if (event.key === 'Enter' && keyboardState.inputBuffer && !isInInputField(event.target)) {
            event.preventDefault();
            const matchNumber = parseInt(keyboardState.inputBuffer);
            selectMatchByNumber(matchNumber);
            keyboardState.inputBuffer = '';
            matchInput.value = '';
            matchInput.classList.remove('is-valid');
            return;
        }

        // Handle Tab key for outcome navigation (only when in match)
        if (event.key === 'Tab' && keyboardState.currentMatch) {
            event.preventDefault();
            navigateOutcomes();
            return;
        }

        // Handle digits + Enter for bet amount (when outcome is selected)
        if (event.key === 'Enter' && keyboardState.currentOutcomeIndex >= 0 && keyboardState.inputBuffer) {
            event.preventDefault();
            const amount = parseFloat(keyboardState.inputBuffer);
            if (amount > 0) {
                enterBetAmount(amount);
            }
            keyboardState.inputBuffer = '';
            matchInput.value = '';
            matchInput.classList.remove('is-valid');
            return;
        }

        // Handle Enter for submitting bet (if any values are entered)
        if (event.key === 'Enter' && !event.ctrlKey && !keyboardState.inputBuffer && selectedOutcomes.size > 0) {
            event.preventDefault();
            submitBet();
            return;
        }

        // Handle Escape key for canceling
        if (event.key === 'Escape') {
            event.preventDefault();
            if (keyboardState.currentMatch) {
                // Close current match and reset inputs
                closeCurrentMatch(true);
            } else {
                // Go back to bets page
                window.location.href = '/cashier/bets';
            }
            return;
        }
    });
}

function isInInputField(element) {
    return element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' || element.tagName === 'SELECT' ||
           element.contentEditable === 'true';
}

function selectMatchByNumber(matchNumber) {
    // Find match card with this number
    const matchCards = document.querySelectorAll('.match-card');
    for (const card of matchCards) {
        const matchId = card.getAttribute('data-match-id');
        const headerText = card.querySelector('h6').textContent;
        const matchNumMatch = headerText.match(/Match #(\d+)/);
        if (matchNumMatch && parseInt(matchNumMatch[1]) === matchNumber) {
            // Open this match
            openMatch(card, matchId);
            // Scroll to the match panel
            card.scrollIntoView({ behavior: 'smooth', block: 'center' });
            return;
        }
    }

    // Match not found - visual feedback
    const matchInput = document.getElementById('match-input');
    matchInput.classList.add('is-invalid');
    setTimeout(() => matchInput.classList.remove('is-invalid'), 1000);
}

function openMatch(card, matchId) {
    // Close any currently open match
    closeCurrentMatch();

    // Open the selected match
    const outcomesDiv = document.getElementById(`outcomes-${matchId}`);
    const icon = card.querySelector('.toggle-match i');

    if (outcomesDiv && outcomesDiv.style.display === 'none') {
        outcomesDiv.style.display = 'block';
        icon.className = 'fas fa-chevron-up me-1';
        card.querySelector('.toggle-match').innerHTML = '<i class="fas fa-chevron-up me-1"></i>Hide Outcomes';

        // Set as current match
        keyboardState.currentMatch = matchId;
        keyboardState.currentOutcomeIndex = -1;

        // Get outcomes for navigation
        const outcomeCards = outcomesDiv.querySelectorAll('.card');
        keyboardState.outcomes = Array.from(outcomeCards);

        // Highlight the match card
        card.classList.add('border-primary');
        card.style.boxShadow = '0 0 0 0.2rem rgba(13, 110, 253, 0.25)';

        // Update keyboard help content
        updateKeyboardHelpContent();
    }
}

function closeCurrentMatch(clearInputs = false) {
    if (keyboardState.currentMatch) {
        const card = document.querySelector(`[data-match-id="${keyboardState.currentMatch}"]`);
        if (card) {
            const outcomesDiv = document.getElementById(`outcomes-${keyboardState.currentMatch}`);
            const icon = card.querySelector('.toggle-match i');

            outcomesDiv.style.display = 'none';
            icon.className = 'fas fa-chevron-down me-1';
            card.querySelector('.toggle-match').innerHTML = '<i class="fas fa-chevron-down me-1"></i>Select Outcomes';

            // Clear input amounts if requested (ESC key behavior)
            if (clearInputs) {
                const amountInputs = outcomesDiv.querySelectorAll('.amount-input');
                amountInputs.forEach(input => {
                    input.value = '';
                    input.dispatchEvent(new Event('input')); // Trigger update of bet summary
                });
            }

            // Remove highlighting
            card.classList.remove('border-primary');
            card.style.boxShadow = '';
        }

        keyboardState.currentMatch = null;
        keyboardState.currentOutcomeIndex = -1;
        keyboardState.outcomes = [];

        // Update keyboard help content
        updateKeyboardHelpContent();
    }
}

function navigateOutcomes() {
    if (keyboardState.outcomes.length === 0) return;

    // Remove previous highlighting
    if (keyboardState.currentOutcomeIndex >= 0) {
        keyboardState.outcomes[keyboardState.currentOutcomeIndex].style.border = '';
        keyboardState.outcomes[keyboardState.currentOutcomeIndex].style.boxShadow = '';
    }

    // Move to next outcome
    keyboardState.currentOutcomeIndex = (keyboardState.currentOutcomeIndex + 1) % keyboardState.outcomes.length;

    // Highlight current outcome
    const currentOutcome = keyboardState.outcomes[keyboardState.currentOutcomeIndex];
    currentOutcome.style.border = '3px solid #0d6efd';
    currentOutcome.style.boxShadow = '0 0 0 0.2rem rgba(13, 110, 253, 0.25)';

    // Focus on the input field within the outcome card
    const amountInput = currentOutcome.querySelector('.amount-input');
    if (amountInput) {
        amountInput.focus();
        amountInput.select(); // Select all text for easy replacement
    }

    // Scroll into view
    currentOutcome.scrollIntoView({ behavior: 'smooth', block: 'center' });
}

function enterBetAmount(amount) {
    if (keyboardState.currentOutcomeIndex < 0 || !keyboardState.outcomes[keyboardState.currentOutcomeIndex]) return;

    const outcomeCard = keyboardState.outcomes[keyboardState.currentOutcomeIndex];
    const amountInput = outcomeCard.querySelector('.amount-input');

    if (amountInput) {
        amountInput.value = amount.toFixed(2);
        amountInput.dispatchEvent(new Event('input')); // Trigger the input event to update summary

        // Visual feedback
        amountInput.classList.add('is-valid');
        setTimeout(() => amountInput.classList.remove('is-valid'), 500);

        // Move to next outcome automatically
        setTimeout(() => navigateOutcomes(), 200);
    }
}

let selectedOutcomes = new Map(); // matchId -> { outcomes: [], amounts: [] }

// Function to load and display available matches for betting
function loadAvailableMatches() {
    console.log('🔍 loadAvailableMatches() called');

    const container = document.getElementById('available-matches-container');
    const countBadge = document.getElementById('available-matches-count');

    if (!container) {
        console.error('❌ available-matches-container not found');
        return;
    }

    console.log('📡 Making API request to /api/cashier/available-matches');

    fetch('/api/cashier/available-matches')
        .then(response => {
            console.log('📡 API response status:', response.status);
            if (!response.ok) {
                throw new Error('API request failed: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            console.log('📦 API response data:', data);

            if (data.success) {
                // Update count badge
                countBadge.textContent = data.total;
                countBadge.className = data.total > 0 ? 'badge bg-success ms-2' : 'badge bg-warning ms-2';

                updateAvailableMatchesDisplay(data, container);
            } else {
                container.innerHTML = `
                    <div class="text-center text-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>Error loading matches: ${data.error || 'Unknown error'}
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('❌ Error loading matches:', error);
            container.innerHTML = `
                <div class="text-center text-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>Error loading matches: ${error.message}
                </div>
            `;
        });
}

function generateOutcomeOptionsHTML(match, matchId) {
    // Use actual outcomes from the database if available, otherwise fallback to defaults
    let outcomes = match.outcomes || [];
    
    // If no outcomes from database, use standard fallback
    if (outcomes.length === 0) {
        console.warn(`No outcomes found for match ${matchId}, using standard fallback`);
        outcomes = [
            { outcome_name: 'WIN1', display_name: `WIN1 - ${match.fighter1_township}`, outcome_id: null },
            { outcome_name: 'WIN2', display_name: `WIN2 - ${match.fighter2_township}`, outcome_id: null },
            { outcome_name: 'X', display_name: 'X - Draw', outcome_id: null }
        ];
    }
    
    let outcomesHTML = '';
    const colors = ['border-success text-success', 'border-danger text-danger', 'border-warning text-warning', 'border-info text-info', 'border-primary text-primary'];
    
    outcomes.forEach((outcome, index) => {
        const colorClass = colors[index % colors.length];
        const outcomeName = outcome.outcome_name;
        const displayName = outcome.display_name || outcome.outcome_name;
        
        outcomesHTML += `
            <div class="col-md-4 mb-3">
                <div class="card ${colorClass.split(' ')[0]}">
                    <div class="card-body text-center p-3">
                        <div class="mb-2">
                            <label class="form-label fw-bold ${colorClass.split(' ')[1]}">
                                ${displayName}
                            </label>
                        </div>
                        <div class="input-group input-group-sm">
                            <span class="input-group-text currency-symbol">USh</span>
                            <input type="number" class="form-control amount-input"
                                   id="amount-${matchId}-${outcomeName}"
                                   data-match-id="${matchId}"
                                   data-outcome="${outcomeName}"
                                   placeholder="0.00" step="0.01" min="0.01">
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    
    return outcomesHTML;
}

function updateAvailableMatchesDisplay(data, container) {
    if (data.total === 0) {
        container.innerHTML = `
            <div class="text-center text-muted">
                <i class="fas fa-info-circle me-2"></i>No matches available for betting today
                <div class="mt-2">
                    <small>Matches must be in 'bet' status to accept wagers</small>
                </div>
            </div>
        `;
        return;
    }

    let htmlContent = '';

    data.matches.forEach(match => {
        const matchId = match.id;
        const startTime = match.start_time ? new Date(match.start_time).toLocaleString() : 'TBD';
        
        htmlContent += `
            <div class="card mb-3 match-card" data-match-id="${matchId}">
                <div class="card-header bg-light">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h6 class="mb-0">
                                <i class="fas fa-fist-raised me-2 text-primary"></i>
                                Match #${match.match_number}: ${match.fighter1_township} vs ${match.fighter2_township}
                            </h6>
                            <small class="text-muted">
                                <i class="fas fa-map-marker-alt me-1"></i>${match.venue_kampala_township} • 
                                <i class="fas fa-clock me-1"></i>${startTime}
                            </small>
                        </div>
                        <div class="col-md-4 text-end">
                            <button class="btn btn-outline-primary btn-sm toggle-match" data-match-id="${matchId}">
                                <i class="fas fa-chevron-down me-1"></i>Select Outcomes
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body match-outcomes" id="outcomes-${matchId}" style="display: none;">
                    <div class="row">
                        <div class="col-12">
                            <h6 class="text-primary mb-3">
                                <i class="fas fa-target me-2"></i>Available Betting Outcomes
                            </h6>
                        </div>
                    </div>
                    <div class="row">
                        ${generateOutcomeOptionsHTML(match, matchId)}
                    </div>
                </div>
            </div>
        `;
    });

    container.innerHTML = htmlContent;

    // Add event listeners for toggle buttons
    container.querySelectorAll('.toggle-match').forEach(button => {
        button.addEventListener('click', function() {
            const matchId = this.getAttribute('data-match-id');
            const outcomesDiv = document.getElementById(`outcomes-${matchId}`);
            const icon = this.querySelector('i');
            
            if (outcomesDiv.style.display === 'none') {
                outcomesDiv.style.display = 'block';
                icon.className = 'fas fa-chevron-up me-1';
                this.innerHTML = '<i class="fas fa-chevron-up me-1"></i>Hide Outcomes';
            } else {
                outcomesDiv.style.display = 'none';
                icon.className = 'fas fa-chevron-down me-1';
                this.innerHTML = '<i class="fas fa-chevron-down me-1"></i>Select Outcomes';
            }
        });
    });

    // Add event listeners for amount inputs only
    container.querySelectorAll('.amount-input').forEach(input => {
        input.addEventListener('input', function() {
            // Clear other outcomes for this match when entering an amount
            const matchId = this.getAttribute('data-match-id');
            const currentOutcome = this.getAttribute('data-outcome');

            // Clear all other amount inputs for this match
            container.querySelectorAll(`.amount-input[data-match-id="${matchId}"]`).forEach(otherInput => {
                if (otherInput !== this) {
                    otherInput.value = '';
                }
            });

            updateBetSummary();
        });
    });
}

function updateBetSummary() {
    const summaryContent = document.getElementById('bet-summary-content');
    const totalSection = document.getElementById('bet-total-section');
    const totalAmountElement = document.getElementById('bet-total-amount');
    const submitButton = document.getElementById('btn-submit-bet');
    
    // Clear previous selections
    selectedOutcomes.clear();
    
    let totalAmount = 0;
    let hasSelections = false;
    let summaryHTML = '';
    
    // Collect all amount inputs with values > 0
    document.querySelectorAll('.amount-input').forEach(input => {
        const amount = parseFloat(input.value) || 0;
        
        if (amount > 0) {
            const matchId = input.getAttribute('data-match-id');
            const outcome = input.getAttribute('data-outcome');
            
            hasSelections = true;
            totalAmount += amount;
            
            // Store selection
            if (!selectedOutcomes.has(matchId)) {
                selectedOutcomes.set(matchId, { outcomes: [], amounts: [] });
            }
            const matchSelections = selectedOutcomes.get(matchId);
            matchSelections.outcomes.push(outcome);
            matchSelections.amounts.push(amount);
            
            // Get match info for display
            const matchCard = input.closest('.match-card');
            const matchTitle = matchCard.querySelector('h6').textContent.trim();
            
            summaryHTML += `
                <div class="mb-2 p-2 bg-light rounded">
                    <small class="fw-bold d-block">${matchTitle.split(':')[1]}</small>
                    <small class="text-primary">${outcome}</small>
                    <div class="text-end">
                        <strong class="text-success currency-amount" data-amount="${amount}">${formatCurrency(amount)}</strong>
                    </div>
                </div>
            `;
        }
    });
    
    if (hasSelections) {
        summaryContent.innerHTML = summaryHTML;
        totalSection.style.display = 'block';
        totalAmountElement.textContent = formatCurrency(totalAmount);
        submitButton.disabled = false;
    } else {
        summaryContent.innerHTML = `
            <div class="text-center text-muted">
                <i class="fas fa-info-circle me-2"></i>
                <small>Enter amounts for outcomes to start building your bet</small>
            </div>
        `;
        totalSection.style.display = 'none';
        submitButton.disabled = true;
    }
}

function submitBet() {
    if (selectedOutcomes.size === 0) {
        showNotification('Please select at least one outcome with an amount', 'error');
        return;
    }
    
    // Prepare bet data
    const betData = {
        bet_details: []
    };
    
    selectedOutcomes.forEach((selections, matchId) => {
        selections.outcomes.forEach((outcome, index) => {
            betData.bet_details.push({
                match_id: parseInt(matchId),
                outcome: outcome,
                amount: selections.amounts[index]
            });
        });
    });
    
    console.log('📤 Submitting bet data:', betData);
    
    // Submit to API
    fetch('/api/cashier/bets', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(betData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('Bet submitted successfully!', 'success');
            setTimeout(() => {
                window.location.href = `/cashier/bets/${data.bet_id}`;
            }, 1500);
        } else {
            showNotification('Failed to submit bet: ' + (data.error || 'Unknown error'), 'error');
        }
    })
    .catch(error => {
        showNotification('Error submitting bet: ' + error.message, 'error');
    });
}

function initializeKeyboardHelp() {
    const helpPanel = document.getElementById('keyboard-help-panel');

    // Auto-minimize after 10 seconds
    setTimeout(() => {
        if (helpPanel && !helpPanel.classList.contains('minimized')) {
            helpPanel.classList.add('minimized');
        }
    }, 10000);

    // Add global keyboard listener for 'h' key to toggle help
    document.addEventListener('keydown', function(event) {
        if (event.key === 'h' || event.key === 'H') {
            event.preventDefault();
            toggleKeyboardHelp();
        }
    });

    // Update help content based on current state
    updateKeyboardHelpContent();
}

function toggleKeyboardHelp() {
    const helpPanel = document.getElementById('keyboard-help-panel');
    if (helpPanel) {
        helpPanel.classList.toggle('minimized');
    }
}

function updateKeyboardHelpContent() {
    const contentDiv = document.getElementById('keyboard-help-content');
    if (!contentDiv) return;

    let shortcuts = [];

    if (!keyboardState.currentMatch) {
        // Match selection state
        shortcuts = [
            { key: '1-9 + Enter', action: 'Select Match' },
            { key: 'Esc', action: 'Back to Bets' }
        ];
    } else {
        // Outcome navigation state
        shortcuts = [
            { key: 'Tab', action: 'Navigate Outcomes' },
            { key: 'Digits + Enter', action: 'Enter Bet Amount' },
            { key: 'Enter', action: 'Submit Bet' },
            { key: 'Esc', action: 'Cancel/Close' }
        ];
    }

    let html = '';
    shortcuts.forEach(shortcut => {
        html += `
            <div class="keyboard-shortcut">
                <kbd>${shortcut.key}</kbd>
                <span>${shortcut.action}</span>
            </div>
        `;
    });

    contentDiv.innerHTML = html;
}

function showNotification(message, type = 'info') {
    // Simple notification system - could be enhanced with toast notifications
    const alertClass = type === 'success' ? 'alert-success' : type === 'error' ? 'alert-danger' : 'alert-info';
    const notification = document.createElement('div');
    notification.className = `alert ${alertClass} alert-dismissible fade show position-fixed`;
    notification.style.top = '20px';
    notification.style.right = '20px';
    notification.style.zIndex = '9999';
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(notification);

    // Auto-remove after 3 seconds
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}
</script>
<script>
// Initialize dashboard with timer functionality
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Dashboard with timer support
    if (typeof Dashboard !== 'undefined') {
        Dashboard.init({
            user: {
                username: '{{ current_user.username }}',
                role: 'cashier'
            }
        });
    }
});
</script>
{% endblock %}