<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Autocomplete Nomor Perkara</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <style>
        .autocomplete-container {
            position: relative;
        }
        .autocomplete-suggestions {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #ddd;
            border-top: none;
            border-radius: 0 0 4px 4px;
            max-height: 300px;
            overflow-y: auto;
            z-index: 1000;
            display: none;
        }
        .autocomplete-suggestion {
            padding: 10px 15px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
        }
        .autocomplete-suggestion:hover {
            background-color: #f8f9fa;
        }
        .autocomplete-suggestion:last-child {
            border-bottom: none;
        }
        .suggestion-main {
            font-weight: 600;
            color: #212529;
        }
        .suggestion-detail {
            font-size: 0.85em;
            color: #6c757d;
            margin-top: 2px;
        }
        .loading {
            padding: 10px 15px;
            text-align: center;
            color: #6c757d;
        }
        .no-results {
            padding: 10px 15px;
            text-align: center;
            color: #6c757d;
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0"><i class="fa fa-search me-2"></i>Test Autocomplete Nomor Perkara</h5>
                    </div>
                    <div class="card-body">
                        <form>
                            <div class="mb-3">
                                <label for="nomor_perkara" class="form-label">Nomor Perkara <span class="text-danger">*</span></label>
                                <div class="autocomplete-container">
                                    <input type="text" class="form-control" id="nomor_perkara" name="nomor_perkara" 
                                           placeholder="contoh: 123/Pid.B/2025/PN.Wtp" autocomplete="off">
                                    <div class="autocomplete-suggestions" id="suggestions"></div>
                                </div>
                                <div class="form-text">Ketik minimal 2 karakter untuk mencari nomor perkara</div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Hasil Pilihan:</label>
                                <div id="selected-info" class="alert alert-info" style="display: none;">
                                    <strong>Nomor Perkara:</strong> <span id="selected-nomor"></span><br>
                                    <strong>Lokasi Arsip:</strong> <span id="selected-lokasi"></span>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        class NomorPerkaraAutocomplete {
            constructor(inputId, suggestionsId) {
                this.input = document.getElementById(inputId);
                this.suggestions = document.getElementById(suggestionsId);
                this.currentIndex = -1;
                this.searchTimeout = null;
                
                this.bindEvents();
            }
            
            bindEvents() {
                this.input.addEventListener('input', (e) => {
                    this.handleInput(e.target.value);
                });
                
                this.input.addEventListener('keydown', (e) => {
                    this.handleKeydown(e);
                });
                
                this.input.addEventListener('blur', () => {
                    // Delay hiding to allow click events on suggestions
                    setTimeout(() => this.hideSuggestions(), 200);
                });
                
                document.addEventListener('click', (e) => {
                    if (!e.target.closest('.autocomplete-container')) {
                        this.hideSuggestions();
                    }
                });
            }
            
            handleInput(value) {
                clearTimeout(this.searchTimeout);
                
                if (value.length < 2) {
                    this.hideSuggestions();
                    return;
                }
                
                this.searchTimeout = setTimeout(() => {
                    this.search(value);
                }, 300); // Debounce 300ms
            }
            
            handleKeydown(e) {
                const items = this.suggestions.querySelectorAll('.autocomplete-suggestion');
                
                switch(e.key) {
                    case 'ArrowDown':
                        e.preventDefault();
                        this.currentIndex = Math.min(this.currentIndex + 1, items.length - 1);
                        this.updateSelection(items);
                        break;
                        
                    case 'ArrowUp':
                        e.preventDefault();
                        this.currentIndex = Math.max(this.currentIndex - 1, -1);
                        this.updateSelection(items);
                        break;
                        
                    case 'Enter':
                        e.preventDefault();
                        if (this.currentIndex >= 0 && items[this.currentIndex]) {
                            this.selectSuggestion(items[this.currentIndex]);
                        }
                        break;
                        
                    case 'Escape':
                        this.hideSuggestions();
                        break;
                }
            }
            
            updateSelection(items) {
                items.forEach((item, index) => {
                    item.classList.toggle('bg-light', index === this.currentIndex);
                });
            }
            
            async search(query) {
                this.showLoading();
                
                try {
                    const response = await fetch(`api/search-nomor-perkara.php?q=${encodeURIComponent(query)}`);
                    
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    
                    const data = await response.json();
                    this.displaySuggestions(data);
                    
                } catch (error) {
                    console.error('Search error:', error);
                    this.showError();
                }
            }
            
            showLoading() {
                this.suggestions.innerHTML = '<div class="loading"><i class="fa fa-spinner fa-spin"></i> Mencari...</div>';
                this.suggestions.style.display = 'block';
            }
            
            showError() {
                this.suggestions.innerHTML = '<div class="no-results">Terjadi kesalahan saat mencari data</div>';
                this.suggestions.style.display = 'block';
            }
            
            displaySuggestions(data) {
                this.currentIndex = -1;
                
                if (data.length === 0) {
                    this.suggestions.innerHTML = '<div class="no-results">Tidak ada nomor perkara yang cocok</div>';
                    this.suggestions.style.display = 'block';
                    return;
                }
                
                const html = data.map(item => {
                    const lokasi = `Ruang ${item.no_ruang || '-'}, Lemari ${item.no_lemari || '-'}, Rak ${item.no_rak || '-'}, Berkas ${item.no_berkas || '-'}`;
                    
                    return `
                        <div class="autocomplete-suggestion" data-nomor="${item.nomor_perkara}" data-lokasi="${lokasi}">
                            <div class="suggestion-main">${item.nomor_perkara}</div>
                            <div class="suggestion-detail">Arsip: ${item.nomor_arsip || '-'} | ${lokasi}</div>
                        </div>
                    `;
                }).join('');
                
                this.suggestions.innerHTML = html;
                this.suggestions.style.display = 'block';
                
                // Add click events
                this.suggestions.querySelectorAll('.autocomplete-suggestion').forEach(item => {
                    item.addEventListener('click', () => this.selectSuggestion(item));
                });
            }
            
            selectSuggestion(item) {
                const nomor = item.dataset.nomor;
                const lokasi = item.dataset.lokasi;
                
                this.input.value = nomor;
                this.hideSuggestions();
                
                // Show selected info
                document.getElementById('selected-nomor').textContent = nomor;
                document.getElementById('selected-lokasi').textContent = lokasi;
                document.getElementById('selected-info').style.display = 'block';
                
                // Trigger change event
                this.input.dispatchEvent(new Event('change'));
            }
            
            hideSuggestions() {
                this.suggestions.style.display = 'none';
                this.currentIndex = -1;
            }
        }
        
        // Initialize autocomplete when page loads
        document.addEventListener('DOMContentLoaded', function() {
            new NomorPerkaraAutocomplete('nomor_perkara', 'suggestions');
        });
    </script>
</body>
</html>
