{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-12">
        <h1 class="mb-4">
            <i class="fas fa-info-circle me-2"></i>Bet Details
            <small class="text-muted">Bet ID: {{ bet.uuid[:8] }}...</small>
        </h1>
    </div>
</div>

<!-- Back button and controls -->
<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-cog me-2"></i>Bet Controls
                </h5>
            </div>
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-md-3 mb-3">
                        <a href="{{ url_for('main.cashier_bets') }}" class="btn btn-outline-secondary w-100">
                            <i class="fas fa-arrow-left me-2"></i>Back to Bets
                        </a>
                    </div>
                    <div class="col-md-3 mb-3">
                        <button class="btn btn-outline-info w-100 btn-preview-bet"
                                data-bet-id="{{ bet.uuid }}"
                                title="Preview Bet Receipt">
                            <i class="fas fa-eye me-2"></i>Preview Receipt
                        </button>
                    </div>
                    <div class="col-md-3 mb-3">
                        <button class="btn btn-outline-primary w-100 btn-print-bet"
                                data-bet-id="{{ bet.uuid }}"
                                title="Print Bet Receipt Directly">
                            <i class="fas fa-print me-2"></i>Print Directly
                        </button>
                    </div>
                    <div class="col-md-3 mb-3">
                        {% if bet.has_pending %}
                        <button class="btn btn-danger w-100" id="btn-cancel-bet" data-bet-uuid="{{ bet.uuid }}">
                            <i class="fas fa-times me-2"></i>Cancel Entire Bet
                        </button>
                        {% endif %}
                    </div>
                    <div class="col-md-3 mb-3">
                        <div class="text-center">
                            <strong class="text-success h4 currency-amount" data-amount="{{ bet.total_amount|round(2) }}">Total: €{{ bet.total_amount|round(2) }}</strong>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Main Content Layout -->
<div class="row">
    <!-- Bet Details List - 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-ul me-2"></i>Bet Details
                    <span class="badge bg-info ms-2">{{ bet.bet_count }} items</span>
                </h5>
            </div>
            <div class="card-body">
                <div id="bet-details-container">
                    {% if bet.bet_details %}
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead class="table-dark">
                                <tr>
                                    <th><i class="fas fa-hashtag me-1"></i>Match</th>
                                    <th><i class="fas fa-target me-1"></i>Outcome</th>
                                    <th><i class="fas fa-euro-sign me-1"></i>Amount</th>
                                    <th><i class="fas fa-flag me-1"></i>Result</th>
                                    <th><i class="fas fa-trophy me-1"></i>Winning Outcomes</th>
                                    <th><i class="fas fa-balance-scale me-1"></i>Under/Over</th>
                                    <th><i class="fas fa-cogs me-1"></i>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for detail in bet.bet_details %}
                                <tr>
                                    <td>
                                        <strong>Match #{{ detail.match.match_number }}</strong><br>
                                        <small class="text-muted">
                                            {{ detail.match.fighter1_township }} vs {{ detail.match.fighter2_township }}
                                        </small>
                                    </td>
                                    <td>
                                        <span class="badge bg-primary">{{ detail.outcome }}</span>
                                    </td>
                                    <td>
                                        <strong class="currency-amount" data-amount="{{ detail.amount|round(2) }}">€{{ detail.amount|round(2) }}</strong>
                                    </td>
                                    <td>
                                        {% if detail.result == 'pending' %}
                                            <span class="badge bg-warning">Pending</span>
                                        {% elif detail.result == 'win' %}
                                            <span class="badge bg-success">Won</span>
                                        {% elif detail.result == 'lost' %}
                                            <span class="badge bg-danger">Lost</span>
                                        {% elif detail.result == 'cancelled' %}
                                            <span class="badge bg-secondary">Cancelled</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if detail.match.winning_outcomes %}
                                            {% for outcome in detail.match.winning_outcomes %}
                                                <span class="badge bg-success">{{ outcome }}</span>
                                            {% endfor %}
                                        {% else %}
                                            <span class="text-muted">Not available</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if detail.match.under_over_result %}
                                            <span class="badge bg-info">{{ detail.match.under_over_result }}</span>
                                        {% else %}
                                            <span class="text-muted">Not available</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if detail.result == 'pending' %}
                                        <button class="btn btn-sm btn-outline-danger btn-delete-detail"
                                                data-detail-id="{{ detail.id }}"
                                                title="Delete this bet detail">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                        {% else %}
                                        <span class="text-muted">No actions</span>
                                        {% endif %}
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    {% else %}
                    <div class="text-center text-muted">
                        <i class="fas fa-inbox me-2"></i>No bet details found
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- Right Column - Bet Summary -->
    <div class="col-lg-3 col-md-4">
        <!-- Bet Summary -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-info me-2"></i>Bet Summary
                </h6>
            </div>
            <div class="card-body p-3">
                <dl class="mb-0 small">
                    <dt class="text-muted">Bet UUID</dt>
                    <dd class="font-monospace">{{ bet.uuid }}</dd>

                    <dt class="text-muted">Barcode ID</dt>
                    <dd class="font-monospace">
                        {% if bet.barcode_data %}
                            {{ bet.barcode_data }}
                        {% else %}
                            <span class="text-muted">Not available</span>
                        {% endif %}
                    </dd>

                    <dt class="text-muted">Created</dt>
                    <dd>{{ bet.bet_datetime.strftime('%Y-%m-%d %H:%M') }}</dd>

                    <dt class="text-muted">Fixture</dt>
                    <dd>{{ bet.fixture_id }}</dd>

                    <dt class="text-muted">Total Items</dt>
                    <dd><span class="badge bg-info">{{ bet.bet_count }}</span></dd>

                    <dt class="text-muted">Total Amount</dt>
                    <dd><strong class="text-success currency-amount" data-amount="{{ bet.total_amount|round(2) }}">€{{ bet.total_amount|round(2) }}</strong></dd>

                    <dt class="text-muted">Status</dt>
                    <dd>
                        {% if bet.has_pending %}
                            <span class="badge bg-warning">Has Pending</span>
                        {% else %}
                            <span class="badge bg-success">Completed</span>
                        {% endif %}
                    </dd>

                    <dt class="text-muted">Payment Status</dt>
                    <dd>
                        {% if bet.paid %}
                            <span class="badge bg-success"><i class="fas fa-check me-1"></i>Paid</span>
                        {% else %}
                            <span class="badge bg-secondary"><i class="fas fa-clock me-1"></i>Unpaid</span>
                        {% endif %}
                    </dd>
                </dl>
            </div>
        </div>

        <!-- QR Code for Verification -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-qrcode me-2"></i>Bet Verification
                </h6>
            </div>
            <div class="card-body p-3 text-center">
                <div id="bet-verification-qr" class="mb-3">
                    <div class="spinner-border spinner-border-sm" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
                <p class="text-muted small">
                    Scan this QR code for bet verification
                </p>
                <div class="input-group input-group-sm">
                    <input type="text" class="form-control" id="bet-uuid-text" value="{{ bet.uuid }}" readonly>
                    <button class="btn btn-outline-secondary btn-sm" onclick="copyBetUuid()">
                        <i class="fas fa-copy"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- Payment Actions -->
        {% if not bet.paid %}
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-money-bill me-2"></i>Payment Actions
                </h6>
            </div>
            <div class="card-body p-3">
                <button class="btn btn-success w-100" id="btn-mark-paid" data-bet-uuid="{{ bet.uuid }}">
                    <i class="fas fa-check me-2"></i>Mark as Paid
                </button>
                <p class="text-muted small mt-2 mb-0">
                    Mark this bet as paid when payment is received from customer
                </p>
            </div>
        </div>
        {% endif %}

        <!-- Results Summary -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-chart-pie me-2"></i>Results Summary
                </h6>
            </div>
            <div class="card-body p-3">
                <div class="row text-center">
                    <div class="col-6 mb-2">
                        <h6 class="text-warning mb-1">{{ results.pending }}</h6>
                        <small class="text-muted">Pending</small>
                    </div>
                    <div class="col-6 mb-2">
                        <h6 class="text-success mb-1">{{ results.won }}</h6>
                        <small class="text-muted">Won</small>
                    </div>
                    <div class="col-6 mb-2">
                        <h6 class="text-danger mb-1">{{ results.lost }}</h6>
                        <small class="text-muted">Lost</small>
                    </div>
                    <div class="col-6 mb-2">
                        <h6 class="text-secondary mb-1">{{ results.cancelled }}</h6>
                        <small class="text-muted">Cancelled</small>
                    </div>
                </div>
                <hr class="my-2">
                <div class="text-center">
                    <strong class="text-success currency-amount" data-amount="{{ results.winnings|round(2) }}">Winnings: €{{ results.winnings|round(2) }}</strong>
                </div>
            </div>
        </div>

        <!-- Session Info -->
        <div class="card">
            <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">Current Time</dt>
                    <dd id="current-time">Loading...</dd>
                </dl>
            </div>
        </div>
    </div>
