<div id="patrol-dashboard" class="patrol-system">
    <!-- Patrol Header -->
    <div class="patrol-header">
        <h2>🚨 Patrol Tracking System</h2>
        <div class="patrol-meta">
            <span class="post-name" id="post-name">Loading...</span>
            <span class="current-time" id="current-time"></span>
        </div>
    </div>

    <!-- Countdown Timer -->
    <div class="countdown-section">
        <div class="countdown-box">
            <div class="countdown-label">Next Patrol Hour In:</div>
            <div class="countdown-timer" id="countdown-timer">
                <div class="timer-segment">
                    <span class="timer-value" id="countdown-minutes">00</span>
                    <span class="timer-unit">min</span>
                </div>
                <div class="timer-separator">:</div>
                <div class="timer-segment">
                    <span class="timer-value" id="countdown-seconds">00</span>
                    <span class="timer-unit">sec</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Current Hour Status -->
    <div class="status-section">
        <h3>Current Hour Patrol Status</h3>
        
        <div class="patrol-score">
            <div class="score-circle">
                <div class="score-value" id="score-value">0</div>
                <div class="score-max">/8</div>
            </div>
            <div class="score-details">
                <div class="detail-row">
                    <span class="label">Status:</span>
                    <span class="value status-badge" id="patrol-status">Missed</span>
                </div>
                <div class="detail-row">
                    <span class="label">Completion:</span>
                    <span class="value" id="completion-percentage">0%</span>
                </div>
                <div class="detail-row">
                    <span class="label">Scans:</span>
                    <span class="value" id="total-scans">0/8</span>
                </div>
            </div>
        </div>

        <!-- Progress Bar -->
        <div class="progress-bar-section">
            <div class="progress-bar">
                <div class="progress-fill" id="progress-fill" style="width: 0%"></div>
            </div>
            <div class="progress-text">
                <span id="progress-text">No scans yet</span>
            </div>
        </div>
    </div>

    <!-- Patrol Points Grid -->
    <div class="patrol-points-section">
        <h3>Patrol Points Status</h3>
        <div class="points-grid" id="points-grid">
            <!-- Points will be loaded here -->
        </div>
    </div>

    <!-- QR Scanner -->
    <div class="qr-scanner-section">
        <h3>📱 Scan QR Code</h3>
        <div class="scanner-box">
            <div id="qr-reader" style="width: 100%; height: 400px;"></div>
            <div class="scanner-controls">
                <button class="btn btn-primary" id="start-scanner">Start Scanner</button>
                <button class="btn btn-secondary" id="stop-scanner" style="display:none;">Stop Scanner</button>
            </div>
            <input type="hidden" id="qr-input" placeholder="Or paste QR code here">
            <small class="text-muted">Click above to open camera and scan patrol point QR codes</small>
        </div>
    </div>

    <!-- Last Scan Info -->
    <div class="last-scan-section">
        <h3>Last Scan</h3>
        <div class="last-scan-card" id="last-scan-card">
            <p class="text-muted">No scans yet</p>
        </div>
    </div>

    <!-- Recent Scans List -->
    <div class="recent-scans-section">
        <h3>Recent Scans (This Hour)</h3>
        <div class="scans-list" id="scans-list">
            <p class="text-muted">No scans recorded yet</p>
        </div>
    </div>

    <!-- Patrol History -->
    <div class="patrol-history-section">
        <h3>Patrol History (Last 7 Days)</h3>
        <div class="history-table">
            <table id="patrol-history-table">
                <thead>
                    <tr>
                        <th>Time</th>
                        <th>Score</th>
                        <th>Status</th>
                        <th>Completion</th>
                        <th>Scans</th>
                    </tr>
                </thead>
                <tbody id="patrol-history-body">
                    <tr><td colspan="5" class="text-center text-muted">Loading history...</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
