<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pemindai & Pencocok RFID & QR Code</title>
    
    <script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js"></script>
    <script src="https://unpkg.com/lucide@latest"></script>

    <style>
        /* --- CSS Variables untuk Tema --- */
        :root {
            --bg-color: #f4f7f6;
            --card-bg: #ffffff;
            --text-color: #333333;
            --label-color: #555555;
            --border-color: #e0e0e0;
            --primary-color: #007bff;
            --success-color: #28a745;
            --error-color: #dc3545;
            --shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
            --transition: all 0.3s ease;
        }

        [data-theme="dark"] {
            --bg-color: #121212;
            --card-bg: #1e1e1e;
            --text-color: #e0e0e0;
            --label-color: #a0a0a0;
            --border-color: #333333;
            --primary-color: #4a9eff;
            --shadow: 0 4px 15px rgba(0, 0, 0, 0.4);
        }

        /* --- Gaya Umum --- */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: var(--bg-color);
            color: var(--text-color);
            transition: var(--transition);
        }

        .container {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }

        header {
            background-color: var(--card-bg);
            padding: 20px;
            text-align: center;
            border-bottom: 1px solid var(--border-color);
            box-shadow: var(--shadow);
        }

        h1 {
            font-size: 1.8rem;
            font-weight: 700;
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            flex: 1;
            gap: 20px;
            padding: 20px;
        }

        .scanner-column {
            background-color: var(--card-bg);
            border-radius: 15px;
            padding: 25px;
            box-shadow: var(--shadow);
            display: flex;
            flex-direction: column;
        }

        .column-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
            font-size: 1.3rem;
            font-weight: 600;
            color: var(--label-color);
        }

        .scan-input-area {
            margin-bottom: 20px;
        }

        #rfid-input {
            width: 100%;
            padding: 15px;
            font-size: 1.1rem;
            font-family: 'Courier New', Courier, monospace;
            text-align: center;
            border-radius: 10px;
            border: 2px dashed var(--border-color);
            background-color: var(--bg-color);
            color: var(--text-color);
            transition: var(--transition);
        }
        #rfid-input:focus {
            outline: none;
            border-color: var(--primary-color);
        }

        .camera-container {
            position: relative;
            width: 100%;
            aspect-ratio: 4/3;
            border-radius: 10px;
            overflow: hidden;
            background-color: #000;
            margin-bottom: 20px;
        }

        #camera-video, #camera-canvas {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        #camera-canvas {
            display: none;
        }
        
        .scan-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            display: none;
        }
        .scan-line {
            position: absolute;
            width: 100%;
            height: 2px;
            background: linear-gradient(to right, transparent, var(--primary-color), transparent);
            animation: scan 2s linear infinite;
        }
        @keyframes scan {
            0% { top: 0; }
            100% { top: 100%; }
        }

        .scan-list {
            flex: 1;
            overflow-y: auto;
            border: 1px solid var(--border-color);
            border-radius: 10px;
            padding: 10px;
            background-color: var(--bg-color);
        }

        .scan-list-item {
            padding: 12px 15px;
            margin-bottom: 8px;
            background-color: var(--card-bg);
            border-radius: 8px;
            border-left: 4px solid transparent;
            transition: var(--transition);
            cursor: default;
            display: flex;
            justify-content: space-between;
            align-items: center;
            animation: fadeIn 0.4s ease;
        }
        
        .scan-list-item:last-child {
            margin-bottom: 0;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .scan-list-item.matched {
            border-left-color: var(--success-color);
            background-color: rgba(40, 167, 69, 0.15);
            box-shadow: 0 0 10px rgba(40, 167, 69, 0.3);
            animation: pulse 0.6s ease;
        }

        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.03); }
            100% { transform: scale(1); }
        }

        .scan-list-item .data {
            font-weight: 500;
            word-break: break-all;
        }

        .scan-list-item .timestamp {
            font-size: 0.75rem;
            color: var(--label-color);
            white-space: nowrap;
            margin-left: 10px;
        }

        .controls {
            margin-top: 20px;
            display: flex;
            gap: 10px;
        }

        .btn {
            flex: 1;
            padding: 12px 15px;
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: var(--transition);
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }
        .btn-primary:hover {
            opacity: 0.9;
        }
        .btn-danger {
            background-color: var(--error-color);
            color: white;
        }

        .status-bar {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 15px;
            text-align: center;
            font-weight: 600;
            transform: translateY(100%);
            transition: transform 0.4s ease;
            z-index: 1000;
        }
        .status-bar.show {
            transform: translateY(0);
        }
        .status-bar.success {
            background-color: var(--success-color);
            color: white;
        }
        .status-bar.error {
            background-color: var(--error-color);
            color: white;
        }
        .status-bar.info {
            background-color: var(--primary-color);
            color: white;
        }

        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>

    <div class="container">
        <header>
            <h1>🚀 Pemindai & Pencocok RFID & QR Code</h1>
        </header>

        <main class="main-content">
            <!-- Kolom Kiri: Pemindai RFID -->
            <section class="scanner-column">
                <div class="column-header">
                    <i data-lucide="credit-card"></i>
                    <span>Scan RFID</span>
                </div>
                
                <div class="scan-input-area">
                    <input type="text" id="rfid-input" placeholder="Tempelkan kartu RFID di sini..." autocomplete="off">
                </div>

                <div class="scan-list" id="rfid-list">
                    <!-- Item RFID akan ditambahkan di sini -->
                </div>

                <div class="controls">
                    <button id="clear-rfid-btn" class="btn btn-danger">
                        <i data-lucide="trash-2"></i> Hapus Semua
                    </button>
                </div>
            </section>

            <!-- Kolom Kanan: Pemindai QR Code -->
            <section class="scanner-column">
                <div class="column-header">
                    <i data-lucide="camera"></i>
                    <span>Scan QR Code</span>
                </div>
                
                <div class="camera-container">
                    <video id="camera-video"></video>
                    <canvas id="camera-canvas"></canvas>
                    <div class="scan-overlay" id="scan-overlay">
                        <div class="scan-line"></div>
                    </div>
                </div>

                <div class="scan-list" id="qr-list">
                    <!-- Item QR akan ditambahkan di sini -->
                </div>

                <div class="controls">
                    <button id="start-scan-btn" class="btn btn-primary">
                        <i data-lucide="scan-line"></i> Aktifkan Kamera
                    </button>
                    <button id="clear-qr-btn" class="btn btn-danger">
                        <i data-lucide="trash-2"></i> Hapus Semua
                    </button>
                </div>
            </section>
        </main>
    </div>

    <!-- Status Bar untuk Notifikasi -->
    <div id="status-bar" class="status-bar"></div>

    <script>
        // Inisialisasi Lucide Icons
        lucide.createIcons();

        // --- ELEMEN DOM ---
        // RFID
        const rfidInput = document.getElementById('rfid-input');
        const rfidList = document.getElementById('rfid-list');
        const clearRfidBtn = document.getElementById('clear-rfid-btn');
        
        // QR
        const videoElement = document.getElementById('camera-video');
        const canvasElement = document.getElementById('camera-canvas');
        const startScanBtn = document.getElementById('start-scan-btn');
        const scanOverlay = document.getElementById('scan-overlay');
        const qrList = document.getElementById('qr-list');
        const clearQrBtn = document.getElementById('clear-qr-btn');

        // Status
        const statusBar = document.getElementById('status-bar');

        // --- VARIABEL GLOBAL ---
        let stream = null;
        let isScanning = false;
        let scanInterval = null;
        let scannedRfidData = [];
        let scannedQrData = [];
        let lastScannedCode = null;
        let scanCooldown = false;

        // --- FUNGSI UTILITAS ---
        const showStatus = (message, type = 'info', duration = 3000) => {
            statusBar.textContent = message;
            statusBar.className = `status-bar ${type} show`;
            setTimeout(() => {
                statusBar.classList.remove('show');
            }, duration);
        };

        const formatTime = () => {
            return new Date().toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
        };

        // --- LOGIKA UTAMA: TAMBAH DATA & CEK COCOKAN ---
        const addDataAndCheckMatch = (data, listElement, dataArray, otherListElement, otherDataArray) => {
            // Cegah duplikat di daftar sendiri
            if (dataArray.includes(data)) {
                showStatus(`Data "${data}" sudah ada.`, 'info');
                return;
            }

            // Tambahkan ke array data
            dataArray.push(data);

            // Buat elemen list baru
            const listItem = document.createElement('div');
            listItem.className = 'scan-list-item';
            listItem.dataset.value = data;
            
            listItem.innerHTML = `
                <span class="data">${data}</span>
                <span class="timestamp">${formatTime()}</span>
            `;
            
            listElement.prepend(listItem);

            // Cek kecocokan dengan daftar di kolom lain
            const matchIndex = otherDataArray.indexOf(data);
            if (matchIndex !== -1) {
                // Jika cocok, sorot kedua item
                listItem.classList.add('matched');
                const matchedItem = otherListElement.querySelector(`[data-value="${data}"]`);
                if (matchedItem) {
                    matchedItem.classList.add('matched');
                }
                showStatus(`✅ KECOCOKAN DITEMUKAN: ${data}`, 'success');
            } else {
                // Jika tidak cocok, beri tahu bahwa data baru ditambahkan
                const source = listElement.id === 'rfid-list' ? 'RFID' : 'QR';
                showStatus(`🆕 Data ${source} baru ditambahkan.`, 'info');
            }
        };

        // --- EVENT LISTENER PEMINDAI RFID ---
        rfidInput.addEventListener('keydown', (event) => {
            if (event.key === 'Enter') {
                event.preventDefault();
                const scannedData = rfidInput.value.trim();
                if (scannedData) {
                    addDataAndCheckMatch(scannedData, rfidList, scannedRfidData, qrList, scannedQrData);
                    rfidInput.value = ''; // Kosongkan input
                }
            }
        });

        clearRfidBtn.addEventListener('click', () => {
            scannedRfidData = [];
            rfidList.innerHTML = '';
            // Hapus highlight yang cocok di daftar QR
            qrList.querySelectorAll('.matched').forEach(item => item.classList.remove('matched'));
            showStatus('Daftar RFID dihapus.', 'info');
        });

        // --- EVENT LISTENER PEMINDAI QR ---
        const startScan = async () => {
            if (isScanning) {
                stopScan();
                return;
            }
            if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                showStatus('❌ Browser tidak mendukung kamera.', 'error');
                return;
            }
            try {
                stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" }, audio: false });
                videoElement.srcObject = stream;
                videoElement.play();
                videoElement.onloadedmetadata = () => {
                    isScanning = true;
                    scanOverlay.style.display = 'block';
                    startScanBtn.innerHTML = '<i data-lucide="stop-circle"></i> Nonaktifkan';
                    canvasElement.width = videoElement.videoWidth;
                    canvasElement.height = videoElement.videoHeight;
                    scanInterval = setInterval(scanQRCode, 150);
                };
            } catch (e) {
                console.error("Kesalahan Akses Kamera:", e);
                let errorMsg = '🚫 Gagal mengakses kamera.';
                if (e.name === 'NotAllowedError') errorMsg = '🚨 Izin kamera ditolak.';
                else if (e.name === 'NotReadableError') errorMsg = '🛑 Kamera sedang digunakan.';
                else if (e.name === 'SecurityError' && location.protocol !== 'https:') errorMsg = '🔒 Butuh koneksi HTTPS.';
                showStatus(errorMsg, 'error');
            }
        };

        const stopScan = () => {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
                stream = null;
            }
            isScanning = false;
            scanOverlay.style.display = 'none';
            startScanBtn.innerHTML = '<i data-lucide="scan-line"></i> Aktifkan Kamera';
            if (scanInterval) {
                clearInterval(scanInterval);
                scanInterval = null;
            }
        };

        function scanQRCode() {
            if (!isScanning || videoElement.paused || videoElement.ended || scanCooldown) return;
            
            const canvasContext = canvasElement.getContext('2d');
            canvasContext.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
            const imageData = canvasContext.getImageData(0, 0, canvasElement.width, canvasElement.height);
            const code = jsQR(imageData.data, imageData.width, imageData.height);
            
            if (code && code.data !== lastScannedCode) {
                const scannedData = code.data;
                addDataAndCheckMatch(scannedData, qrList, scannedQrData, rfidList, scannedRfidData);
                lastScannedCode = scannedData;
                scanCooldown = true;
                setTimeout(() => { scanCooldown = false; }, 2000);
            }
        }

        startScanBtn.addEventListener('click', startScan);
        clearQrBtn.addEventListener('click', () => {
            scannedQrData = [];
            qrList.innerHTML = '';
            // Hapus highlight yang cocok di daftar RFID
            rfidList.querySelectorAll('.matched').forEach(item => item.classList.remove('matched'));
            showStatus('Daftar QR dihapus.', 'info');
        });

        // --- INISIALISASI AWAL ---
        window.addEventListener('load', () => {
            setTimeout(() => rfidInput.focus(), 100);
            lucide.createIcons();
        });
    </script>
</body>
</html>