</div>

<!-- Thermal Receipt Print Modal -->
<div class="modal fade" id="printReceiptModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-print me-2"></i>Print Receipt
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0">
                <div id="thermal-receipt" class="thermal-receipt">
                    <!-- Receipt content will be dynamically generated -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>Cancel
                </button>
                <button type="button" class="btn btn-primary" id="btn-print-receipt">
                    <i class="fas fa-print me-1"></i>Print
                </button>
            </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">
        <div class="keyboard-shortcut">
            <kbd>Enter</kbd>
            <span>Print Receipt</span>
        </div>
        <div class="keyboard-shortcut">
            <kbd>Esc</kbd>
            <span>Back to Bets</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: 250px;
    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 type="application/json" id="bet-data-json">
{
    "uuid": "{{ bet.uuid }}",
    "bet_datetime": "{{ bet.bet_datetime.strftime('%Y-%m-%d %H:%M:%S') }}",
    "fixture_id": "{{ bet.fixture_id }}",
    "total_amount": {{ bet.total_amount|round(2) }},
    "bet_count": {{ bet.bet_count }},
    "barcode_standard": "{{ bet.barcode_standard }}",
    "barcode_data": "{{ bet.barcode_data }}",
    "bet_details": [
        {% for detail in bet.bet_details %}
        {
            "match_number": "{{ detail.match.match_number if detail.match else 'Unknown' }}",
            "fighter1": "{{ detail.match.fighter1_township if detail.match else 'Unknown' }}",
            "fighter2": "{{ detail.match.fighter2_township if detail.match else 'Unknown' }}",
            "venue": "{{ detail.match.venue_kampala_township if detail.match else 'Unknown' }}",
            "outcome": "{{ detail.outcome }}",
            "amount": {{ detail.amount|round(2) }},
            "odds": {{ detail.odds|round(2) }},
            "potential_winning": {{ detail.potential_winning|round(2) }},
            "result": "{{ detail.result }}"
        }{% if not loop.last %},{% endif %}
        {% endfor %}
    ]
}
</script>
<script>
// Global bet data for printing
window.betData = JSON.parse(document.getElementById('bet-data-json').textContent);