.patrol-system {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

.patrol-header {
    margin-bottom: 30px;
    border-bottom: 2px solid #2563eb;
    padding-bottom: 15px;
}

.patrol-header h2 {
    margin: 0 0 10px 0;
    color: #1e40af;
}

.patrol-meta {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    color: #666;
}

.countdown-section {
    margin-bottom: 30px;
}

.countdown-box {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
}

.countdown-label {
    font-size: 14px;
    opacity: 0.9;
    margin-bottom: 10px;
}

.countdown-timer {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
}

.timer-segment {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.timer-value {
    font-size: 36px;
    font-weight: bold;
    line-height: 1;
}

.timer-unit {
    font-size: 12px;
    opacity: 0.8;
    margin-top: 5px;
}

.timer-separator {
    font-size: 24px;
    margin: 0 5px;
}

.status-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 30px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.patrol-score {
    display: flex;
    gap: 30px;
    margin-bottom: 20px;
    align-items: center;
}

.score-circle {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background: linear-gradient(135deg, #059669 0%, #10b981 100%);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: white;
    font-weight: bold;
}

.score-value {
    font-size: 48px;
    line-height: 1;
}

.score-max {
    font-size: 20px;
    opacity: 0.8;
}

.score-details {
    flex: 1;
}

.detail-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    font-size: 16px;
}

.detail-row .label {
    font-weight: 500;
    color: #666;
}

.detail-row .value {
    font-weight: 600;
    color: #1e40af;
}

.status-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 13px;
}

.status-badge.completed {
    background: #d1fae5;
    color: #059669;
}

.status-badge.incomplete {
    background: #fef3c7;
    color: #d97706;
}

.status-badge.missed {
    background: #fee2e2;
    color: #dc2626;
}

.progress-bar-section {
    margin-top: 20px;
}

.progress-bar {
    width: 100%;
    height: 24px;
    background: #e5e7eb;
    border-radius: 12px;
    overflow: hidden;
}

.progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #3b82f6 0%, #10b981 100%);
    transition: width 0.3s ease;
}

.progress-text {
    margin-top: 8px;
    font-size: 13px;
    color: #666;
}

.patrol-points-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 30px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.patrol-points-section h3 {
    margin-top: 0;
}

.points-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 15px;
}

.point-card {
    border: 1px solid #e5e7eb;
    padding: 15px;
    border-radius: 6px;
    transition: all 0.3s ease;
}

.point-card:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.point-card.completed {
    border-left: 4px solid #10b981;
    background: #f0fdf4;
}

.point-card.incomplete {
    border-left: 4px solid #f59e0b;
    background: #fffbf0;
}

.point-card.missed {
    border-left: 4px solid #ef4444;
    background: #fef2f2;
}

.point-name {
    font-weight: 600;
    margin-bottom: 8px;
}

.point-scans {
    font-size: 13px;
    color: #666;
    margin-bottom: 8px;
}

.point-score {
    display: flex;
    justify-content: space-between;
    font-size: 13px;
}

.qr-scanner-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 30px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.scanner-box {
    border: 2px dashed #d1d5db;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    background: #f9fafb;
}

#qr-reader {
    border-radius: 6px;
    overflow: hidden;
}

.scanner-controls {
    margin-top: 15px;
    display: flex;
    gap: 10px;
    justify-content: center;
}

.scanner-controls button {
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-weight: 500;
    transition: all 0.3s ease;
}

.btn.btn-primary {
    background: #2563eb;
    color: white;
}

.btn.btn-primary:hover {
    background: #1d4ed8;
}

.btn.btn-secondary {
    background: #6b7280;
    color: white;
}

.btn.btn-secondary:hover {
    background: #4b5563;
}

.last-scan-section,
.recent-scans-section,
.patrol-history-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 30px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.last-scan-card {
    border: 1px solid #e5e7eb;
    padding: 15px;
    border-radius: 6px;
    background: #f9fafb;
}

.scans-list {
    max-height: 300px;
    overflow-y: auto;
}

.scan-item {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    border-bottom: 1px solid #e5e7eb;
    font-size: 13px;
}

.scan-item:last-child {
    border-bottom: none;
}

.history-table {
    overflow-x: auto;
}

.history-table table {
    width: 100%;
    border-collapse: collapse;
}

.history-table th {
    background: #f3f4f6;
    padding: 12px;
    text-align: left;
    font-weight: 600;
    border-bottom: 2px solid #e5e7eb;
}

.history-table td {
    padding: 12px;
    border-bottom: 1px solid #e5e7eb;
}

.text-center {
    text-align: center;
}

.text-muted {
    color: #999;
}

