{% load static i18n %}{% get_current_language as LANGUAGE_CODE %}<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE }}" dir="{% if LANGUAGE_CODE == 'ar' %}rtl{% else %}ltr{% endif %}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% trans "Customer Display" %}</title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700&family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">
    
    {% if LANGUAGE_CODE == 'ar' %}
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css">
    {% else %}
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    {% endif %}
    
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="{% static 'css/custom.css' %}?v={{ deployment_timestamp }}">

    <style>
        body {
            overflow: hidden;
            background-color: #f8f9fa;
            font-size: 0.85rem; /* Reduced font size further */
        }
        #welcome-screen {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: white;
            z-index: 1000;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
        }
        #main-display {
            height: 100vh;
            display: none; /* Hidden by default until data arrives */
        }
        .cart-item {
            background: white;
            border-radius: 8px;
            margin-bottom: 0.25rem; /* Reduced margin */
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
            padding: 0.5rem; /* Reduced padding */
        }
        .total-section {
            background: white;
            height: 100%;
            padding: 1rem; /* Reduced padding */
            display: flex;
            flex-direction: column;
            justify-content: center;
        }
        .grand-total {
            font-size: 2rem; /* Slightly smaller grand total */
            font-weight: bold;
            color: var(--bs-primary);
        }
        
        /* Debug Panel */
        #debugStatus {
            position: fixed;
            bottom: 10px;
            right: 10px;
            background: rgba(0,0,0,0.8);
            color: lime;
            padding: 5px 10px;
            border-radius: 5px;
            font-family: monospace;
            font-size: 10px;
            z-index: 2000;
            pointer-events: auto;
            max-width: 300px;
        }
        .debug-btn {
            font-size: 10px; 
            padding: 2px 6px; 
            margin-left: 5px; 
            cursor: pointer; 
            background: #444; 
            border: 1px solid #666; 
            color: white;
        }
        #debugLog {
            display: none;
            position: fixed;
            bottom: 40px;
            right: 10px;
            width: 300px;
            height: 200px;
            background: rgba(0,0,0,0.9);
            color: #ddd;
            font-size: 10px;
            overflow-y: auto;
            padding: 10px;
            border-radius: 5px;
            z-index: 2000;
        }
    </style>