// Update currency symbols when settings are loaded
document.addEventListener('currencySettingsLoaded', function(event) {
    // Update all currency amounts
    document.querySelectorAll('.currency-amount').forEach(element => {
        const amount = parseFloat(element.dataset.amount || 0);
        const prefix = element.textContent.includes('Total:') ? 'Total: ' :
                      element.textContent.includes('Winnings:') ? 'Winnings: ' : '';
        element.textContent = prefix + formatCurrency(amount);
    });
});

document.addEventListener('DOMContentLoaded', function() {
    // Check for print parameter and automatically print if present
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('print') === 'true') {
        // Automatically print the ticket after a short delay to ensure page is fully loaded
        setTimeout(() => {
            directPrintBet(window.betData.uuid);
        }, 1000);
    }

    // Generate QR code for bet verification
    generateBetVerificationQR();

    // Cancel entire bet button
    const cancelBetBtn = document.getElementById('btn-cancel-bet');
    if (cancelBetBtn) {
        cancelBetBtn.addEventListener('click', function() {
            const betUuid = this.dataset.betUuid;
            cancelEntireBet(betUuid);
        });
    }

    // Delete bet detail buttons
    const deleteDetailBtns = document.querySelectorAll('.btn-delete-detail');
    deleteDetailBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            const detailId = this.dataset.detailId;
            deleteBetDetail(detailId);
        });
    });

    // Preview bet button
    const previewBetBtns = document.querySelectorAll('.btn-preview-bet');
    previewBetBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            const betId = this.dataset.betId;
            generateThermalReceipt(betId);
        });
    });

    // Print bet button (direct print)
    const printBetBtns = document.querySelectorAll('.btn-print-bet');
    printBetBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            const betId = this.dataset.betId;
            directPrintBet(betId);
        });
    });

    // Print receipt button in modal
    const printReceiptBtn = document.getElementById('btn-print-receipt');
    if (printReceiptBtn) {
        printReceiptBtn.addEventListener('click', function() {
            printThermalReceipt();
        });
    }

    // Mark as paid button
    const markPaidBtn = document.getElementById('btn-mark-paid');
    if (markPaidBtn) {
        markPaidBtn.addEventListener('click', function() {
            const betUuid = this.dataset.betUuid;
            markBetAsPaid(betUuid);
        });
    }

    // Update current time every second
    setInterval(updateCurrentTime, 1000);
    updateCurrentTime();

    // Initialize keyboard navigation
    initializeBetDetailsKeyboardNavigation();

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

function initializeBetDetailsKeyboardNavigation() {
    // Global keyboard event listener for bet details page
    document.addEventListener('keydown', function(event) {
        // Handle Enter key for printing ticket
        if (event.key === 'Enter' && !isInInputField(event.target)) {
            event.preventDefault();
            // Print the ticket directly
            directPrintBet(window.betData.uuid);
            return;
        }

        // Handle Escape key for going back to bet list
        if (event.key === 'Escape') {
            event.preventDefault();
            window.location.href = '/cashier/bets';
            return;
        }
    });
}

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

