<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dasbor Status - API WA Bill</title>
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Inter Font -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <!-- Heroicons -->
    <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script>
    <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script>
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f8fafc; /* slate-50 */
        }
        /* Custom tooltip styling */
        #custom-tooltip {
            transition: opacity 0.2s;
        }
    </style>
</head>
<body class="min-h-screen font-sans text-slate-800 p-4 sm:p-6 lg:p-8">
    <div class="max-w-7xl mx-auto">
        <!-- Header -->
        <header class="mb-8 text-center">
            <h1 class="text-3xl md:text-4xl font-extrabold text-slate-900 mb-2">Dasbor Status API WA Bill</h1>
            <p class="text-lg text-slate-600">
                Pantau kesehatan dan aktivitas sistem secara real-time.
            </p>
        </header>

        <!-- Stat Cards Section -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <!-- Card 1: Overall Status -->
            <div class="bg-white p-6 rounded-xl shadow-md border border-slate-200 flex items-center space-x-4">
                <div id="status-icon-container" class="bg-green-100 text-green-600 p-3 rounded-full">
                    <ion-icon name="checkmark-circle" class="text-3xl"></ion-icon>
                </div>
                <div>
                    <p class="text-sm text-slate-500">Status Sistem</p>
                    <p id="appStatus" class="text-xl font-bold text-slate-800"><%= status %></p>
                </div>
            </div>
            <!-- Card 2: Uptime -->
            <div class="bg-white p-6 rounded-xl shadow-md border border-slate-200 flex items-center space-x-4">
                <div class="bg-sky-100 text-sky-600 p-3 rounded-full">
                    <ion-icon name="pulse-outline" class="text-3xl"></ion-icon>
                </div>
                <div>
                    <p class="text-sm text-slate-500">Uptime (24 Jam)</p>
                    <p id="uptime-percentage" class="text-xl font-bold text-slate-800">Menghitung...</p>
                </div>
            </div>
            <!-- Card 3: API Version -->
            <div class="bg-white p-6 rounded-xl shadow-md border border-slate-200 flex items-center space-x-4">
                <div class="bg-indigo-100 text-indigo-600 p-3 rounded-full">
                    <ion-icon name="git-branch-outline" class="text-3xl"></ion-icon>
                </div>
                <div>
                    <p class="text-sm text-slate-500">Versi Aplikasi</p>
                    <p id="apiVersion" class="text-xl font-bold text-slate-800">v<%= appVersion %></p>
                </div>
            </div>
             <!-- Card 4: Current Date -->
             <div class="bg-white p-6 rounded-xl shadow-md border border-slate-200 flex items-center space-x-4">
                <div class="bg-amber-100 text-amber-600 p-3 rounded-full">
                    <ion-icon name="calendar-outline" class="text-3xl"></ion-icon>
                </div>
                <div>
                    <p class="text-sm text-slate-500">Tanggal</p>
                    <p id="currentDate" class="text-xl font-bold text-slate-800"><%= date %></p>
                </div>
            </div>
        </div>

        <!-- Main Content Grid -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Left Column: Timeline Chart -->
            <div class="lg:col-span-2 bg-white p-6 rounded-xl shadow-md border border-slate-200">
                <h2 class="text-xl font-semibold text-slate-800 mb-4">Linimasa Aktivitas Sistem (24 Jam Terakhir)</h2>
                
                <!-- API Status Row -->
                <div class="mb-6">
                    <h3 class="text-md font-semibold text-slate-700 mb-2">Aktivitas API</h3>
                    <div id="api-chart-container" class="flex flex-wrap gap-0.5 bg-slate-100 p-1 rounded">
                        <!-- Bars for API status will be dynamically added here -->
                    </div>
                </div>
    
                <!-- Sending Invoice Status Row -->
                <div>
                    <h3 class="text-md font-semibold text-slate-700 mb-2">Pengiriman Invoice</h3>
                    <div id="invoice-chart-container" class="flex flex-wrap gap-0.5 bg-slate-100 p-1 rounded">
                        <!-- Bars will be dynamically added here -->
                    </div>
                </div>

                <!-- Legend -->
                <div class="mt-6 flex flex-wrap items-center justify-center gap-x-6 gap-y-2 text-sm text-slate-600">
                    <div class="flex items-center"><div class="w-3 h-3 rounded-full bg-green-500 mr-2"></div><span>Normal</span></div>
                    <div class="flex items-center"><div class="w-3 h-3 rounded-full bg-yellow-500 mr-2"></div><span>Peringatan</span></div>
                    <div class="flex items-center"><div class="w-3 h-3 rounded-full bg-red-500 mr-2"></div><span>Error</span></div>
                    <div class="flex items-center"><div class="w-3 h-3 rounded-full bg-slate-300 mr-2"></div><span>Tidak Ada Data</span></div>
                </div>
            </div>

            <!-- Right Column: Visitor Info & Actions -->
            <div class="space-y-8">
                <!-- Visitor Info Card -->
                <div class="bg-white p-6 rounded-xl shadow-md border border-slate-200">
                    <h2 class="text-xl font-semibold text-slate-900 mb-4 pb-2 border-b border-slate-200 flex items-center">
                        <ion-icon name="finger-print-outline" class="text-2xl mr-3 text-indigo-600"></ion-icon>
                        Informasi Pengunjung
                    </h2>
                    <div class="space-y-4 text-sm">
                        <div class="flex items-start">
                            <ion-icon name="locate-outline" class="text-slate-500 mt-1 mr-3 text-lg"></ion-icon>
                            <div>
                                <p class="font-semibold text-slate-600">IP Address</p>
                                <p id="fpIPAddress" class="text-slate-800 font-mono"><%= ipAddress %></p>
                            </div>
                        </div>
                        <div class="flex items-start">
                            <ion-icon name="browsers-outline" class="text-slate-500 mt-1 mr-3 text-lg"></ion-icon>
                            <div>
                                <p class="font-semibold text-slate-600">Browser</p>
                                <p id="fpBrowser" class="text-slate-800"><%= browsers %></p>
                            </div>
                        </div>
                        <div class="flex items-start">
                            <ion-icon name="laptop-outline" class="text-slate-500 mt-1 mr-3 text-lg"></ion-icon>
                            <div>
                                <p class="font-semibold text-slate-600">Sistem Operasi</p>
                                <p id="fpOS" class="text-slate-800"><%= os %></p>
                            </div>
                        </div>
                    </div>
                    <p class="text-xs text-slate-500 mt-4 text-center">
                        Informasi ini diambil dari header permintaan Anda.
                    </p>
                </div>

                <!-- Actions Card -->
                <div class="bg-white p-6 rounded-xl shadow-md border border-slate-200 text-center">
                     <h2 class="text-xl font-semibold text-slate-900 mb-4 pb-2 border-b border-slate-200 flex items-center justify-center">
                        <ion-icon name="flash-outline" class="text-2xl mr-3 text-indigo-600"></ion-icon>
                        Aksi Cepat
                    </h2>
                    <div class="space-y-3 flex flex-col">
                        <a href="<%= apiDocsUrl %>" target="_blank" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-6 rounded-lg shadow-lg transition duration-300 ease-in-out transform hover:-translate-y-0.5 flex items-center justify-center">
                            <ion-icon name="book-outline" class="text-xl mr-2"></ion-icon>
                            Dokumentasi API
                        </a>
                        <a href="/changelog" target="_blank" class="w-full bg-slate-200 hover:bg-slate-300 text-slate-800 font-bold py-3 px-6 rounded-lg shadow-lg transition duration-300 ease-in-out transform hover:-translate-y-0.5 flex items-center justify-center">
                            <ion-icon name="newspaper-outline" class="text-xl mr-2"></ion-icon>
                            Riwayat Perubahan
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Global tooltip element
        const customTooltip = document.createElement('div');
        customTooltip.id = 'custom-tooltip';
        customTooltip.classList.add(
            'absolute', 'bg-slate-800', 'text-white', 'text-sm', 'p-2',
            'rounded-md', 'shadow-lg', 'z-50', 'hidden', 'pointer-events-none', 'max-w-xs'
        );
        document.body.appendChild(customTooltip);

        function getStatusIcon(level) {
            switch (level) {
                case 'info': return '✅';
                case 'warn': return '⚠️';
                case 'error': return '❌';
                default: return '❔';
            }
        }

        function calculateUptimePercentage(data) {
            if (!data || data.length === 0) return 'N/A';

            const nonErrorCount = data.filter(item => item.status !== 'error').length;
            const percentage = (nonErrorCount / data.length) * 100;
            return `${percentage.toFixed(2)}%`;
        }

        function updateOverallStatus(data) {
            const statusEl = document.getElementById('appStatus');
            const iconContainer = document.getElementById('status-icon-container');
            const icon = iconContainer.querySelector('ion-icon');

            const hasError = data.some(item => item.status === 'error');
            const hasWarn = data.some(item => item.status === 'warn');

            iconContainer.className = 'p-3 rounded-full'; // Reset classes

            if (hasError) {
                statusEl.textContent = 'Error';
                statusEl.classList.add('text-red-600');
                iconContainer.classList.add('bg-red-100', 'text-red-600');
                icon.setAttribute('name', 'close-circle');
            } else if (hasWarn) {
                statusEl.textContent = 'Peringatan';
                statusEl.classList.add('text-yellow-600');
                iconContainer.classList.add('bg-yellow-100', 'text-yellow-600');
                icon.setAttribute('name', 'warning');
            } else {
                statusEl.textContent = 'Normal';
                statusEl.classList.add('text-green-600');
                iconContainer.classList.add('bg-green-100', 'text-green-600');
                icon.setAttribute('name', 'checkmark-circle');
            }
        }

        function showTooltip(event, dataPoint) {
            const intervalStart = new Date(dataPoint.timestamp);
            const intervalEnd = new Date(intervalStart.getTime() + 30 * 60 * 1000);

            const formattedInterval = `${intervalStart.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' })} - ${intervalEnd.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' })}`;

            let detailsHtml = dataPoint.details.map(detail => {
                const detailTime = new Date(detail.timestamp).toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
                return `
                    <div class="flex items-start text-xs">
                        <span class="font-mono text-slate-400 mr-2">${detailTime}</span>
                        <span class="mr-2">${getStatusIcon(detail.level)}</span>
                        <span class="flex-1">${detail.message}</span>
                    </div>
                `;
            }).join('');

            customTooltip.innerHTML = `
                <div class="font-bold mb-1 border-b border-slate-600 pb-1">${formattedInterval}</div>
                <div class="space-y-1 mt-2 max-h-48 overflow-y-auto">${detailsHtml}</div>
            `;
            customTooltip.classList.remove('hidden');
            moveTooltip(event);
        }

        function moveTooltip(event) {
            const tooltipRect = customTooltip.getBoundingClientRect();
            let left = event.clientX + 15;
            let top = event.clientY + 15;

            // Prevent tooltip from going off-screen
            if (left + tooltipRect.width > window.innerWidth) {
                left = event.clientX - tooltipRect.width - 15;
            }
            if (top + tooltipRect.height > window.innerHeight) {
                top = event.clientY - tooltipRect.height - 15;
            }

            customTooltip.style.left = `${left}px`;
            customTooltip.style.top = `${top}px`;
        }

        function hideTooltip() {
            customTooltip.classList.add('hidden');
        }

        function createBar(dataPoint) {
            const bar = document.createElement('div');
            bar.classList.add('w-2', 'h-8', 'rounded-sm', 'cursor-pointer', 'transition-transform', 'duration-150', 'hover:scale-125');

            switch (dataPoint.status) {
                case 'info': bar.classList.add('bg-green-500'); break;
                case 'warn': bar.classList.add('bg-yellow-500'); break;
                case 'error': bar.classList.add('bg-red-500'); break;
                default: bar.classList.add('bg-slate-300');
            }

            bar.addEventListener('mouseover', (event) => showTooltip(event, dataPoint));
            bar.addEventListener('mousemove', (event) => moveTooltip(event));
            bar.addEventListener('mouseout', hideTooltip);

            return bar;
        }

        function renderCategoryChart(containerId, data) {
            const chartContainer = document.getElementById(containerId);
            if (!chartContainer) return;
            chartContainer.innerHTML = '';

            data.forEach(dataPoint => {
                const bar = createBar(dataPoint);
                chartContainer.appendChild(bar);
            });
        }

        document.addEventListener('DOMContentLoaded', () => {
            const apiDataFromController = <%- JSON.stringify(apiData) %>;
            const invoiceDataFromController = <%- JSON.stringify(invoiceData) %>;

            const allData = [...apiDataFromController, ...invoiceDataFromController];

            renderCategoryChart('api-chart-container', apiDataFromController);
            renderCategoryChart('invoice-chart-container', invoiceDataFromController);

            const uptimePercentageElement = document.getElementById('uptime-percentage');
            if (uptimePercentageElement) {
                uptimePercentageElement.textContent = calculateUptimePercentage(allData);
            }

            updateOverallStatus(allData);
        });

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