/* Toast Notifications */
@keyframes slideInRight {
    from {
        transform: translateX(400px);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

@keyframes slideOutRight {
    from {
        transform: translateX(0);
        opacity: 1;
    }
    to {
        transform: translateX(400px);
        opacity: 0;
    }
}

.animate-slideInRight {
    animation: slideInRight 0.3s ease-in-out;
}

.animate-slideOutRight {
    animation: slideOutRight 0.3s ease-in-out;
}

/* Scanner Box Focus Effect */
.scanner-box {
    border: 2px solid #e5e7eb;
    transition: all 0.3s ease;
}

.scanner-box.scanning {
    border-color: #3b82f6;
    box-shadow: 0 0 10px rgba(59, 130, 246, 0.5);
}
</style>

<script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>

<script>
// QR Code Scanner using html5-qrcode library
let html5QrcodeScanner;
let scannerActive = false;
let currentPostId = new URLSearchParams(window.location.search).get('post_id');
let lastCountdownUpdate = 0;
let countdownInterval = null;
let lastScannedQR = null;
let scanDebounceTimer = null;
let consecutiveScanCount = 0;
const SCAN_DEBOUNCE_MS = 500; // Prevent duplicate scans within 500ms
const CONSECUTIVE_SCAN_THRESHOLD = 2; // Require 2 consecutive identical scans

document.addEventListener('DOMContentLoaded', function() {
    initializePatrolDashboard();
    
    // Start automatic updates - only check server every 60 seconds
    setInterval(updatePatrolStatus, 60000); // Update every 60 seconds (1 minute)
    
    // Start client-side countdown timer - updates every second
    startCountdownTimer();
    
    // Initialize scanner button
    const startBtn = document.getElementById('start-scanner');
    const stopBtn = document.getElementById('stop-scanner');
    if (startBtn) startBtn.addEventListener('click', startScanner);
    if (stopBtn) stopBtn.addEventListener('click', stopScanner);
});

async function initializePatrolDashboard() {
    if (!currentPostId) {
        console.log('No post_id provided to dashboard');
        document.getElementById('post-name').textContent = 'Select a post to begin';
        return;
    }

    // Load current status
    await updatePatrolStatus();
    
    // Load history
    await loadPatrolHistory();
}

async function updatePatrolStatus() {
    try {
        const response = await fetch(`?page=api&endpoint=patrol/status&post_id=${currentPostId}`);
        const data = await response.json();

        if (data.success) {
            updateUIWithPatrolData(data.data);
            updateCountdownUI(data.countdown);
        }
    } catch (error) {
        console.error('Failed to update patrol status:', error);
    }
}

function updateUIWithPatrolData(patrol) {
    // Update score
    document.getElementById('score-value').textContent = patrol.score;
    document.getElementById('completion-percentage').textContent = patrol.completion_percentage + '%';
    document.getElementById('total-scans').textContent = patrol.total_scans + '/8';
    document.getElementById('progress-fill').style.width = patrol.completion_percentage + '%';
    
    // Update status badge
    const statusBadge = document.getElementById('patrol-status');
    statusBadge.textContent = patrol.status;
    statusBadge.className = 'value status-badge ' + patrol.status.toLowerCase();

    // Update progress text
    const remainingPoints = 4 - (patrol.points ? patrol.points.filter(p => p.status === 'Completed').length : 0);
    document.getElementById('progress-text').textContent = `${patrol.score}/8 points (${remainingPoints} incomplete)`;

    // Update points grid
    const pointsGrid = document.getElementById('points-grid');
    pointsGrid.innerHTML = '';

    if (patrol.points && patrol.points.length > 0) {
        patrol.points.forEach(point => {
            const pointCard = document.createElement('div');
            pointCard.className = 'point-card ' + point.status.toLowerCase();
            pointCard.innerHTML = `
                <div class="point-name">${point.point_name}</div>
                <div class="point-scans">Scans: ${point.scan_count}/${point.max_scans}</div>
                <div class="point-score">
                    <span>Score: ${point.score}/2</span>
                    <span>${point.status}</span>
                </div>
            `;
            pointsGrid.appendChild(pointCard);
        });
    }
}

function updateCountdownUI(countdown) {
    const minutes = String(countdown.minutes).padStart(2, '0');
    const seconds = String(countdown.seconds).padStart(2, '0');
    
    document.getElementById('countdown-minutes').textContent = minutes;
    document.getElementById('countdown-seconds').textContent = seconds;
}

// Client-side countdown timer - calculates time to next hour without server calls
function startCountdownTimer() {
    const updateDisplay = () => {
        const now = new Date();
        const nextHour = new Date(now.getTime());
        nextHour.setHours(nextHour.getHours() + 1, 0, 0, 0);
        
        const timeLeft = nextHour - now;
        const minutes = Math.floor((timeLeft % 3600000) / 60000);
        const seconds = Math.floor((timeLeft % 60000) / 1000);
        
        document.getElementById('countdown-minutes').textContent = String(minutes).padStart(2, '0');
        document.getElementById('countdown-seconds').textContent = String(seconds).padStart(2, '0');
    };
    
    // Update immediately
    updateDisplay();
    
    // Then update every second
    if (countdownInterval) clearInterval(countdownInterval);
    countdownInterval = setInterval(updateDisplay, 1000);
}

function updateCountdown() {
    // For legacy support - now handled by startCountdownTimer
    // No longer makes server calls
}

function startScanner() {
    scannerActive = true;
    lastScannedQR = null;
    consecutiveScanCount = 0;
    document.getElementById('start-scanner').style.display = 'none';
    document.getElementById('stop-scanner').style.display = 'inline-block';
    
    // Initialize HTML5 QR Code Scanner with optimized settings
    try {
        html5QrcodeScanner = new Html5Qrcode("qr-reader");
        
        // Request camera access and start scanning with fast configuration
        html5QrcodeScanner.start(
            { facingMode: "environment" }, // Use rear camera
            {
                fps: 30,                   // Fast 30 FPS for real-time detection
                qrbox: { width: 300, height: 300 }, // Larger scan box
                aspectRatio: 1.0,
                disableFlip: false
            },
            onScanSuccess,
            onScanError
        ).catch(err => {
            console.error('Failed to start scanner:', err);
            alert('Camera access denied or unavailable. Please check permissions.');
            stopScanner();
        });
    } catch (error) {
        console.error('Scanner initialization error:', error);
        alert('Unable to initialize camera. Please try again.');
        stopScanner();
    }
}

function stopScanner() {
    if (html5QrcodeScanner && scannerActive) {
        try {
            html5QrcodeScanner.stop().then(() => {
                scannerActive = false;
                lastScannedQR = null;
                consecutiveScanCount = 0;
                if (scanDebounceTimer) clearTimeout(scanDebounceTimer);
                document.getElementById('start-scanner').style.display = 'inline-block';
                document.getElementById('stop-scanner').style.display = 'none';
                html5QrcodeScanner = null;
            }).catch(err => {
                console.error('Error stopping scanner:', err);
                scannerActive = false;
                lastScannedQR = null;
                consecutiveScanCount = 0;
                document.getElementById('start-scanner').style.display = 'inline-block';
                document.getElementById('stop-scanner').style.display = 'none';
                html5QrcodeScanner = null;
            });
        } catch (error) {
            console.error('Error in stopScanner:', error);
            scannerActive = false;
            lastScannedQR = null;
            consecutiveScanCount = 0;
            document.getElementById('start-scanner').style.display = 'inline-block';
            document.getElementById('stop-scanner').style.display = 'none';
        }
    }
}

function onScanSuccess(qrCode) {
    // Smart QR detection: Require consecutive identical scans to prevent false positives
    if (qrCode === lastScannedQR) {
        consecutiveScanCount++;
        
        // Process scan only after threshold of consecutive identical codes
        if (consecutiveScanCount >= CONSECUTIVE_SCAN_THRESHOLD) {
            // Clear debounce and set new one
            if (scanDebounceTimer) clearTimeout(scanDebounceTimer);
            
            // Process the scan
            handleQRScan(qrCode);
            
            // Reset counters and prevent duplicate scans
            lastScannedQR = null;
            consecutiveScanCount = 0;
            
            // Pause scanning briefly to prevent rapid duplicate submissions
            scanDebounceTimer = setTimeout(() => {
                scanDebounceTimer = null;
            }, SCAN_DEBOUNCE_MS);
        }
    } else {
        // Different QR code detected, reset counter
        lastScannedQR = qrCode;
        consecutiveScanCount = 1;
    }
}

function onScanError(errorMessage) {
    // Suppress repeated error logs - only log if it's a new error
    // This prevents spam in the console
}

async function handleQRScan(qrCode) {
    try {
        // Show scanning indicator
        showScanningIndicator(true);
        
        const response = await fetch(`?page=api&endpoint=patrol/scan`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                post_id: currentPostId,
                qr_code: qrCode,
                device_info: navigator.userAgent
            })
        });

        const data = await response.json();

        // Hide scanning indicator
        showScanningIndicator(false);

        if (data.success) {
            // Show success feedback without page reload
            showSuccessMessage('✓ Scan recorded: ' + (data.point?.point_name || 'Point scanned'));
            
            // Update UI in real-time without reload
            updateLastScanDisplay(data.point, data.patrol);
            
            // Refresh patrol status asynchronously
            await updatePatrolStatus();
            
            // Visual feedback
            playSuccessSound();
            animateSuccessIndicator();
        } else {
            showErrorMessage('✗ ' + (data.error || 'Scan failed - Invalid QR code'));
        }
    } catch (error) {
        console.error('Scan submission failed:', error);
        showErrorMessage('✗ Failed to submit scan - Check connection');
        showScanningIndicator(false);
    }
}

