<?php
$pageTitle = 'Search Contacts';
$activePage = 'search';
include __DIR__ . '/_header.php';
?>

<header class="pwa-header">
    <div class="container-fluid">
        <div class="d-flex align-items-center justify-content-between">
            <h1 class="header-title mb-0">
                <i class="bi bi-search me-2"></i>
                Search Contacts
            </h1>
            <a href="<?php echo URL_PATH; ?>/logout" class="btn-icon" title="Logout">
                <i class="bi bi-box-arrow-right"></i>
            </a>
        </div>
    </div>
</header>

<main class="pwa-content">
    <div class="container-fluid">
        <div class="mb-3">
            <div class="input-group">
                <input type="text" class="form-control" id="searchInput"
                    placeholder="Search by name, phone, designation, village, or notes..."
                    autocomplete="off">
                <button class="btn btn-primary" type="button" id="searchBtn">
                    <i class="bi bi-search"></i>
                </button>
            </div>
            <div id="searchLoading" class="text-center mt-2" style="display: none;">
                <div class="spinner-border spinner-border-sm text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <span class="ms-2 text-muted">Searching...</span>
            </div>
        </div>

        <div id="resultsContainer">
            <div class="empty-state">
                <div class="empty-icon">
                    <i class="bi bi-search"></i>
                </div>
                <h3 class="empty-title">Search Contacts</h3>
                <p class="empty-text">Enter a name, phone number, or notes to search.</p>
            </div>
        </div>
    </div>
</main>

<?php
$additionalJS = <<<'JS'
<script>
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');
    const searchLoading = document.getElementById('searchLoading');
    const resultsContainer = document.getElementById('resultsContainer');
    
    let searchTimeout;
    
    async function performSearch(query) {
        searchLoading.style.display = 'block';
        
        try {
            const url = `${APP_CONFIG.urlPath}/api/search?q=${encodeURIComponent(query)}`;
            console.log('Fetching:', url);
            
            const response = await fetch(url);
            console.log('Response status:', response.status);
            
            const data = await response.json();
            console.log('Response data:', data);
            
            searchLoading.style.display = 'none';
            
            if (data.success) {
                if (data.data && data.data.length > 0) {
                    displayResults(data.data);
                } else {
                    if (query.length === 0) {
                        showEmptyState('No Contacts', 'You have no contacts yet. Add your first contact to get started.');
                    } else {
                        showEmptyState('No Results Found', 'No contacts match your search query.');
                    }
                }
            } else {
                showEmptyState('Error', data.message || 'Failed to load contacts');
            }
        } catch (error) {
            console.error('Search error:', error);
            searchLoading.style.display = 'none';
            showEmptyState('Error', 'Failed to search contacts. Please try again. Check console for details.');
        }
    }
    
    function displayResults(contacts) {
        // Use Bootstrap 5 grid + cards for responsive layout
        const html = `
            <style>
                /* small, page-scoped styles to improve mobile behavior */
                .search-card-avatar { width:56px; height:56px; font-size:20px; }
                @media (max-width:576px) { .search-card-avatar { width:44px; height:44px; font-size:16px; } }
                .pwa-content { padding-bottom: 76px; } /* avoid bottom nav overlap on small screens */
            </style>
            <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
                ${contacts.map(contact => `
                    <div class="col">
                        <div class="card h-100 shadow-sm">
                            <div class="card-body d-flex align-items-start gap-3">
                                <div class="d-flex align-items-center">
                                    <div class="search-card-avatar rounded-circle bg-primary bg-gradient text-white d-flex align-items-center justify-content-center">
                                        ${escapeHtml(contact.full_name.charAt(0).toUpperCase())}
                                    </div>
                                </div>
                                <div class="flex-fill">
                                    <h5 class="card-title mb-1">${escapeHtml(contact.full_name)}</h5>
                                    <p class="mb-1 text-muted small"><i class="bi bi-telephone me-1"></i> ${escapeHtml(contact.contact_number)}</p>
                                    ${contact.designation ? `<p class="mb-1 text-muted small"><i class="bi bi-briefcase me-1"></i> ${escapeHtml(contact.designation)}</p>` : ''}
                                    ${contact.village ? `<p class="mb-1 text-muted small"><i class="bi bi-geo-alt me-1"></i> ${escapeHtml(contact.village)}</p>` : ''}
                                    ${contact.note ? `<p class="mb-0 text-muted small"><i class="bi bi-sticky me-1"></i> ${escapeHtml(contact.note)}</p>` : ''}
                                </div>
                            </div>
                        </div>
                    </div>
                `).join('')}
            </div>
        `;
        resultsContainer.innerHTML = html;

        // Ensure search input remains focused for keyboard users
        searchInput.focus();
    }
    
    function showEmptyState(title, message) {
        const html = `
            <div class="empty-state">
                <div class="empty-icon">
                    <i class="bi bi-search"></i>
                </div>
                <h3 class="empty-title">${title}</h3>
                <p class="empty-text">${message}</p>
            </div>
        `;
        resultsContainer.innerHTML = html;
    }
    
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    searchInput.addEventListener('input', (e) => {
        clearTimeout(searchTimeout);
        const query = e.target.value.trim();
        
        searchTimeout = setTimeout(() => performSearch(query), 500);
    });
    
    searchBtn.addEventListener('click', () => {
        const query = searchInput.value.trim();
        performSearch(query);
    });
    
    searchInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            const query = searchInput.value.trim();
            performSearch(query);
        }
    });
    
    // Load all contacts on page load
    performSearch('');
    
    searchInput.focus();
</script>
JS;

include __DIR__ . '/_footer.php';
?>