function deleteBetDetail(detailId) {
    if (confirm('Are you sure you want to delete this bet detail? This action cannot be undone.')) {
        fetch(`/api/cashier/bet-details/${detailId}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('Bet detail deleted successfully', 'success');
                // Reload the page to update the display
                window.location.reload();
            } else {
                showNotification('Failed to delete bet detail: ' + (data.error || 'Unknown error'), 'error');
            }
        })
        .catch(error => {
            showNotification('Error deleting bet detail: ' + error.message, 'error');
        });
    }
}

function cancelEntireBet(betUuid) {
    if (confirm('Are you sure you want to cancel the entire bet? All pending bet details will be cancelled. This action cannot be undone.')) {
        fetch(`/api/cashier/bets/${betUuid}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('Entire bet cancelled successfully', 'success');
                // Redirect back to bets list
                window.location.href = '/cashier/bets';
            } else {
                showNotification('Failed to cancel bet: ' + (data.error || 'Unknown error'), 'error');
            }
        })
        .catch(error => {
            showNotification('Error cancelling bet: ' + error.message, 'error');
        });
    }
}

function updateCurrentTime() {
    const now = new Date();
    const timeString = now.toLocaleTimeString();
    const timeElement = document.getElementById('current-time');
    if (timeElement) {
        timeElement.textContent = timeString;
    }
}

function generateThermalReceipt(betId) {
    // Get bet details from the global bet data
    const receiptContainer = document.getElementById('thermal-receipt');
    const receiptHtml = generateReceiptHtml(window.betData);
    receiptContainer.innerHTML = receiptHtml;

    // Generate verification codes for preview
    generateVerificationCodes(window.betData.uuid).then(() => {
        // Show the modal after verification codes are loaded
        const modal = new bootstrap.Modal(document.getElementById('printReceiptModal'));
        modal.show();
    }).catch(error => {
        console.warn('Error generating verification codes for preview, showing modal anyway:', error);
        // Show modal even if verification codes fail
        const modal = new bootstrap.Modal(document.getElementById('printReceiptModal'));
        modal.show();
    });
}

function generateReceiptHtml(betData) {
    const currentDateTime = new Date().toLocaleString();

    let receiptHtml = `
        <div class="thermal-receipt-content">
            <!-- Header -->
            <div class="receipt-header">
                <div class="receipt-title">BETTING SLIP</div>
            </div>

            <!-- Separator -->
            <div class="receipt-separator">================================</div>

            <!-- Bet Information -->
            <div class="receipt-info">
                <div class="receipt-row">
                    <span>BET ID:</span>
                    <span>${betData.uuid.substring(0, 8).toUpperCase()}</span>
                </div>
                <div class="receipt-row">
                    <span>DATE:</span>
                    <span>${betData.bet_datetime}</span>
                </div>
                <div class="receipt-row">
                    <span>FIXTURE:</span>
                    <span>${betData.fixture_id}</span>
                </div>
                <div class="receipt-row">
                    <span>ITEMS:</span>
                    <span>${betData.bet_count}</span>
                </div>
            </div>

            <!-- Separator -->
            <div class="receipt-separator">================================</div>

            <!-- Bet Details -->
            <div class="receipt-bets">
    `;

    let totalAmount = 0;
    betData.bet_details.forEach((detail, index) => {
        totalAmount += parseFloat(detail.amount);
        receiptHtml += `
                <div class="receipt-bet-item">
                    <div class="receipt-match">
                        MATCH #${detail.match_number}
                    </div>
                    <div class="receipt-match-details">
                        ${detail.fighter1} vs ${detail.fighter2}
                    </div>
                    <div class="receipt-venue">
                        @ ${detail.venue}
                    </div>
                    <div class="receipt-bet-line">
                        <span>OUTCOME: ${detail.outcome}</span>
                        <span>${formatCurrency(parseFloat(detail.amount))}</span>
                    </div>
                    <div class="receipt-bet-line">
                        <span>ODDS: ${parseFloat(detail.odds).toFixed(2)}</span>
                        <span>POTENTIAL WIN: ${formatCurrency(parseFloat(detail.potential_winning))}</span>
                    </div>
                    <div class="receipt-status">
                        STATUS: ${detail.result.toUpperCase()}
                    </div>
                </div>
        `;

        if (index < betData.bet_details.length - 1) {
            receiptHtml += `<div class="receipt-separator">- - - - - - - - - - - - - - - - -</div>`;
        }
    });

    receiptHtml += `
            </div>

            <!-- Separator -->
            <div class="receipt-separator">================================</div>

            <!-- Total -->
            <div class="receipt-total">
                <div class="receipt-total-line">
                    <span>TOTAL AMOUNT:</span>
                    <span>${formatCurrency(totalAmount)}</span>
                </div>
            </div>

            <!-- Separator -->
            <div class="receipt-separator">================================</div>

            <!-- QR Code and Barcode (conditional based on settings) -->
            <div class="receipt-verification" id="receipt-verification-${betData.uuid}">
                <!-- QR Code and Barcode will be conditionally added here -->
            </div>

            <!-- Footer -->
            <div class="receipt-footer">
                <div>Thank you for betting with MBetter!</div>
                <div>Keep this slip for verification</div>
                <div class="receipt-timestamp">Printed: ${currentDateTime}</div>
            </div>
        </div>
    `;

    return receiptHtml;
}

