<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Detail Koleksi | Pustaka Nawasena</title>
    <link rel="icon" href="{{ asset('images/kartu.png') }}" type="image/png">

    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --lib-navy: #0f172a;
            --lib-gold: #b45309;
            --lib-bg: #f8fafc;
        }

        * { box-sizing: border-box; user-select: none; }

        body { 
            font-family: 'Plus Jakarta Sans', sans-serif; 
            background-image: linear-gradient(rgba(15, 23, 42, 0.85), rgba(15, 23, 42, 0.85)), url("{{ asset('images/utama.jpg') }}"); 
            background-size: cover;
            background-position: center;
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            margin: 0;
        }

        .top-bar {
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(15px);
            border-bottom: 4px solid var(--lib-gold);
            padding: 0.5rem 3rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 90px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            z-index: 100;
        }

        .logo-frame {
            background: white;
            border: 2px solid #e2e8f0;
            padding: 6px 16px;
            border-radius: 16px;
            display: flex;
            align-items: center;
            gap: 12px;
            box-shadow: inset 0 2px 4px rgba(0,0,0,0.05);
            position: relative;
        }

        .img-container { height: 45px; display: flex; align-items: center; }
        .img-container img { height: 100%; width: auto; object-fit: contain; }

        .main-content {
            flex: 1; display: flex; align-items: center; justify-content: center; padding: 2rem;
        }

        .kiosk-card {
            background: white;
            width: 95%;
            max-width: 950px;
            height: 65vh;
            min-height: 480px;
            border-radius: 2.5rem;
            display: grid;
            grid-template-columns: 0.8fr 1.2fr;
            overflow: hidden;
            box-shadow: 0 50px 100px -20px rgba(0, 0, 0, 0.6);
            animation: cardPop 0.5s cubic-bezier(0.17, 0.67, 0.83, 0.67);
        }

        @keyframes cardPop {
            from { opacity: 0; transform: scale(0.9); }
            to { opacity: 1; transform: scale(1); }
        }

        .visual-side {
            background: var(--lib-navy);
            padding: 3rem;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: white;
            text-align: center;
            border-right: 1px solid rgba(255,255,255,0.1);
        }

        .data-side {
            padding: 3.5rem;
            display: flex;
            flex-direction: column;
            background: white;
        }

        .info-row {
            margin-bottom: 1.2rem;
            border-bottom: 1px solid #f1f5f9;
            padding-bottom: 0.8rem;
        }

        .info-label {
            font-size: 10px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.2em;
            color: var(--lib-gold);
            margin-bottom: 5px;
        }

        .info-value {
            font-size: 1.4rem;
            font-weight: 700;
            color: var(--lib-navy);
            line-height: 1.2;
        }

        .btn-action {
            height: 60px;
            border-radius: 1.2rem;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            cursor: pointer;
            width: 100%;
        }

        .btn-confirm { background: var(--lib-navy); color: white; }
        .btn-confirm:hover:not(:disabled) { background: #1e293b; transform: translateY(-3px); }
        .btn-confirm:disabled { opacity: 0.4; cursor: not-allowed; }

        .btn-cancel { background: #f1f5f9; color: #64748b; }
        .btn-cancel:hover { background: #fee2e2; color: #ef4444; }

        .btn-hint {
            font-size: 9px;
            color: #94a3b8;
            margin-top: 8px;
            line-height: 1.4;
            text-align: center;
            font-weight: 500;
        }

        .lib-footer {
            background: rgba(0, 0, 0, 0.9);
            color: rgba(255,255,255,0.4);
            padding: 0.8rem;
            text-align: center;
            font-size: 0.7rem;
            letter-spacing: 2px;
            text-transform: uppercase;
        }
    </style>
</head>
<body>

    <nav class="top-bar">
        <div class="logo-frame">
            <div class="img-container"><img src="{{ asset('images/kartu.png') }}" alt="Logo Kartu"></div>
            <div class="w-[1px] h-8 bg-slate-200"></div>
            <div class="img-container"><img src="{{ asset('images/bakorwil.png') }}" alt="Logo Bakorwil"></div>
            <div class="ml-2 pr-2">
                <h1 class="text-slate-800 font-extrabold text-xl leading-none tracking-tighter uppercase">NAWASENA</h1>
                <p class="text-orange-700 text-[9px] font-bold uppercase tracking-[0.2em] mt-1">Smart Library System</p>
            </div>
        </div>

        <div class="text-right">
            <div id="clock" class="text-4xl font-black text-slate-800 tracking-tighter leading-none">00:00</div>
            <div id="date" class="text-[9px] font-bold text-slate-400 uppercase tracking-widest mt-2">Memuat Kalender...</div>
        </div>
    </nav>

    <main class="main-content">
        <div class="kiosk-card">
            <div class="visual-side">
                <div class="text-7xl mb-6 filter drop-shadow-2xl">📖</div>
                <h2 class="text-2xl font-black mb-2 uppercase tracking-tight leading-tight">Verifikasi<br>Koleksi</h2>
                <div class="w-12 h-1 bg-orange-500 rounded-full mb-6"></div>
                <p class="text-[11px] text-slate-400 leading-relaxed px-8 italic">
                    "Satu buku adalah satu dunia. Pastikan data koleksi sudah sesuai."
                </p>
            </div>

            <div class="data-side">
                <div id="data-container" class="flex-1">
                    <div id="loading-state" class="animate-pulse space-y-8">
                        <div class="h-14 bg-slate-50 rounded-xl"></div>
                        <div class="h-14 bg-slate-50 rounded-xl"></div>
                        <div class="h-14 bg-slate-50 rounded-xl"></div>
                    </div>

                    <div id="book-info" class="hidden">
                        <div class="info-row">
                            <div class="info-label">Judul Koleksi</div>
                            <div id="txt-judul" class="info-value">Memuat...</div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">ID Barcode / ID Buku</div>
                            <div id="txt-barcode" class="info-value text-orange-600">...</div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">Status Verifikasi</div>
                            <div class="flex items-center gap-2 mt-1">
                                <span class="h-2 w-2 rounded-full bg-green-500 animate-pulse"></span>
                                <span class="text-sm font-bold text-green-600 uppercase tracking-widest">Siap Diproses</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="flex gap-6 mt-6 items-start">
                    <div class="flex-1">
                        <button onclick="batal()" class="btn-action btn-cancel">✕ Batal</button>
                        <p class="btn-hint">Hapus sesi dan kembali ke scan.</p>
                    </div>

                    <div class="flex-[1.5]">
                        <button id="btn-lanjut" onclick="lanjut()" class="btn-action btn-confirm" disabled>
                            Lanjutkan ➔
                        </button>
                        <p id="hint-lanjut" class="btn-hint font-bold text-slate-500">Klik untuk mulai identifikasi kartu RFID.</p>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <footer class="lib-footer">
        Bakorwil III Malang &bull; Smart Terminal v4.2.0 &bull; 2026
    </footer>

<script>
// =======================
// 1. CLOCK & UI
// =======================
function updateDateTime() {
            const now = new Date();
            document.getElementById('clock').textContent = now.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });
            document.getElementById('date').textContent = now.toLocaleDateString('id-ID', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
        }

setInterval(updateDateTime, 1000);

// =======================
// STATE CONTROL
// =======================
let isDataLoaded = false;

// =======================
// 2. RENDER DATA
// =======================
function renderData(data = {}) {

    console.log("📦 Render Book Data:", data);

    const loading = document.getElementById('loading-state');
    const info = document.getElementById('book-info');
    const btn = document.getElementById('btn-lanjut');

    if (loading) loading.classList.add('hidden');
    if (info) info.classList.remove('hidden');

    document.getElementById('txt-judul').innerText =
        data.judul || data.title || "Judul tidak tersedia";

    document.getElementById('txt-barcode').innerText =
        data.barcode || data.kode_eksemplar || "-";

    localStorage.setItem('trx_buku', JSON.stringify(data));

    if (btn) {
        btn.disabled = false;
        btn.style.opacity = "1";
    }

    isDataLoaded = true;
}

// =======================
// 3. MQTT CONNECTION
// =======================
const client = mqtt.connect('ws://127.0.0.1:9001', {
    clientId: 'web_detail_' + Math.random().toString(16).substr(2, 8),
    clean: true,
    reconnectPeriod: 2000
});

client.on('connect', () => {
    console.log("✅ MQTT Connected");

    client.subscribe('rfid/ui/detail');
    client.subscribe('rfid/ui/redirect_return');
});

client.on('message', (topic, message) => {
    try {
        const data = JSON.parse(message.toString());

        if (topic === 'rfid/ui/detail') {
            renderData(data);
        }

        if (topic === 'rfid/ui/redirect_return') {
            localStorage.setItem('return_buku', JSON.stringify(data));
            window.location.href = "/transaksi/konfirmasi-kembali";
        }

    } catch (e) {
        console.error("MQTT Parse Error:", e);
    }
});

// =======================
// 4. API STATE (FALLBACK)
// =======================
async function initLoad() {
    if (isDataLoaded) return;

    try {
        const res = await fetch('/api/esp/state');
        const data = await res.json();

        if (data.status === 'ok' && data.book) {
            renderData(data.book);
        }

        if (data.mode === 'return_confirm') {
            window.location.href = "/transaksi/konfirmasi-kembali";
        }

    } catch (err) {
        console.error("Polling error:", err);
    }
}

// polling ringan
const pollingInterval = setInterval(() => {
    if (isDataLoaded) clearInterval(pollingInterval);
    else initLoad();
}, 1500);

// =======================
// 5. ACTION: LANJUT
// =======================
async function lanjut() {

    const btn = document.getElementById('btn-lanjut');
    btn.disabled = true;
    btn.innerHTML = "⏳ MENYIAPKAN SCANNER...";

    try {
        // 🔥 FIX 1: MQTT TOPIC HARUS SAMA DENGAN BACKEND
        client.publish('rfid/mode', 'user');

        // ❌ HAPUS RESET CEPAT (INI YANG BIKIN BUG)
        // await fetch('/api/esp/selesai-transaksi');

        // kasih waktu MQTT nyampe ke ESP
        await new Promise(r => setTimeout(r, 800));

        window.location.href = "/transaksi/scan-rfid";

    } catch (err) {
        console.error(err);
        btn.disabled = false;
        btn.innerHTML = "Lanjutkan ➔";
    }
}

// =======================
// 6. ACTION: BATAL
// =======================
async function batal() {

    if (!confirm("Batalkan transaksi ini?")) return;

    try {
        await fetch('/api/esp/reset'); // lebih aman daripada selesai-transaksi

        localStorage.removeItem('trx_buku');

        window.location.href = "/transaksi/scan-barcode";

    } catch (err) {
        console.error(err);
        window.location.href = "/transaksi/scan-barcode";
    }
}

// =======================
// INIT
// =======================
window.onload = () => {
    updateDateTime();
    initLoad();
};
</script>
</body>
</html>

