<!DOCTYPE html>
<html lang="id">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Tampilan Antrian Loket Pendaftaran</title>
	<link rel="stylesheet" href="<?= base_url('assets/adminlte/plugins/bootstrap/css/bootstrap.min.css'); ?>">
	<link rel="stylesheet" href="<?= base_url('assets/adminlte/plugins/fontawesome-free/css/all.min.css'); ?>">
	<style>
		body {
			margin: 0;
			min-height: 100vh;
			background: radial-gradient(circle at top, #0f2027, #203a43, #2c5364);
			font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
			color: #f0f4f7;
		}

		.loket-display {
			padding: 25px;
			max-width: 1400px;
			margin: 0 auto;
		}

		.display-header {
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			justify-content: space-between;
			gap: 15px;
			margin-bottom: 25px;
			border-bottom: 1px solid rgba(255, 255, 255, 0.15);
			padding-bottom: 15px;
		}

		.display-title h1 {
			font-size: 2.6rem;
			margin: 0;
			font-weight: 800;
			color: #00bcd4;
		}

		.display-title p {
			margin: 0;
			color: #a3b6cc;
			font-size: 1.1rem;
		}

		.display-clock {
			text-align: right;
		}

		.display-clock .time {
			font-size: 2.4rem;
			font-weight: 800;
		}

		.loket-grid {
			display: grid;
			grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
			gap: 20px;
			margin-bottom: 25px;
		}

		.loket-card {
			background: rgba(255, 255, 255, 0.08);
			border-radius: 18px;
			padding: 20px 22px;
			box-shadow: 0 15px 35px rgba(0, 0, 0, 0.35);
			backdrop-filter: blur(4px);
		}

		.loket-card h3 {
			margin: 0;
			font-size: 1.4rem;
			font-weight: 700;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.loket-card h3 span {
			font-size: 0.95rem;
			color: #a3b6cc;
			font-weight: 500;
		}

		.current-number {
			font-size: 4rem;
			font-weight: 900;
			margin: 15px 0 5px;
			color: #ff4757;
			text-shadow: 0 3px 10px rgba(0, 0, 0, 0.6);
		}

		.current-meta {
			color: #c8d9ea;
			font-size: 1rem;
			margin-bottom: 10px;
		}

		.next-label {
			font-size: 0.9rem;
			color: #a3b6cc;
			text-transform: uppercase;
			letter-spacing: 1px;
			margin-bottom: 5px;
		}

		.next-list {
			font-size: 1.2rem;
			font-weight: 600;
			color: #2ed573;
			min-height: 24px;
		}

		.waiting-board {
			background: rgba(0, 0, 0, 0.35);
			border-radius: 20px;
			padding: 25px 30px;
			box-shadow: 0 25px 40px rgba(0, 0, 0, 0.5);
		}

		.waiting-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 15px;
			border-bottom: 1px solid rgba(255, 255, 255, 0.15);
			padding-bottom: 10px;
		}

		.waiting-header h2 {
			margin: 0;
			font-size: 1.8rem;
			font-weight: 700;
		}

		.waiting-header span {
			font-size: 1rem;
			color: #a3b6cc;
		}

		.waiting-row {
			display: grid;
			grid-template-columns: 120px 1fr 160px;
			align-items: center;
			padding: 12px 0;
			border-bottom: 1px solid rgba(255, 255, 255, 0.08);
		}

		.waiting-row:last-child {
			border-bottom: none;
		}

		.waiting-number {
			font-size: 2rem;
			font-weight: 800;
			color: #2196f3;
		}

		.waiting-info {
			font-size: 1.1rem;
		}

		.waiting-time {
			text-align: right;
			color: #a3b6cc;
			font-size: 1rem;
		}

		.empty-state {
			text-align: center;
			color: #8aa6c1;
			padding: 40px 0;
		}

		.empty-state i {
			font-size: 3rem;
			margin-bottom: 10px;
		}

		@media (max-width: 768px) {
			.display-clock {
				text-align: left;
			}

			.waiting-row {
				grid-template-columns: 1fr;
				text-align: center;
				gap: 5px;
			}

			.waiting-time {
				text-align: center;
			}
		}
	</style>
</head>

<body>
	<div class="loket-display">
		<div class="display-header">
			<div class="display-title">
				<h1><i class="fas fa-ticket-alt text-warning mr-2"></i>Loket Pendaftaran Rumah Sakit</h1>
				<p>Tampilan khusus pasien: nomor antrian loket yang sedang dipanggil dan giliran berikutnya.</p>
				<small class="text-muted">Update terakhir: <span id="last-update">-</span></small>
			</div>
			<div class="display-clock">
				<div class="time" id="current-time"><?= date('H:i:s'); ?></div>
				<div id="current-date"><?= date('d F Y'); ?></div>
			</div>
		</div>

		<div class="loket-grid" id="loket-board">
			<!-- Loket cards injected via JS -->
		</div>

		<div class="waiting-board">
			<div class="waiting-header">
				<h2><i class="fas fa-users mr-2"></i>Daftar Tunggu</h2>
				<span id="waiting-count">0 Antrian</span>
			</div>
			<div id="waiting-list">
				<div class="empty-state">
					<i class="fas fa-chair text-warning"></i>
					<p>Tidak ada antrian menunggu saat ini</p>
				</div>
			</div>
		</div>
	</div>

	<script src="<?= base_url('assets/adminlte/plugins/jquery/jquery.min.js'); ?>"></script>
	<script>
		const REFRESH_INTERVAL = 5000;
		const TODAY = '<?= date('Y-m-d'); ?>';
		let refreshTimer = null;
		let loketList = [];

		function updateClock() {
			const now = new Date();
			$('#current-time').text(now.toLocaleTimeString('id-ID', {
				hour: '2-digit',
				minute: '2-digit',
				second: '2-digit'
			}));
			$('#current-date').text(now.toLocaleDateString('id-ID', {
				day: '2-digit',
				month: 'long',
				year: 'numeric'
			}));
		}

		function normalizeLoket(value, fallback = 'LOKET_1') {
			return (value || fallback).toString().trim().toUpperCase();
		}

		function sortByNomor(antrian) {
			return antrian.slice().sort((a, b) => {
				const numA = parseInt(a.nomor_antrian, 10);
				const numB = parseInt(b.nomor_antrian, 10);
				if (isNaN(numA) || isNaN(numB)) {
					return (a.created_at > b.created_at) ? 1 : -1;
				}
				return numA - numB;
			});
		}

		function formatTime(value) {
			if (!value) {
				return '-';
			}
			const date = new Date(value.replace(' ', 'T'));
			return date.toLocaleTimeString('id-ID', {
				hour: '2-digit',
				minute: '2-digit'
			});
		}

		function renderLoketCards(queueData) {
			if (!loketList.length) {
				loketList = [{
					loket: 'LOKET_1'
				}];
			}

			const cards = loketList.map((loketObj, idx) => {
				const code = normalizeLoket(loketObj.loket, `LOKET_${idx + 1}`);
				const perLoket = queueData.filter(item => normalizeLoket(item.loket) === code);

				const current = perLoket.find(item => item.status_antrian === 'DIPANGGIL');
				const waiting = sortByNomor(perLoket.filter(item => item.status_antrian === 'MENUNGGU'));

				const nextPreview = waiting.slice(0, 3).map(item => `#${item.nomor_antrian}`).join(' · ') || '-';
				const currentNumber = current ? `#${current.nomor_antrian}` : '-';
				const lastCallInfo = current ? `Dipanggil ${formatTime(current.waktu_panggil || current.updated_at)}` : 'Menunggu panggilan petugas';

				return `
					<div class="loket-card">
						<h3>${code}<span>${perLoket.length} antrian</span></h3>
						<div class="current-number">${currentNumber}</div>
						<div class="current-meta">${lastCallInfo}</div>
						<div class="next-label">Berikutnya</div>
						<div class="next-list">${nextPreview}</div>
					</div>
				`;
			}).join('');

			$('#loket-board').html(cards);
		}

		function renderWaitingList(queueData) {
			const waiting = sortByNomor(queueData.filter(item => item.status_antrian === 'MENUNGGU'));
			const preview = waiting.slice(0, 8);

			$('#waiting-count').text(`${waiting.length} Antrian`);

			if (!preview.length) {
				$('#waiting-list').html(`
					<div class="empty-state">
						<i class="fas fa-chair text-warning"></i>
						<p>Tidak ada antrian menunggu saat ini</p>
					</div>
				`);
				return;
			}

			const rows = preview.map(item => `
				<div class="waiting-row">
					<div class="waiting-number">#${item.nomor_antrian}</div>
					<div class="waiting-info">Loket: ${normalizeLoket(item.loket)}</div>
					<div class="waiting-time">${formatTime(item.created_at)}</div>
				</div>
			`).join('');

			$('#waiting-list').html(rows);
		}

		function loadLoketList() {
			return $.getJSON('<?= site_url("loket/get_loket_list"); ?>', function(response) {
				if (Array.isArray(response) && response.length) {
					loketList = response.map(item => ({
						loket: normalizeLoket(item.loket)
					}));
				} else {
					loketList = [{
						loket: 'LOKET_1'
					}];
				}
			}).fail(function() {
				loketList = [{
					loket: 'LOKET_1'
				}];
			});
		}

		function loadQueueData() {
			const params = new URLSearchParams({
				loket: 'all',
				status: 'all',
				start_date: TODAY,
				end_date: TODAY
			});

			return $.getJSON('<?= site_url("loket/get_antrian_loket"); ?>?' + params.toString(), function(response) {
				const queueData = Array.isArray(response) ? response : [];
				renderLoketCards(queueData);
				renderWaitingList(queueData);
				$('#last-update').text(new Date().toLocaleTimeString('id-ID'));
			}).fail(function() {
				$('#loket-board').html(`
					<div class="empty-state">
						<i class="fas fa-exclamation-triangle text-warning"></i>
						<p>Gagal memuat data antrian loket</p>
					</div>
				`);
			});
		}

		function startAutoRefresh() {
			if (refreshTimer) {
				clearInterval(refreshTimer);
			}
			refreshTimer = setInterval(function() {
				loadQueueData();
			}, REFRESH_INTERVAL);
		}

		$(document).ready(function() {
			updateClock();
			setInterval(updateClock, 1000);

			loadLoketList().always(function() {
				loadQueueData();
				startAutoRefresh();
			});
		});
	</script>
</body>

</html>