function generateVerificationCodes(betUuid) {
    return new Promise((resolve) => {
        const verificationContainer = document.getElementById(`receipt-verification-${betUuid}`);
        if (!verificationContainer) {
            resolve();
            return;
        }

        let completedOperations = 0;
        const totalOperations = 2; // QR code check + barcode check

        function checkComplete() {
            completedOperations++;
            if (completedOperations >= totalOperations) {
                resolve();
            }
        }

        // Check QR code settings - QR codes should NOT print if disabled
        // Default to NOT showing QR codes if API fails
        let shouldShowQR = false;

        try {
            // Try to get QR settings from API
            fetch('/api/qrcode-settings')
                .then(response => {
                    if (!response.ok) {
                        console.warn('QR settings API failed with status:', response.status);
                        checkComplete();
                        return null;
                    }
                    return response.json();
                })
                .then(qrSettings => {
                    if (qrSettings && qrSettings.success && qrSettings.settings) {
                        shouldShowQR = qrSettings.settings.enabled === true && qrSettings.settings.show_on_thermal === true;
                        console.log('QR settings check result:', shouldShowQR, qrSettings.settings);
                    } else {
                        console.warn('Invalid QR settings response:', qrSettings);
                        shouldShowQR = false; // Default to not showing
                    }

                    // Add QR code if enabled
                    if (shouldShowQR) {
                        console.log('Adding QR code to receipt');
                        const qrHtml = `
                            <div class="receipt-qr">
                                <div class="qr-code" id="qr-code-${betUuid}"></div>
                                <div class="qr-text">Scan QR for verification</div>
                            </div>
                        `;
                        verificationContainer.insertAdjacentHTML('beforeend', qrHtml);

                        // Generate QR code
                        const qrContainer = document.getElementById(`qr-code-${betUuid}`);
                        if (qrContainer) {
                            const qrImageUrl = `https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=${encodeURIComponent(betUuid)}&format=png`;
                            qrContainer.innerHTML = `<img src="${qrImageUrl}" alt="QR Code" class="qr-image">`;
                        }
                    } else {
                        console.log('QR code disabled - not adding to receipt');
                    }
                    checkComplete();
                })
                .catch(error => {
                    console.warn('Failed to check QR code settings, defaulting to disabled:', error);
                    shouldShowQR = false; // Default to not showing on error
                    checkComplete();
                });
        } catch (error) {
            console.warn('Error in QR code settings check, defaulting to disabled:', error);
            shouldShowQR = false; // Default to not showing on error
            checkComplete();
        }

        // Check barcode settings - use saved barcode data instead of regenerating
        const betData = window.betData;
        if (betData && betData.barcode_data && betData.barcode_standard) {
            // Use saved barcode data from bet
            fetch('/api/barcode-settings')
                .then(response => response.json())
                .then(settings => {
                    if (settings.success && settings.settings && settings.settings.show_on_thermal) {
                        // Generate barcode image using the saved barcode data
                        return fetch(`/api/barcode/${betUuid}`)
                            .then(response => response.blob())
                            .then(blob => {
                                return new Promise((resolve) => {
                                    const reader = new FileReader();
                                    reader.onload = function() {
                                        const base64 = reader.result;
                                        // Add barcode to receipt
                                        const barcodeHtml = `
                                            <div class="receipt-barcode" id="barcode-container-${betUuid}">
                                                <div class="barcode-image" id="barcode-${betUuid}"></div>
                                                <div class="barcode-text">Scan barcode for verification</div>
                                            </div>
                                        `;
                                        verificationContainer.insertAdjacentHTML('beforeend', barcodeHtml);

                                        // Display barcode
                                        const barcodeElement = document.getElementById(`barcode-${betUuid}`);
                                        if (barcodeElement) {
                                            barcodeElement.innerHTML = `<img src="${base64}" alt="Barcode" class="barcode-img" style="width: 200px; height: 100px;">`;
                                        }
                                        resolve();
                                    };
                                    reader.readAsDataURL(blob);
                                });
                            })
                            .then(() => {
                                checkComplete();
                            })
                            .catch(error => {
                                console.warn('Failed to generate barcode image:', error);
                                checkComplete();
                            });
                    } else {
                        checkComplete();
                    }
                })
                .catch(error => {
                    console.warn('Failed to check barcode settings:', error);
                    checkComplete();
                });
        } else {
            checkComplete();
        }
    });
}