function updateLastScanDisplay(point, patrol) {
    // Update last scan info card without page reload
    const lastScanCard = document.getElementById('last-scan-card');
    if (lastScanCard && point) {
        const now = new Date();
        lastScanCard.innerHTML = `
            <div class="flex items-start justify-between mb-3 pb-3 border-b border-gray-200">
                <div>
                    <p class="text-sm font-semibold text-gray-800">${point.point_name || 'Patrol Point'}</p>
                    <p class="text-xs text-gray-500 mt-1">${now.toLocaleTimeString()}</p>
                </div>
                <span class="bg-green-100 text-green-800 px-2 py-1 rounded text-xs font-semibold">Just now</span>
            </div>
            <div class="grid grid-cols-2 gap-2 text-sm">
                <div>
                    <span class="text-gray-600">QR Code:</span>
                    <p class="font-mono text-xs text-gray-800 truncate">${point.qr_code || 'N/A'}</p>
                </div>
                <div>
                    <span class="text-gray-600">Location:</span>
                    <p class="font-semibold text-gray-800">${point.location_description || 'N/A'}</p>
                </div>
            </div>
        `;
    }
}

function showScanningIndicator(show) {
    // Visual feedback while scanning
    const scanBox = document.querySelector('.scanner-box');
    if (scanBox) {
        if (show) {
            scanBox.style.borderColor = '#3b82f6';
            scanBox.style.boxShadow = '0 0 10px rgba(59, 130, 246, 0.5)';
        } else {
            scanBox.style.borderColor = '#e5e7eb';
            scanBox.style.boxShadow = 'none';
        }
    }
}