</head>
<body>

    <!-- Welcome Screen -->
    <div id="welcome-screen">
        <div class="mb-4">
            {% if settings.logo %}
            <img src="{{ settings.logo.url }}" alt="Logo" style="max-height: 100px;" class="mb-3">
            {% else %}
            <i class="bi bi-cart3 text-primary display-4 mb-3"></i>
            {% endif %}
            <h2 class="fw-bold">{{ settings.business_name }}</h2>
            <p class="text-muted">{% trans "Welcome! Please wait while we prepare your order." %}</p>
        </div>
        
        <!-- Diagnostic Info for User -->
        <div class="mt-4 text-muted small">
            <div id="connection-status">Waiting for POS...</div>
        </div>
    </div>

    <!-- Main Transaction Display -->
    <div id="main-display" class="container-fluid p-0">
        <div class="row g-0 h-100">
            <!-- Left: Item List -->
            <div class="col-8 h-100 bg-light p-3 overflow-auto">
                <h5 class="mb-3 fw-bold">{% trans "Your Order" %}</h5>
                <div id="cart-items-container">
                    <!-- Items injected here -->
                </div>
            </div>

            <!-- Right: Totals -->
            <div class="col-4 h-100 shadow-lg">
                <div class="total-section">
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted">{% trans "Subtotal" %}</span>
                        <span id="display-subtotal" class="fw-bold">0.00</span>
                    </div>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted">{% trans "VAT" %}</span>
                        <span id="display-tax" class="fw-bold">0.00</span>
                    </div>
                    <div class="d-flex justify-content-between mb-3 text-success">
                        <span>{% trans "Discount" %}</span>
                        <span id="display-discount">-0.00</span>
                    </div>
                    <hr>
                    <div class="text-center mt-3">
                        <div class="text-uppercase text-muted small fw-bold mb-1">{% trans "Total to Pay" %}</div>
                        <div id="display-total" class="grand-total">0.00</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Debug Overlay -->
    <div id="debugStatus">
        <span id="statusText">Init (v10.1 - Standalone/Compact)...</span>
        <button class="debug-btn" onclick="runTestRender()">Test Render</button>
        <button class="debug-btn" onclick="toggleLog()">Log</button>
    </div>
    <div id="debugLog"></div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const currency = '{{ site_settings.currency_symbol|escapejs }}';
        
        // Elements
        const welcomeScreen = document.getElementById('welcome-screen');
        const mainDisplay = document.getElementById('main-display');
        const itemsContainer = document.getElementById('cart-items-container');
        const statusText = document.getElementById('statusText');
        const logPanel = document.getElementById('debugLog');

        // ---------------------------------------------------------
        // Logging & Debug
        // ---------------------------------------------------------
        function log(msg) {
            const time = new Date().toLocaleTimeString();
            console.log(`[CFD ${time}] ${msg}`);
            logPanel.innerHTML += `<div>[${time}] ${msg}</div>`;
            logPanel.scrollTop = logPanel.scrollHeight;
        }

        function toggleLog() {
            logPanel.style.display = logPanel.style.display === 'none' ? 'block' : 'none';
        }

        function setStatus(msg) {
            statusText.innerText = msg;
        }

        // ---------------------------------------------------------
        // Rendering Logic
        // ---------------------------------------------------------
        function updateDisplay(data) {
            // Hide welcome, show main
            welcomeScreen.style.display = 'none';
            mainDisplay.style.display = 'block';

            if (!data.cart || data.cart.length === 0) {
                if (data.type === 'clear') {
                     log('Cart cleared');
                     welcomeScreen.style.display = 'flex';
                     mainDisplay.style.display = 'none';
                     return;
                }
            }

            // Render Items
            let html = '';
            data.cart.forEach(item => {
                html += `
                    <div class="cart-item d-flex justify-content-between align-items-center animate__animated animate__fadeIn">
                        <div class="d-flex align-items-center gap-2">
                            <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" style="width:25px; height:25px; font-weight:bold; font-size: 0.8rem;">
                                ${item.quantity}
                            </div>
                            <div>
                                <div class="fw-bold text-dark" style="font-size: 0.9rem;">${item.name_ar}</div>
                                <div class="text-muted small" style="font-size: 0.75rem;">${item.name_en}</div>
                            </div>
                        </div>
                        <div class="fw-bold" style="font-size: 0.9rem;">
                            ${currency} ${(item.price * item.quantity).toFixed(2)}
                        </div>
                    </div>
                `;
            });
            itemsContainer.innerHTML = html;

            // Render Totals
            document.getElementById('display-subtotal').innerText = currency + ' ' + (data.totals.subtotal).toFixed(3);
            document.getElementById('display-tax').innerText = currency + ' ' + (data.totals.tax).toFixed(3);
            document.getElementById('display-discount').innerText = '- ' + currency + ' ' + (data.totals.discount).toFixed(3);
            document.getElementById('display-total').innerText = currency + ' ' + (data.totals.total).toFixed(3);
            
            setStatus('Sync: ' + new Date().toLocaleTimeString());
        }

        // ---------------------------------------------------------
        // Communication Logic
        // ---------------------------------------------------------
        let lastProcessedTimestamp = 0;

        function handleMessage(data) {
            if (!data) return;
            
            // Dedup based on timestamp if provided
            if (data.timestamp && data.timestamp <= lastProcessedTimestamp) {
                return;
            }
            if (data.timestamp) lastProcessedTimestamp = data.timestamp;

            log('New Data: ' + data.type);
            if (data.type === 'update_cart') {
                updateDisplay(data);
            } else if (data.type === 'clear') {
                welcomeScreen.style.display = 'flex';
                mainDisplay.style.display = 'none';
                setStatus('Cleared');
            }
        }

        // Server Sync Polling (v8)
        // The most reliable method when windows are isolated
        setInterval(() => {
            fetch('/api/pos/sync/state/')
                .then(res => res.json())
                .then(data => {
                    if (data.status === 'empty') return;
                    
                    // If we got data, check timestamp
                    if (data.timestamp && data.timestamp > lastProcessedTimestamp) {
                        handleMessage(data);
                    }
                })
                .catch(e => {
                    // silent fail, maybe offline
                });
                
            // Also keep checking LocalStorage as a backup for same-origin speed
            try {
                const raw = localStorage.getItem('pos_cart_update');
                if (raw) {
                    const data = JSON.parse(raw);
                    if (data.timestamp > lastProcessedTimestamp) handleMessage(data);
                }
            } catch(e) {}

        }, 1000);


        // ---------------------------------------------------------
        // Diagnostics
        // ---------------------------------------------------------
        window.runTestRender = function() {
            log('Running Test Render');
            const testData = {
                type: 'update_cart',
                timestamp: Date.now(),
                cart: [
                    { name_en: 'Test Item A', name_ar: 'منتج تجريبي أ', quantity: 2, price: 10.00 },
                    { name_en: 'Test Item B', name_ar: 'منتج تجريبي ب', quantity: 1, price: 5.50 }
                ],
                totals: { subtotal: 25.50, tax: 3.825, discount: 0, total: 29.325 }
            };
            updateDisplay(testData);
        };

    </script>
</body>
</html>