function printThermalReceipt() {
    // Mark bet as paid before printing
    markBetAsPaidForPrinting(window.betData.uuid).then(() => {
        const printContent = document.getElementById('thermal-receipt').innerHTML;
        const printWindow = window.open('', '', 'height=600,width=400');

        printWindow.document.write(`
            <html>
            <head>
                <title>Betting Receipt</title>
                <style>
                    @media print {
                        body { margin: 0; padding: 10px; font-family: 'Courier New', monospace; }
                        .thermal-receipt-content { width: 100%; }
                        .receipt-header { text-align: center; margin-bottom: 10px; }
                        .receipt-title { font-size: 18px; font-weight: bold; margin-bottom: 2px; }
                        .receipt-separator { text-align: center; margin: 8px 0; font-size: 10px; }
                        .receipt-info, .receipt-bets, .receipt-total, .receipt-footer { margin: 10px 0; }
                        .receipt-row, .receipt-bet-line, .receipt-total-line {
                            display: flex; justify-content: space-between; margin-bottom: 2px; font-size: 10px;
                        }
                        .receipt-bet-item { margin-bottom: 8px; }
                        .receipt-match { font-weight: bold; font-size: 12px; text-align: center; }
                        .receipt-match-details { font-size: 10px; text-align: center; margin-bottom: 2px; }
                        .receipt-venue { font-size: 9px; text-align: center; margin-bottom: 3px; }
                        .receipt-status { font-size: 9px; text-align: center; margin-top: 2px; }
                        .receipt-total { border-top: 1px solid #000; padding-top: 5px; font-weight: bold; }
                        .receipt-verification { text-align: center; margin: 10px 0; }
                        .receipt-qr, .receipt-barcode { margin: 5px 0; text-align: center; }
                        .qr-image { width: 80px; height: 80px; }
                        .qr-text, .barcode-text { font-size: 9px; margin-top: 3px; }
                        .barcode-img { width: auto; height: auto; max-width: 150px; }
                        .receipt-footer { text-align: center; font-size: 9px; margin-top: 10px; border-top: 1px solid #000; padding-top: 5px; }
                        .receipt-timestamp { margin-top: 5px; font-size: 8px; }
                    }

                    body {
                        font-family: 'Courier New', monospace;
                        font-size: 11px;
                        line-height: 1.2;
                        color: #000;
                        background: #fff;
                    }
                    .thermal-receipt-content {
                        max-width: 300px;
                        margin: 0 auto;
                        padding: 10px;
                    }
                    .receipt-header { text-align: center; margin-bottom: 15px; }
                    .receipt-title { font-size: 20px; font-weight: bold; margin-bottom: 3px; letter-spacing: 2px; }
                    .receipt-separator {
                        text-align: center;
                        margin: 12px 0;
                        font-size: 11px;
                        letter-spacing: -1px;
                    }
                    .receipt-info, .receipt-bets, .receipt-total, .receipt-footer { margin: 15px 0; }
                    .receipt-row, .receipt-bet-line, .receipt-total-line {
                        display: flex;
                        justify-content: space-between;
                        margin-bottom: 3px;
                        font-size: 11px;
                    }
                    .receipt-bet-item { margin-bottom: 12px; }
                    .receipt-match { font-weight: bold; font-size: 13px; text-align: center; }
                    .receipt-match-details { font-size: 11px; text-align: center; margin-bottom: 3px; }
                    .receipt-venue { font-size: 10px; text-align: center; margin-bottom: 4px; color: #666; }
                    .receipt-status { font-size: 10px; text-align: center; margin-top: 3px; font-weight: bold; }
                    .receipt-total {
                        border-top: 2px solid #000;
                        padding-top: 8px;
                        font-weight: bold;
                        font-size: 14px;
                    }
                    .receipt-verification { text-align: center; margin: 15px 0; }
                    .receipt-qr, .receipt-barcode { margin: 8px 0; text-align: center; }
                    .qr-image { width: 100px; height: 100px; border: 1px solid #ccc; }
                    .qr-text, .barcode-text { font-size: 10px; margin-top: 5px; }
                    .barcode-img { width: auto; height: auto; max-width: 200px; border: 1px solid #ccc; }
                    .receipt-footer {
                        text-align: center;
                        font-size: 10px;
                        margin-top: 15px;
                        border-top: 1px solid #000;
                        padding-top: 8px;
                    }
                    .receipt-timestamp { margin-top: 8px; font-size: 9px; color: #666; }
                </style>
            </head>
            <body>
                ${printContent}
            </body>
            </html>
        `);

        printWindow.document.close();
        printWindow.focus();

        // Wait for images to load then print
        setTimeout(() => {
            printWindow.print();
            printWindow.close();
        }, 500);
    }).catch(error => {
        console.error('Failed to mark bet as paid:', error);
        // Still print even if marking as paid fails
        const printContent = document.getElementById('thermal-receipt').innerHTML;
        const printWindow = window.open('', '', 'height=600,width=400');

        printWindow.document.write(`
            <html>
            <head>
                <title>Betting Receipt</title>
                <style>
                    @media print {
                        body { margin: 0; padding: 10px; font-family: 'Courier New', monospace; }
                        .thermal-receipt-content { width: 100%; }
                        .receipt-header { text-align: center; margin-bottom: 10px; }
                        .receipt-title { font-size: 18px; font-weight: bold; margin-bottom: 2px; }
                        .receipt-separator { text-align: center; margin: 8px 0; font-size: 10px; }
                        .receipt-info, .receipt-bets, .receipt-total, .receipt-footer { margin: 10px 0; }
                        .receipt-row, .receipt-bet-line, .receipt-total-line {
                            display: flex; justify-content: space-between; margin-bottom: 2px; font-size: 11px;
                        }
                        .receipt-bet-item { margin-bottom: 8px; }
                        .receipt-match { font-weight: bold; font-size: 12px; text-align: center; }
                        .receipt-match-details { font-size: 10px; text-align: center; margin-bottom: 2px; }
                        .receipt-venue { font-size: 9px; text-align: center; margin-bottom: 3px; }
                        .receipt-status { font-size: 9px; text-align: center; margin-top: 2px; }
                        .receipt-total { border-top: 1px solid #000; padding-top: 5px; font-weight: bold; }
                        .receipt-verification { text-align: center; margin: 10px 0; }
                        .receipt-qr, .receipt-barcode { margin: 5px 0; text-align: center; }
                        .qr-image { width: 80px; height: 80px; }
                        .qr-text, .barcode-text { font-size: 9px; margin-top: 3px; }
                        .barcode-img { width: auto; height: auto; max-width: 150px; }
                        .receipt-footer { text-align: center; font-size: 9px; margin-top: 10px; border-top: 1px solid #000; padding-top: 5px; }
                        .receipt-timestamp { margin-top: 5px; font-size: 8px; }
                    }

                    body {
                        font-family: 'Courier New', monospace;
                        font-size: 11px;
                        line-height: 1.2;
                        color: #000;
                        background: #fff;
                    }
                    .thermal-receipt-content {
                        max-width: 300px;
                        margin: 0 auto;
                        padding: 10px;
                    }
                    .receipt-header { text-align: center; margin-bottom: 15px; }
                    .receipt-title { font-size: 20px; font-weight: bold; margin-bottom: 3px; letter-spacing: 2px; }
                    .receipt-separator {
                        text-align: center;
                        margin: 12px 0;
                        font-size: 11px;
                        letter-spacing: -1px;
                    }
                    .receipt-info, .receipt-bets, .receipt-total, .receipt-footer { margin: 15px 0; }
                    .receipt-row, .receipt-bet-line, .receipt-total-line {
                        display: flex;
                        justify-content: space-between;
                        margin-bottom: 3px;
                        font-size: 12px;
                    }
                    .receipt-bet-item { margin-bottom: 12px; }
                    .receipt-match { font-weight: bold; font-size: 13px; text-align: center; }
                    .receipt-match-details { font-size: 11px; text-align: center; margin-bottom: 3px; }
                    .receipt-venue { font-size: 10px; text-align: center; margin-bottom: 4px; color: #666; }
                    .receipt-status { font-size: 10px; text-align: center; margin-top: 3px; font-weight: bold; }
                    .receipt-total {
                        border-top: 2px solid #000;
                        padding-top: 8px;
                        font-weight: bold;
                        font-size: 14px;
                    }
                    .receipt-verification { text-align: center; margin: 15px 0; }
                    .receipt-qr, .receipt-barcode { margin: 8px 0; text-align: center; }
                    .qr-image { width: 100px; height: 100px; border: 1px solid #ccc; }
                    .qr-text, .barcode-text { font-size: 10px; margin-top: 5px; }
                    .barcode-img { width: auto; height: auto; max-width: 200px; border: 1px solid #ccc; }
                    .receipt-footer {
                        text-align: center;
                        font-size: 10px;
                        margin-top: 15px;
                        border-top: 1px solid #000;
                        padding-top: 8px;
                    }
                    .receipt-timestamp { margin-top: 8px; font-size: 9px; color: #666; }
                </style>
            </head>
            <body>
                ${printContent}
            </body>
            </html>
        `);

        printWindow.document.close();
        printWindow.focus();

        // Wait for images to load then print
        setTimeout(() => {
            printWindow.print();
            printWindow.close();
        }, 500);
    });
}