function playSuccessSound() {
    // Create a simple beep sound for feedback (browser might block autoplay audio)
    try {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        oscillator.frequency.value = 800; // 800 Hz beep
        oscillator.type = 'sine';
        
        gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.1);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.1);
    } catch (e) {
        // Silently fail if audio context is not available
    }
}

function animateSuccessIndicator() {
    // Flash the progress bar green
    const progressFill = document.getElementById('progress-fill');
    if (progressFill) {
        const originalColor = progressFill.style.backgroundColor;
        progressFill.style.backgroundColor = '#10b981';
        progressFill.style.transition = 'background-color 0.2s';
        
        setTimeout(() => {
            progressFill.style.backgroundColor = originalColor;
        }, 300);
    }
}

async function loadPatrolHistory() {
    try {
        const response = await fetch(`?page=api&endpoint=patrol/history&post_id=${currentPostId}&days=7`);
        const data = await response.json();

        if (data.success) {
            const tbody = document.getElementById('patrol-history-body');
            tbody.innerHTML = '';

            data.data.forEach(patrol => {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td>${patrol.patrol_hour}</td>
                    <td>${patrol.score}/8</td>
                    <td><span class="status-badge ${patrol.status.toLowerCase()}">${patrol.status}</span></td>
                    <td>${patrol.completion_percentage}%</td>
                    <td>${patrol.total_scans}</td>
                `;
            });
        }
    } catch (error) {
        console.error('Failed to load patrol history:', error);
    }
}

function showSuccessMessage(message) {
    // Show toast notification without page reload
    const toast = document.createElement('div');
    toast.className = 'fixed top-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50 animate-slideInRight';
    toast.textContent = message;
    toast.style.animation = 'slideInRight 0.3s ease-in-out';
    document.body.appendChild(toast);
    
    // Auto-remove after 3 seconds
    setTimeout(() => {
        toast.style.animation = 'slideOutRight 0.3s ease-in-out';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

function showErrorMessage(message) {
    // Show error toast notification without page reload
    const toast = document.createElement('div');
    toast.className = 'fixed top-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg z-50 animate-slideInRight';
    toast.textContent = message;
    toast.style.animation = 'slideInRight 0.3s ease-in-out';
    document.body.appendChild(toast);
    
    // Auto-remove after 4 seconds
    setTimeout(() => {
        toast.style.animation = 'slideOutRight 0.3s ease-in-out';
        setTimeout(() => toast.remove(), 300);
    }, 4000);
}

// Update current time display
setInterval(function() {
    const now = new Date();
    document.getElementById('current-time').textContent = now.toLocaleTimeString();
}, 1000);
</script>