function generateBetVerificationQR() {
    const betUuid = window.betData.uuid;
    const qrContainer = document.getElementById('bet-verification-qr');
    
    if (qrContainer && betUuid) {
        // Use QR Server API for generating QR code
        const qrImageUrl = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(betUuid)}&format=png`;
        qrContainer.innerHTML = `<img src="${qrImageUrl}" alt="Bet Verification QR Code" class="img-fluid" style="max-width: 200px;">`;
    }
}

function copyBetUuid() {
    const element = document.getElementById('bet-uuid-text');
    if (element) {
        element.select();
        element.setSelectionRange(0, 99999);
        document.execCommand('copy');
        
        // Show feedback
        const button = element.nextElementSibling;
        const originalHtml = button.innerHTML;
        button.innerHTML = '<i class="fas fa-check"></i>';
        button.classList.add('btn-success');
        button.classList.remove('btn-outline-secondary');
        
        setTimeout(() => {
            button.innerHTML = originalHtml;
            button.classList.remove('btn-success');
            button.classList.add('btn-outline-secondary');
        }, 2000);
        
        showNotification('Bet UUID copied to clipboard!', 'success');
    }
}

function markBetAsPaid(betUuid) {
    if (confirm('Are you sure you want to mark this bet as paid? This action cannot be undone.')) {
        fetch(`/api/cashier/bets/${betUuid}/mark-paid`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('Bet marked as paid successfully!', 'success');
                // Reload the page to update the display
                window.location.reload();
            } else {
                showNotification('Failed to mark bet as paid: ' + (data.error || 'Unknown error'), 'error');
            }
        })
        .catch(error => {
            showNotification('Error marking bet as paid: ' + error.message, 'error');
        });
    }
}

function markBetAsPaidForPrinting(betUuid) {
    return fetch(`/api/cashier/bets/${betUuid}/mark-paid`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            console.log('Bet marked as paid for printing');
        } else {
            throw new Error(data.error || 'Failed to mark bet as paid');
        }
    });
}

function directPrintBet(betId) {
    // Mark bet as paid before printing
    markBetAsPaidForPrinting(betId).then(() => {
        // Use the global bet data for direct printing
        const receiptHtml = generateReceiptHtml(window.betData);

        // Create temporary container for receipt content
        const tempContainer = document.createElement('div');
        tempContainer.innerHTML = receiptHtml;
        tempContainer.style.display = 'none';
        document.body.appendChild(tempContainer);

        // Generate verification codes and wait for completion
        generateVerificationCodes(window.betData.uuid).then(() => {
            // Get the updated HTML content after verification codes are added
            const updatedReceiptHtml = tempContainer.innerHTML;
            printDirectly(updatedReceiptHtml);
            document.body.removeChild(tempContainer);
        }).catch(error => {
            console.warn('Error generating verification codes, printing without them:', error);
            // Print anyway even if verification codes fail
            printDirectly(receiptHtml);
            document.body.removeChild(tempContainer);
        });
    }).catch(error => {
        console.error('Failed to mark bet as paid:', error);
        // Still print even if marking as paid fails
        const receiptHtml = generateReceiptHtml(window.betData);
        printDirectly(receiptHtml);
    });
}

function printDirectly(printContent) {
    const printWindow = window.open('', '', 'height=600,width=400');
    
    printWindow.document.write(`
        <html>
        <head>
            <title>Betting Receipt</title>
            <style>
                @media print {
                    body { margin: 0; padding: 10px; font-family: 'Courier New', monospace; }
                    .thermal-receipt-content { width: 100%; }
                    .receipt-header { text-align: center; margin-bottom: 10px; }
                    .receipt-logo { font-size: 24px; margin-bottom: 5px; }
                    .boxing-glove { color: #000; }
                    .receipt-title { font-size: 18px; font-weight: bold; margin-bottom: 2px; }
                    .receipt-subtitle { font-size: 12px; margin-bottom: 5px; }
                    .receipt-separator { text-align: center; margin: 8px 0; font-size: 10px; }
                    .receipt-info, .receipt-bets, .receipt-total, .receipt-footer { margin: 10px 0; }
                    .receipt-row, .receipt-bet-line, .receipt-total-line {
                        display: flex; justify-content: space-between; margin-bottom: 2px; font-size: 11px;
                    }
                    .receipt-bet-item { margin-bottom: 8px; }
                    .receipt-match { font-weight: bold; font-size: 12px; text-align: center; }
                    .receipt-match-details { font-size: 10px; text-align: center; margin-bottom: 2px; }
                    .receipt-venue { font-size: 9px; text-align: center; margin-bottom: 3px; }
                    .receipt-status { font-size: 9px; text-align: center; margin-top: 2px; }
                    .receipt-total { border-top: 1px solid #000; padding-top: 5px; font-weight: bold; }
                    .receipt-verification { text-align: center; margin: 10px 0; }
                    .receipt-qr, .receipt-barcode { margin: 5px 0; text-align: center; }
                    .qr-image { width: 80px; height: 80px; }
                    .qr-text, .barcode-text { font-size: 9px; margin-top: 3px; }
                    .barcode-img { width: auto; height: auto; max-width: 150px; }
                    .receipt-footer { text-align: center; font-size: 9px; margin-top: 10px; border-top: 1px solid #000; padding-top: 5px; }
                    .receipt-timestamp { margin-top: 5px; font-size: 8px; }
                }
            </style>
        </head>
        <body onload="window.print(); window.close();">
            ${printContent}
        </body>
        </html>
    `);
    
    printWindow.document.close();
}

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

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

function showNotification(message, type = 'info') {
    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);

    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}
</script>
{% endblock %}