<?= $this->extend('template/layout') ?>

<?= $this->section('title') ?><?= env('app.name') ?><?= $this->endSection() ?>

<!-- main section start-->
<?= $this->section('main') ?>
<?php
    $uri      = current_url(true);
    $segment1 = $uri->setSilent()->getSegment(1);
    $segment2 = $uri->setSilent()->getSegment(2);
    $segment3 = $uri->setSilent()->getSegment(3);
?>
<!-- Breadcumb -->
<ol class="breadcrumb page-breadcrumb">
    <li class="breadcrumb-item"><a href="javascript:void(0);"><?= env('app.name') ?></a></li>
    <li class="breadcrumb-item">Potensi Wilayah</li>
    <li class="breadcrumb-item">Kurasi Lokasi</li>
    <?php if (!empty($segment3)) { ?>
    <li class="breadcrumb-item active"><?= ucfirst($segment3) ?></li>
	<?php } ?>
    <li class="position-absolute pos-top pos-right d-none d-sm-block"><span class="js-get-date"></span></li>
</ol>

<div class="d-flex flex-grow-1 p-0 shadow-1">
    
    <!-- middle content area -->
    <div class="d-flex flex-column flex-grow-1 bg-white">
        <div class="p-0 p-sm-3">
            <div class="row hidden-lg-up mb-g">
                <div class="col-12">
                    <a href="javascript:void(0);" class="btn btn-default btn-sm btn-block btn-lg waves-effect waves-themed" data-action="toggle" data-class="slide-on-mobile-right-show" data-target="#js-slide-right">
                        Buka Sidebar Lokasi
                    </a>
                </div>
            </div>
            <div class="row">
                <div class="col-12">
                    <div class="panel">
                        <div class="panel-hdr">
                            <h2>Peta Lokasi di Sekitar Kantor</h2>
                            <div class="panel-toolbar">
                                <button type="button" class="btn btn-primary btn-sm" id="btn-reset">
                                    <i class="fal fa-home"></i> Reset Peta
                                </button>
                            </div>
                        </div>
                        <div class="panel-container show">
                            <div class="panel-content p-0">
                                <div id="mapx" style="height: 600px; width: 100%;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- right slider panel : must have unique ID -->
    <div id="js-slide-right" class="flex-wrap flex-shrink-0 position-relative slide-on-mobile slide-on-mobile-right bg-default-200 p-3" style="width: 350px; min-width: 320px;">
        <div class="w-100">
            <h5 class="fw-500 mb-3">Filter Kategori</h5>
            <div class="form-group">
                <select class="form-control" id="kategori-filter">
                    <option value="">Semua Kategori</option>
                    <?php if (!empty($kategori_lokasi)): ?>
                        <?php foreach ($kategori_lokasi as $kategori): ?>
                            <option value="<?= esc($kategori['ket']) ?>" title="Keywords: <?= esc($kategori['ket']) ?>">
                                <?= esc($kategori['nama_kat']) ?>
                            </option>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </select>
                <small class="form-text text-muted">
                    
                </small>
            </div>
            
            <div class="d-flex justify-content-between align-items-center mb-3 mt-4">
                <h5 class="fw-500 mb-0">Lokasi di Sekitar (5km)</h5>
                <div>
                    <button class="btn btn-sm btn-primary" id="btn-search-places">
                        <i class="fal fa-search"></i> Cari
                    </button>
                    <button class="btn btn-sm btn-secondary ml-1" id="btn-search-all" title="Tampilkan semua lokasi tanpa filter">
                        <i class="fal fa-globe"></i>
                    </button>
                </div>
            </div>
            
            <small class="text-muted mb-2 d-block">
                <i class="fal fa-info-circle"></i> 
                Klik untuk fokus lokasi, double-klik untuk detail lokasi, klik kanan untuk merekam data
            </small>
            
            <div id="loading-places" class="text-center p-3" style="display: none;">
                <i class="fal fa-spinner fa-spin"></i> 
                <span id="loading-text">Mencari lokasi...</span>
            </div>
            
            <div id="lokasi-list" class="overflow-auto" style="max-height: 500px;">
                <div class="text-center p-3">
                    <p class="text-muted">Klik tombol "Cari" untuk mencari lokasi di sekitar kantor</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal for Recording Location -->
    <div class="modal fade" id="modalRecordLokasi" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Rekam Data Lokasi</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="form-record-lokasi">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label>Nama Lokasi <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="nama" id="modal-nama" readonly>
                                </div>
                            </div>
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label>Alamat <span class="text-danger">*</span></label>
                                    <textarea class="form-control" name="alamat" id="modal-alamat" rows="2" readonly></textarea>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Kategori <span class="text-danger">*</span></label>
                                    <select class="form-control" name="kategori_id" id="modal-kategori" required>
                                        <option value="">Pilih Kategori</option>
                                        <?php if (!empty($kategori_lokasi)): ?>
                                            <?php foreach ($kategori_lokasi as $kategori): ?>
                                                <option value="<?= $kategori['id'] ?>"><?= esc($kategori['nama_kat']) ?></option>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Rating</label>
                                    <input type="text" class="form-control" name="rating" id="modal-rating" readonly>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Telepon</label>
                                    <input type="text" class="form-control" name="phone" id="modal-phone" readonly>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Website</label>
                                    <input type="text" class="form-control" name="website" id="modal-website" readonly>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" name="latitude" id="modal-latitude">
                        <input type="hidden" name="longitude" id="modal-longitude">
                        <input type="hidden" name="place_id" id="modal-place-id">
                        <input type="hidden" name="id_kantor" id="modal-id-kantor" value="<?= $id_kantor ?>">
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                    <button type="button" class="btn btn-primary" id="btn-save-lokasi">
                        <i class="fal fa-save"></i> Simpan Lokasi
                    </button>
                </div>
            </div>
        </div>
    </div>
    <!-- right slider panel backdrop : activated on mobile, must be place immideately after right slider closing tag -->
    <div class="slide-backdrop" data-action="toggle" data-class="slide-on-mobile-right-show" data-target="#js-slide-right"></div>
</div>

<?= $this->endSection() ?>
<!-- main section end-->

<!-- pageScripts section start-->
<?= $this->section('pageScripts') ?>
<style>
/* Responsive sidebar improvements */
@media (max-width: 991.98px) {
    #js-slide-right {
        position: fixed !important;
        top: 0;
        right: -350px !important;
        height: 100vh;
        z-index: 1050;
        transition: right 0.3s ease-in-out !important;
        width: 320px !important;
        min-width: 320px !important;
        max-width: 90vw !important;
        overflow-y: auto;
        transform: translateX(0) !important;
    }
    
    #js-slide-right.slide-on-mobile-right-show {
        right: 0 !important;
        transform: translateX(0) !important;
    }
    
    .slide-backdrop {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 1040;
        display: none;
    }
    
    .slide-backdrop.show {
        display: block;
    }
    
    .d-flex.flex-row {
        flex-direction: column !important;
    }
    
    .flex-grow-1 {
        width: 100% !important;
    }
}

/* Button styling improvements */
.btn-record-location {
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
}

.btn-record-location:hover {
    transform: scale(1.05);
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?key=<?= $map_api ?>&libraries=places,geometry"></script>
<script>
let map;
let kantorMarker;
let lokasiMarkers = [];
let radiusCircle;
let allPlacesData = [];
let kantorLocation = <?= json_encode($kantor_location ?? null) ?>;
let activeInfoWindow = null; // Track active tooltip
let displayedResults = []; // Track currently displayed results for lazy loading
let resultsPerPage = 20; // Number of results to show per page
let currentPage = 0;

function initMap() {
    // Default center (Indonesia)
    let center = { lat: -6.2088, lng: 106.8456 };
    
    if (kantorLocation && kantorLocation.lati && kantorLocation.longi) {
        center = { 
            lat: parseFloat(kantorLocation.lati), 
            lng: parseFloat(kantorLocation.longi) 
        };
    }

    map = new google.maps.Map(document.getElementById('mapx'), {
        zoom: 13,
        center: center,
        mapTypeId: 'roadmap'
    });

    // Add kantor marker with radius
    if (kantorLocation && kantorLocation.lati && kantorLocation.longi) {
        addKantorMarker();
        addRadius();
    }
    
    // Add double-click event for finding places anywhere on map
    map.addListener('dblclick', function(event) {
        const clickPosition = event.latLng;
        searchNearbyPlaceAtPosition(clickPosition);
    });
    
    // Add right-click event for manual location recording
    map.addListener('rightclick', function(event) {
        const clickPosition = event.latLng;
        searchAndRecordLocation(clickPosition);
    });
}

function addKantorMarker() {
    const kantorPos = {
        lat: parseFloat(kantorLocation.lati),
        lng: parseFloat(kantorLocation.longi)
    };

    kantorMarker = new google.maps.Marker({
        position: kantorPos,
        map: map,
        title: kantorLocation.satker || 'Kantor Anda',
        icon: {
            url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(`
                <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24">
                    <path fill="#DC3545" d="M12 2L2 7v10c0 5.55 3.84 10 9 11 1.09-.21 2.07-.64 3-1.1-.85-1.09-1.38-2.47-1.38-3.99 0-3.53 2.61-6.43 6-6.9V7l-10-5z"/>
                    <path fill="#FFF" d="M16 11v2h-1.5v4.5h-1V13H12v-2h4z"/>
                </svg>
            `),
            scaledSize: new google.maps.Size(32, 32),
            anchor: new google.maps.Point(16, 32)
        }
    });

    const infoWindow = new google.maps.InfoWindow({
        content: `
            <div>
                <h6>${kantorLocation.satker || 'Kantor Anda'}</h6>
                <p>Lokasi kantor Anda</p>
            </div>
        `
    });

    kantorMarker.addListener('click', function() {
        infoWindow.open(map, kantorMarker);
    });
}

function addRadius() {
    const kantorPos = {
        lat: parseFloat(kantorLocation.lati),
        lng: parseFloat(kantorLocation.longi)
    };

    radiusCircle = new google.maps.Circle({
        strokeColor: '#007bff',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#007bff',
        fillOpacity: 0.15,
        map: map,
        center: kantorPos,
        radius: 5000 // 5 km in meters
    });
}

// Calculate distance between two coordinates using Haversine formula
function calculateDistance(lat1, lng1, lat2, lng2) {
    const R = 6371; // Earth radius in kilometers
    const dLat = (lat2 - lat1) * Math.PI / 180;
    const dLng = (lng2 - lng1) * Math.PI / 180;
    const a = 
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
        Math.sin(dLng / 2) * Math.sin(dLng / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return R * c;
}

function searchNearbyPlaces() {
    console.log('searchNearbyPlaces() called');
    
    if (!kantorLocation || !kantorLocation.lati || !kantorLocation.longi) {
        console.error('kantorLocation invalid:', kantorLocation);
        alert('Lokasi kantor tidak ditemukan');
        return;
    }

    if (!map) {
        console.error('Map not ready');
        alert('Map belum siap, silakan tunggu sebentar');
        return;
    }

    if (!google.maps.places) {
        console.error('Places API not loaded');
        alert('Places API belum dimuat, silakan refresh halaman');
        return;
    }

    try {
        const location = new google.maps.LatLng(
            parseFloat(kantorLocation.lati), 
            parseFloat(kantorLocation.longi)
        );
        console.log('Location created:', location.toString());

    const selectedCategory = document.getElementById('kategori-filter').value;
    let searchKeyword = '';
    let searchKeywords = []; // Declare at higher scope
    let searchTypes = [];
    
    // Extract simple keyword from category name (ignore ket field)
    if (selectedCategory) {
        // Get the category name from the dropdown text, not the value
        const categorySelect = document.getElementById('kategori-filter');
        const selectedOption = categorySelect.options[categorySelect.selectedIndex];
        const categoryName = selectedOption.text.toLowerCase();
        
        console.log('Selected category name:', categoryName);
        
        // Multiple keywords for better coverage (Indonesian + English + variations)
        const keywordMapping = {
            'pasar': ['pasar', 'market', 'grocery', 'supermarket'],
            'market': ['market', 'pasar', 'grocery', 'supermarket'], 
            'sekolah': ['sekolah', 'school', 'sd', 'smp', 'sma', 'pendidikan'],
            'school': ['school', 'sekolah', 'education'],
            'universitas': ['universitas', 'university', 'kampus', 'college'],
            'university': ['university', 'universitas', 'college'],
            'kantor': ['kantor', 'office', 'gedung'],
            'office': ['office', 'kantor'],
            'pemerintah': ['pemerintah', 'government', 'dinas', 'kelurahan', 'kecamatan'],
            'government': ['government', 'pemerintah', 'office'],
            'rumah sakit': ['rumah sakit', 'hospital', 'klinik', 'puskesmas'],
            'hospital': ['hospital', 'rumah sakit', 'clinic'],
            'bank': ['bank', 'atm'],
            'atm': ['atm', 'bank'],
            'masjid': ['masjid', 'mosque', 'musholla'],
            'mosque': ['mosque', 'masjid'],
            'gereja': ['gereja', 'church'],
            'church': ['church', 'gereja'],
            'restoran': ['restoran', 'restaurant', 'rumah makan', 'warung'],
            'restaurant': ['restaurant', 'restoran'],
            'hotel': ['hotel', 'penginapan', 'inn'],
            'penginapan': ['penginapan', 'hotel', 'inn'],
            'toko': ['toko', 'store', 'shop', 'warung'],
            'warung': ['warung', 'toko', 'shop']
        };
        
        // Find matching keywords array
        for (const [key, values] of Object.entries(keywordMapping)) {
            if (categoryName.includes(key)) {
                searchKeywords = values; // Now properly scoped
                searchKeyword = values[0]; // Primary keyword
                break;
            }
        }
        
        // Fallback: use first word of category name
        if (!searchKeyword) {
            searchKeyword = categoryName.split(' ')[0];
            searchKeywords = [searchKeyword];
        }
        
        console.log('Search keyword:', searchKeyword);
        console.log('Search keywords array:', searchKeywords);
        console.log('Keywords array length:', searchKeywords.length);
        
        // Optional: Add specific types for better results
        const typeMapping = {
            'pasar': ['grocery_or_supermarket', 'supermarket'],
            'sekolah': ['school', 'primary_school', 'secondary_school'],
            'universitas': ['university'],
            'rumah sakit': ['hospital'],
            'bank': ['bank'],
            'masjid': ['mosque'],
            'gereja': ['church'],
            'restoran': ['restaurant'],
            'hotel': ['lodging'],
            'toko': ['store']
        };
        
        if (typeMapping[searchKeyword]) {
            searchTypes = typeMapping[searchKeyword];
        }
        
        console.log('Search types:', searchTypes);
    }

    document.getElementById('loading-places').style.display = 'block';
    document.getElementById('lokasi-list').innerHTML = '';
    
    // Update loading text based on search type
    const loadingText = document.getElementById('loading-text');
    if (selectedCategory && searchKeyword) {
        loadingText.textContent = `Mencari "${searchKeyword}"...`;
    } else {
        loadingText.textContent = 'Mencari semua lokasi...';
    }

    // Use the legacy PlacesService for better compatibility
    const service = new google.maps.places.PlacesService(map);
    
    let request;
    
    if (selectedCategory && searchKeyword) {
        // Start with broader search - no types, just keyword
        request = {
            location: location,
            radius: 5000,
            keyword: searchKeyword
        };
        
        console.log('Search request:', request);
    } else {
        // Default search for establishments
        request = {
            location: location,
            radius: 5000
        };
        console.log('Search request default:', request);
    }

    console.log('Places API Request:', request);
    
    // Initialize array to collect all results
    let allResults = [];
    let searchCount = 0;
    let completedSearches = 0;
    
    // Function to perform multiple searches with different keywords
    function performMultipleSearches() {
        if (selectedCategory && searchKeywords && searchKeywords.length > 1) {
            // Try multiple keywords for better coverage
            searchCount = Math.min(searchKeywords.length, 3); // Max 3 different keywords
            
            searchKeywords.slice(0, 3).forEach((keyword, index) => {
                setTimeout(() => {
                    const keywordRequest = {
                        location: location,
                        radius: 5000,
                        keyword: keyword
                    };
                    
                    console.log(`Search ${index + 1} with keyword:`, keyword);
                    performSingleSearch(keywordRequest, keyword);
                }, index * 500); // Stagger requests by 500ms
            });
        } else {
            // Single search
            searchCount = 1;
            performSingleSearch(request, searchKeyword);
        }
    }
    
    function performSingleSearch(searchRequest, keyword) {
        service.nearbySearch(searchRequest, function(results, status) {
            console.log(`Places API Response for "${keyword}":`, status, results?.length || 0, 'results');
            
            completedSearches++;
            
            if (status === google.maps.places.PlacesServiceStatus.OK && results && results.length > 0) {
                // Filter for radius and avoid duplicates
                const filteredResults = results.filter(place => {
                    // Check radius
                    if (place.geometry && place.geometry.location) {
                        const distance = calculateDistance(
                            kantorLocation.lati,
                            kantorLocation.longi,
                            place.geometry.location.lat(),
                            place.geometry.location.lng()
                        );
                        
                        if (distance > 5) {
                            return false;
                        }
                    }
                    
                    // Check for duplicates based on place_id
                    return !allResults.some(existing => existing.place_id === place.place_id);
                });
                
                allResults = allResults.concat(filteredResults);
                console.log(`Added ${filteredResults.length} new results. Total: ${allResults.length}`);
            }
            
            // Check if all searches completed
            if (completedSearches >= searchCount) {
                finishSearch();
            }
        });
    }
    
    function finishSearch() {
        document.getElementById('loading-places').style.display = 'none';
        
        if (allResults.length > 0) {
            console.log(`Final total results: ${allResults.length}`);
            
            // Calculate distance for each place and sort by distance
            allResults.forEach(place => {
                if (place.geometry && place.geometry.location) {
                    place.distance = calculateDistance(
                        kantorLocation.lati,
                        kantorLocation.longi,
                        place.geometry.location.lat(),
                        place.geometry.location.lng()
                    );
                }
            });
            
            // Sort by distance (nearest first)
            allResults.sort((a, b) => (a.distance || 0) - (b.distance || 0));
            
            allPlacesData = allResults;
            displayedResults = [];
            currentPage = 0;
            
            displayPlacesWithLazyLoad();
            addPlaceMarkers(allResults);
            
            // Update sidebar header with count
            const sidebarTitle = document.querySelector('#js-slide-right h5');
            if (sidebarTitle && sidebarTitle.textContent.includes('Lokasi di Sekitar')) {
                sidebarTitle.textContent = `Lokasi di Sekitar (${allResults.length} lokasi)`;
            }
        } else {
            let message = 'Tidak ada lokasi ditemukan dalam radius 5km';
            if (selectedCategory && searchKeyword) {
                message = `Tidak ada "${searchKeyword}" ditemukan dalam radius 5km`;
            }
            
            document.getElementById('lokasi-list').innerHTML = 
                '<div class="text-center p-3">' +
                '<p class="text-warning">' + message + '</p>' +
                '<small class="text-muted">Coba kata kunci lain atau klik tombol globe untuk melihat semua lokasi</small>' +
                '</div>';
        }
    }
    
    // Start the searches
    performMultipleSearches();
    
    } catch (error) {
        document.getElementById('loading-places').style.display = 'none';
        console.error('Error in searchNearbyPlaces:', error);
        document.getElementById('lokasi-list').innerHTML = 
            '<div class="text-center p-3"><p class="text-danger">Terjadi kesalahan: ' + error.message + '</p></div>';
    }
}

function displayPlacesInSidebar(places) {
    const lokasiList = document.getElementById('lokasi-list');
    let html = '';

    places.forEach(function(place, index) {
        const distance = calculateDistance(
            kantorLocation.lati,
            kantorLocation.longi,
            place.geometry.location.lat(),
            place.geometry.location.lng()
        );

        html += `
            <div class="card mb-2 lokasi-item" data-index="${index}" style="cursor: pointer;">
                <div class="card-body p-2">
                    <h6 class="card-title mb-1">${place.name}</h6>
                    <p class="card-text small mb-1">
                        <i class="fal fa-map-marker-alt"></i> 
                        ${place.vicinity}
                    </p>
                    <p class="card-text small mb-1">
                        <i class="fal fa-tags"></i> 
                        ${place.types ? place.types[0].replace(/_/g, ' ') : 'establishment'}
                    </p>
                    <div class="d-flex justify-content-between align-items-center">
                        <p class="card-text small text-primary mb-0">
                            <i class="fal fa-route"></i> 
                            ${distance.toFixed(2)} km
                        </p>
                        <div class="d-flex align-items-center">
                            ${place.rating ? `<span class="badge badge-warning mr-2"><i class="fa fa-star"></i> ${place.rating}</span>` : ''}
                            <button class="btn btn-sm btn-success btn-record-location" data-index="${index}" title="Rekam Data Lokasi">
                                <i class="fal fa-save"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });

    lokasiList.innerHTML = html;

    // Add click event listeners to location items
    document.querySelectorAll('.lokasi-item').forEach(function(item) {
        item.addEventListener('click', function() {
            const index = parseInt(this.getAttribute('data-index'));
            const place = allPlacesData[index];
            // Only bounce marker, don't zoom
            const clickedMarker = lokasiMarkers.find(marker => {
                return marker.getPosition().equals(place.geometry.location);
            });
            
            if (clickedMarker) {
                lokasiMarkers.forEach(marker => marker.setAnimation(null));
                clickedMarker.setAnimation(google.maps.Animation.BOUNCE);
                setTimeout(() => clickedMarker.setAnimation(null), 2000);
            }
        });
        
        // Double click to zoom and focus
        item.addEventListener('dblclick', function() {
            const index = parseInt(this.getAttribute('data-index'));
            const place = allPlacesData[index];
            focusOnPlace(place);
        });
    });
    
    // Add event listeners for record buttons
    document.querySelectorAll('.btn-record-location').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.stopPropagation(); // Prevent triggering parent click
            const index = parseInt(this.getAttribute('data-index'));
            const place = allPlacesData[index];
            showRecordModal(place);
        });
    });
}

function addPlaceMarkers(places) {
    // Clear existing markers
    lokasiMarkers.forEach(marker => marker.setMap(null));
    lokasiMarkers = [];

    places.forEach(function(place) {
        const marker = new google.maps.Marker({
            position: place.geometry.location,
            map: map,
            title: place.name,
            icon: {
                url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(`
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                        <path fill="#28A745" d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
                    </svg>
                `),
                scaledSize: new google.maps.Size(24, 24),
                anchor: new google.maps.Point(12, 24)
            }
        });

        // Create info window with save button
        const infoWindow = new google.maps.InfoWindow({
            content: createMarkerInfoContent(place)
        });

        marker.addListener('click', function() {
            // Unified tooltip management - close all tooltips
            closeAllTooltips();
            
            // Open this info window
            infoWindow.open(map, marker);
            activeInfoWindow = infoWindow;
            
            // Bounce marker
            lokasiMarkers.forEach(marker => marker.setAnimation(null));
            marker.setAnimation(google.maps.Animation.BOUNCE);
            setTimeout(() => marker.setAnimation(null), 2000);
            
            // Add event listener for save button after content is loaded
            setTimeout(() => {
                const saveBtn = document.getElementById('marker-save-btn-' + place.place_id);
                if (saveBtn) {
                    saveBtn.addEventListener('click', function() {
                        closeAllTooltips();
                        showRecordModal(place);
                    });
                }
            }, 100);
            
            // Add close listener for unified tooltip management
            infoWindow.addListener('closeclick', function() {
                activeInfoWindow = null;
            });
        });
        
        // Store info window reference
        marker.infoWindow = infoWindow;
        
        marker.addListener('dblclick', function() {
            focusOnPlace(place);
        });

        lokasiMarkers.push(marker);
    });
}

function focusOnPlace(place) {
    // Stop any existing marker bouncing
    lokasiMarkers.forEach(marker => marker.setAnimation(null));
    
    // Find the clicked marker and make it bounce
    const clickedMarker = lokasiMarkers.find(marker => {
        return marker.getPosition().equals(place.geometry.location);
    });
    
    if (clickedMarker) {
        clickedMarker.setAnimation(google.maps.Animation.BOUNCE);
        // Stop bouncing after 2 seconds
        setTimeout(() => clickedMarker.setAnimation(null), 2000);
    }
    
    // Center map on the place
    map.setCenter(place.geometry.location);
    map.setZoom(16);
}

// Display places with lazy loading functionality
function displayPlacesWithLazyLoad() {
    const lokasiList = document.getElementById('lokasi-list');
    
    // Reset displayed results and show first page
    displayedResults = [];
    currentPage = 0;
    lokasiList.innerHTML = '';
    
    loadMoreResults();
}

// Load more results (lazy loading)
function loadMoreResults() {
    const lokasiList = document.getElementById('lokasi-list');
    const startIndex = currentPage * resultsPerPage;
    const endIndex = Math.min(startIndex + resultsPerPage, allPlacesData.length);
    
    if (startIndex >= allPlacesData.length) {
        return; // No more results to load
    }
    
    // Get current page results
    const currentPageResults = allPlacesData.slice(startIndex, endIndex);
    displayedResults = displayedResults.concat(currentPageResults);
    
    // Generate HTML for current page
    let html = '';
    currentPageResults.forEach(function(place, localIndex) {
        const globalIndex = startIndex + localIndex;
        
        html += `
            <div class="card mb-2 lokasi-item" data-index="${globalIndex}" style="cursor: pointer;">
                <div class="card-body p-2">
                    <h6 class="card-title mb-1">${place.name}</h6>
                    <p class="card-text small mb-1">
                        <i class="fal fa-map-marker-alt"></i> 
                        ${place.vicinity}
                    </p>
                    <p class="card-text small mb-1">
                        <i class="fal fa-tags"></i> 
                        ${place.types ? place.types[0].replace(/_/g, ' ') : 'establishment'}
                    </p>
                    <div class="d-flex justify-content-between align-items-center">
                        <p class="card-text small text-primary mb-0">
                            <i class="fal fa-route"></i> 
                            ${place.distance ? place.distance.toFixed(2) : '0.00'} km
                        </p>
                        <div class="d-flex align-items-center">
                            ${place.rating ? `<span class="badge badge-warning mr-2"><i class="fa fa-star"></i> ${place.rating}</span>` : ''}
                            <button class="btn btn-sm btn-success btn-record-location" data-index="${globalIndex}" title="Rekam Data Lokasi">
                                <i class="fal fa-save"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    
    // Append to existing content
    lokasiList.insertAdjacentHTML('beforeend', html);
    
    // Add "Load More" button if there are more results
    if (endIndex < allPlacesData.length) {
        const loadMoreBtn = document.getElementById('load-more-btn');
        if (!loadMoreBtn) {
            const loadMoreHtml = `
                <div class="text-center p-2">
                    <button id="load-more-btn" class="btn btn-outline-primary btn-sm">
                        <i class="fal fa-plus"></i> Tampilkan ${Math.min(resultsPerPage, allPlacesData.length - endIndex)} Lokasi Lagi
                    </button>
                    <p class="small text-muted mt-1">
                        Menampilkan ${endIndex} dari ${allPlacesData.length} lokasi
                    </p>
                </div>
            `;
            lokasiList.insertAdjacentHTML('beforeend', loadMoreHtml);
            
            // Add event listener for load more button
            document.getElementById('load-more-btn').addEventListener('click', function() {
                this.remove(); // Remove button
                currentPage++;
                loadMoreResults();
            });
        }
    } else {
        // Show completion message
        const completionHtml = `
            <div class="text-center p-2 mt-2">
                <p class="small text-muted">
                    <i class="fal fa-check-circle text-success"></i> 
                    Semua ${allPlacesData.length} lokasi telah ditampilkan
                </p>
            </div>
        `;
        lokasiList.insertAdjacentHTML('beforeend', completionHtml);
    }
    
    // Add event listeners to new location items
    const newItems = lokasiList.querySelectorAll('.lokasi-item:not([data-listeners-added])');
    newItems.forEach(function(item) {
        item.setAttribute('data-listeners-added', 'true');
        
        item.addEventListener('click', function() {
            const index = parseInt(this.getAttribute('data-index'));
            const place = allPlacesData[index];
            
            // Only bounce marker, don't zoom
            const clickedMarker = lokasiMarkers.find(marker => {
                return marker.getPosition().equals(place.geometry.location);
            });
            
            if (clickedMarker) {
                lokasiMarkers.forEach(marker => marker.setAnimation(null));
                clickedMarker.setAnimation(google.maps.Animation.BOUNCE);
                setTimeout(() => clickedMarker.setAnimation(null), 2000);
            }
        });
        
        // Double click to zoom and focus
        item.addEventListener('dblclick', function() {
            const index = parseInt(this.getAttribute('data-index'));
            const place = allPlacesData[index];
            focusOnPlace(place);
        });
    });
    
    // Add event listeners for new record buttons
    const newButtons = lokasiList.querySelectorAll('.btn-record-location:not([data-listeners-added])');
    newButtons.forEach(function(btn) {
        btn.setAttribute('data-listeners-added', 'true');
        btn.addEventListener('click', function(e) {
            e.stopPropagation(); // Prevent triggering parent click
            const index = parseInt(this.getAttribute('data-index'));
            const place = allPlacesData[index];
            showRecordModal(place);
        });
    });
}

function closeAllTooltips() {
    // Close the active info window (from double-click or marker click)
    if (activeInfoWindow) {
        activeInfoWindow.close();
        activeInfoWindow = null;
    }
    
    // Close all marker info windows
    lokasiMarkers.forEach(marker => {
        if (marker.infoWindow) {
            marker.infoWindow.close();
        }
    });
}

function searchNearbyPlaceAtPosition(position) {
    console.log('Double-click detected at:', position.toString());
    
    // Close any active info window (unified tooltip management)
    closeAllTooltips();
    
    const service = new google.maps.places.PlacesService(map);
    
    // Try multiple search strategies for better coverage
    const searchStrategies = [
        // Strategy 1: Very small radius (50m) for precise location
        {
            location: position,
            radius: 50,
            rankBy: google.maps.places.RankBy.DISTANCE
        },
        // Strategy 2: Slightly larger radius (100m) for more coverage
        {
            location: position,
            radius: 100,
            rankBy: google.maps.places.RankBy.DISTANCE
        },
        // Strategy 3: Text search in the vicinity
        {
            location: position,
            radius: 75,
            keyword: 'place'
        }
    ];
    
    let searchIndex = 0;
    let foundPlace = false;
    
    function tryNextSearch() {
        if (searchIndex >= searchStrategies.length || foundPlace) {
            if (!foundPlace) {
                console.log('No places found at clicked location after trying all strategies');
                // Don't show anything if no place data found (as per requirement)
            }
            return;
        }
        
        const currentRequest = searchStrategies[searchIndex];
        console.log(`Trying search strategy ${searchIndex + 1}:`, currentRequest);
        
        service.nearbySearch(currentRequest, function(results, status) {
            console.log(`Strategy ${searchIndex + 1} result:`, status, results?.length || 0, 'places found');
            
            if (status === google.maps.places.PlacesServiceStatus.OK && results && results.length > 0) {
                // Found places, use the closest one
                const closestPlace = results[0];
                console.log('Found place:', closestPlace.name);
                foundPlace = true;
                
                // Create and show info window for this place
                const infoWindow = new google.maps.InfoWindow({
                    content: createMapClickInfoContent(closestPlace, position),
                    position: position
                });
                
                infoWindow.open(map);
                activeInfoWindow = infoWindow;
                
                // Add event listener for save button after content is loaded
                setTimeout(() => {
                    const saveBtn = document.getElementById('map-click-save-btn-' + closestPlace.place_id);
                    if (saveBtn) {
                        saveBtn.addEventListener('click', function() {
                            closeAllTooltips();
                            // Create place object compatible with existing modal
                            const placeForModal = {
                                ...closestPlace,
                                geometry: {
                                    location: position
                                }
                            };
                            showRecordModal(placeForModal);
                        });
                    }
                }, 100);
                
                // Add close listener for unified tooltip management
                infoWindow.addListener('closeclick', function() {
                    activeInfoWindow = null;
                });
                
            } else {
                // Try next strategy
                searchIndex++;
                setTimeout(tryNextSearch, 300); // Small delay between attempts
            }
        });
    }
    
    // Start the search process
    tryNextSearch();
}

function searchAndRecordLocation(position) {
    console.log('Right-click detected at:', position.toString());
    
    // Close any active info window (unified tooltip management)
    closeAllTooltips();
    
    const service = new google.maps.places.PlacesService(map);
    
    // Search strategies specifically for recording (broader search)
    const recordingSearchStrategies = [
        // Strategy 1: Small radius for precise location
        {
            location: position,
            radius: 25,
            rankBy: google.maps.places.RankBy.DISTANCE
        },
        // Strategy 2: Medium radius with general keywords
        {
            location: position,
            radius: 100,
            keyword: 'place establishment'
        },
        // Strategy 3: Larger radius for any business/location
        {
            location: position,
            radius: 200,
            type: 'establishment'
        }
    ];
    
    let searchIndex = 0;
    let foundPlace = false;
    
    function tryNextRecordingSearch() {
        if (searchIndex >= recordingSearchStrategies.length) {
            if (!foundPlace) {
                // No place data found, show manual recording option
                showManualRecordingTooltip(position);
            }
            return;
        }
        
        const currentRequest = recordingSearchStrategies[searchIndex];
        console.log(`Trying recording search strategy ${searchIndex + 1}:`, currentRequest);
        
        service.nearbySearch(currentRequest, function(results, status) {
            console.log(`Recording strategy ${searchIndex + 1} result:`, status, results?.length || 0, 'places found');
            
            if (status === google.maps.places.PlacesServiceStatus.OK && results && results.length > 0) {
                // Found places, show recording tooltip with place data
                const closestPlace = results[0];
                console.log('Found place for recording:', closestPlace.name);
                foundPlace = true;
                
                showRecordingTooltip(closestPlace, position);
                
            } else {
                // Try next strategy
                searchIndex++;
                setTimeout(tryNextRecordingSearch, 200); // Faster for recording
            }
        });
    }
    
    // Start the recording search process
    tryNextRecordingSearch();
}

function createMapClickInfoContent(place, position) {
    const distance = calculateDistance(
        kantorLocation.lati,
        kantorLocation.longi,
        position.lat(),
        position.lng()
    );
    
    // Get additional info if available
    const phoneInfo = place.formatted_phone_number || place.international_phone_number || '';
    const websiteInfo = place.website || '';
    
    return `
        <div style="max-width: 320px; padding: 12px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;">
            <h6 style="margin: 0 0 10px 0; color: #2c3e50; font-weight: 600; font-size: 15px; line-height: 1.3;">
                ${place.name || 'Lokasi Tidak Diketahui'}
            </h6>
            
            <div style="margin-bottom: 8px; font-size: 13px; color: #555; line-height: 1.4;">
                <i class="fal fa-map-marker-alt" style="margin-right: 6px; color: #e74c3c; font-size: 12px;"></i>
                <strong>Alamat:</strong> ${place.vicinity || place.formatted_address || 'Alamat tidak tersedia'}
            </div>
            
            <div style="margin-bottom: 8px; font-size: 13px; color: #555;">
                <i class="fal fa-globe" style="margin-right: 6px; color: #3498db; font-size: 12px;"></i>
                <strong>Koordinat:</strong> ${position.lat().toFixed(6)}, ${position.lng().toFixed(6)}
            </div>
            
            ${phoneInfo ? `
                <div style="margin-bottom: 8px; font-size: 13px; color: #555;">
                    <i class="fal fa-phone" style="margin-right: 6px; color: #27ae60; font-size: 12px;"></i>
                    <strong>Kontak:</strong> ${phoneInfo}
                </div>
            ` : ''}
            
            <div style="margin-bottom: 10px; font-size: 13px; color: #2980b9; font-weight: 500;">
                <i class="fal fa-route" style="margin-right: 6px;"></i>
                ${distance.toFixed(2)} km dari kantor
            </div>
            
            ${place.rating ? `
                <div style="margin-bottom: 10px;">
                    <span style="background: #f39c12; color: #fff; padding: 3px 8px; border-radius: 12px; font-size: 12px; font-weight: 500;">
                        <i class="fa fa-star" style="margin-right: 3px;"></i>
                        ${place.rating}
                    </span>
                </div>
            ` : ''}
            
            <div style="margin-bottom: 12px; font-size: 12px; color: #27ae60; font-style: italic; text-align: center; background: #ecf0f1; padding: 4px 8px; border-radius: 4px;">
                <i class="fal fa-mouse-pointer" style="margin-right: 4px;"></i>
                Ditemukan dari double-click
            </div>
            
            <div style="text-align: center; border-top: 1px solid #ecf0f1; padding-top: 10px;">
                <button 
                    id="map-click-save-btn-${place.place_id}" 
                    class="btn btn-success btn-sm" 
                    style="padding: 6px 16px; font-size: 12px; font-weight: 500; border-radius: 6px;"
                >
                    <i class="fal fa-save" style="margin-right: 5px;"></i>
                    Simpan Lokasi
                </button>
            </div>
        </div>
    `;
}

function createMarkerInfoContent(place) {
    const distance = calculateDistance(
        kantorLocation.lati,
        kantorLocation.longi,
        place.geometry.location.lat(),
        place.geometry.location.lng()
    );
    
    // Get additional info if available
    const phoneInfo = place.formatted_phone_number || place.international_phone_number || '';
    const websiteInfo = place.website || '';
    
    return `
        <div style="max-width: 320px; padding: 12px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;">
            <h6 style="margin: 0 0 10px 0; color: #2c3e50; font-weight: 600; font-size: 15px; line-height: 1.3;">
                ${place.name || 'Lokasi Tidak Diketahui'}
            </h6>
            
            <div style="margin-bottom: 8px; font-size: 13px; color: #555; line-height: 1.4;">
                <i class="fal fa-map-marker-alt" style="margin-right: 6px; color: #e74c3c; font-size: 12px;"></i>
                <strong>Alamat:</strong> ${place.vicinity || place.formatted_address || 'Alamat tidak tersedia'}
            </div>
            
            <div style="margin-bottom: 8px; font-size: 13px; color: #555;">
                <i class="fal fa-globe" style="margin-right: 6px; color: #3498db; font-size: 12px;"></i>
                <strong>Koordinat:</strong> ${place.geometry.location.lat().toFixed(6)}, ${place.geometry.location.lng().toFixed(6)}
            </div>
            
            ${phoneInfo ? `
                <div style="margin-bottom: 8px; font-size: 13px; color: #555;">
                    <i class="fal fa-phone" style="margin-right: 6px; color: #27ae60; font-size: 12px;"></i>
                    <strong>Kontak:</strong> ${phoneInfo}
                </div>
            ` : ''}
            
            <div style="margin-bottom: 8px; font-size: 13px; color: #555;">
                <i class="fal fa-tags" style="margin-right: 6px; color: #8e44ad; font-size: 12px;"></i>
                <strong>Tipe:</strong> ${place.types ? place.types[0].replace(/_/g, ' ') : 'establishment'}
            </div>
            
            <div style="margin-bottom: 10px; font-size: 13px; color: #2980b9; font-weight: 500;">
                <i class="fal fa-route" style="margin-right: 6px;"></i>
                ${distance.toFixed(2)} km dari kantor
            </div>
            
            ${place.rating ? `
                <div style="margin-bottom: 10px;">
                    <span style="background: #f39c12; color: #fff; padding: 3px 8px; border-radius: 12px; font-size: 12px; font-weight: 500;">
                        <i class="fa fa-star" style="margin-right: 3px;"></i>
                        ${place.rating}
                    </span>
                </div>
            ` : ''}
            
            <div style="margin-bottom: 12px; font-size: 12px; color: #3498db; font-style: italic; text-align: center; background: #ecf0f1; padding: 4px 8px; border-radius: 4px;">
                <i class="fal fa-search" style="margin-right: 4px;"></i>
                Ditemukan dari pencarian
            </div>
            
            <div style="text-align: center; border-top: 1px solid #ecf0f1; padding-top: 10px;">
                <button 
                    id="marker-save-btn-${place.place_id}" 
                    class="btn btn-primary btn-sm" 
                    style="padding: 6px 16px; font-size: 12px; font-weight: 500; border-radius: 6px;"
                >
                    <i class="fal fa-save" style="margin-right: 5px;"></i>
                    Simpan Lokasi
                </button>
            </div>
        </div>
    `;
}

function showRecordingTooltip(place, position) {
    const infoWindow = new google.maps.InfoWindow({
        content: createRecordingTooltipContent(place, position),
        position: position
    });
    
    infoWindow.open(map);
    activeInfoWindow = infoWindow;
    
    // Add event listener for record button after content is loaded
    setTimeout(() => {
        const recordBtn = document.getElementById('record-tooltip-btn-' + place.place_id);
        if (recordBtn) {
            recordBtn.addEventListener('click', function() {
                closeAllTooltips();
                // Create place object compatible with existing modal
                const placeForModal = {
                    ...place,
                    geometry: {
                        location: position
                    }
                };
                showRecordModal(placeForModal);
            });
        }
    }, 100);
    
    // Add close listener for unified tooltip management
    infoWindow.addListener('closeclick', function() {
        activeInfoWindow = null;
    });
}

function showManualRecordingTooltip(position) {
    const infoWindow = new google.maps.InfoWindow({
        content: createManualRecordingTooltipContent(position),
        position: position
    });
    
    infoWindow.open(map);
    activeInfoWindow = infoWindow;
    
    // Add event listener for manual record button
    setTimeout(() => {
        const manualRecordBtn = document.getElementById('manual-record-btn');
        if (manualRecordBtn) {
            manualRecordBtn.addEventListener('click', function() {
                closeAllTooltips();
                showManualRecordModal(position);
            });
        }
    }, 100);
    
    // Add close listener for unified tooltip management
    infoWindow.addListener('closeclick', function() {
        activeInfoWindow = null;
    });
}

function createRecordingTooltipContent(place, position) {
    const distance = calculateDistance(
        kantorLocation.lati,
        kantorLocation.longi,
        position.lat(),
        position.lng()
    );
    
    return `
        <div style="max-width: 300px; padding: 12px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;">
            <h6 style="margin: 0 0 10px 0; color: #2c3e50; font-weight: 600; font-size: 15px; line-height: 1.3;">
                ${place.name || 'Lokasi Tidak Diketahui'}
            </h6>
            
            <div style="margin-bottom: 8px; font-size: 13px; color: #555; line-height: 1.4;">
                <i class="fal fa-map-marker-alt" style="margin-right: 6px; color: #e74c3c; font-size: 12px;"></i>
                <strong>Alamat:</strong> ${place.vicinity || place.formatted_address || 'Alamat tidak tersedia'}
            </div>
            
            <div style="margin-bottom: 8px; font-size: 13px; color: #555;">
                <i class="fal fa-globe" style="margin-right: 6px; color: #3498db; font-size: 12px;"></i>
                <strong>Koordinat:</strong> ${position.lat().toFixed(6)}, ${position.lng().toFixed(6)}
            </div>
            
            <div style="margin-bottom: 10px; font-size: 13px; color: #2980b9; font-weight: 500;">
                <i class="fal fa-route" style="margin-right: 6px;"></i>
                ${distance.toFixed(2)} km dari kantor
            </div>
            
            ${place.rating ? `
                <div style="margin-bottom: 10px;">
                    <span style="background: #f39c12; color: #fff; padding: 3px 8px; border-radius: 12px; font-size: 12px; font-weight: 500;">
                        <i class="fa fa-star" style="margin-right: 3px;"></i>
                        ${place.rating}
                    </span>
                </div>
            ` : ''}
            
            <div style="margin-bottom: 12px; font-size: 12px; color: #e67e22; font-style: italic; text-align: center; background: #fef9e7; padding: 4px 8px; border-radius: 4px; border: 1px solid #f39c12;">
                <i class="fal fa-hand-pointer" style="margin-right: 4px;"></i>
                Klik kanan untuk merekam lokasi
            </div>
            
            <div style="text-align: center; border-top: 1px solid #ecf0f1; padding-top: 10px;">
                <button 
                    id="record-tooltip-btn-${place.place_id}" 
                    class="btn btn-warning btn-sm" 
                    style="padding: 6px 16px; font-size: 12px; font-weight: 500; border-radius: 6px;"
                >
                    <i class="fal fa-plus-circle" style="margin-right: 5px;"></i>
                    Rekam Lokasi Ini
                </button>
            </div>
        </div>
    `;
}

function createManualRecordingTooltipContent(position) {
    const distance = calculateDistance(
        kantorLocation.lati,
        kantorLocation.longi,
        position.lat(),
        position.lng()
    );
    
    return `
        <div style="max-width: 300px; padding: 12px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;">
            <h6 style="margin: 0 0 10px 0; color: #2c3e50; font-weight: 600; font-size: 15px; line-height: 1.3;">
                <i class="fal fa-map-marker-alt" style="margin-right: 6px; color: #e74c3c;"></i>
                Lokasi Baru
            </h6>
            
            <div style="margin-bottom: 8px; font-size: 13px; color: #555;">
                <i class="fal fa-globe" style="margin-right: 6px; color: #3498db; font-size: 12px;"></i>
                <strong>Koordinat:</strong> ${position.lat().toFixed(6)}, ${position.lng().toFixed(6)}
            </div>
            
            <div style="margin-bottom: 10px; font-size: 13px; color: #2980b9; font-weight: 500;">
                <i class="fal fa-route" style="margin-right: 6px;"></i>
                ${distance.toFixed(2)} km dari kantor
            </div>
            
            <div style="margin-bottom: 12px; font-size: 12px; color: #7f8c8d; font-style: italic; text-align: center; background: #ecf0f1; padding: 6px 8px; border-radius: 4px;">
                <i class="fal fa-info-circle" style="margin-right: 4px;"></i>
                Tidak ada data lokasi terdeteksi.<br>
                Anda dapat merekam secara manual.
            </div>
            
            <div style="text-align: center; border-top: 1px solid #ecf0f1; padding-top: 10px;">
                <button 
                    id="manual-record-btn" 
                    class="btn btn-info btn-sm" 
                    style="padding: 6px 16px; font-size: 12px; font-weight: 500; border-radius: 6px;"
                >
                    <i class="fal fa-edit" style="margin-right: 5px;"></i>
                    Rekam Manual
                </button>
            </div>
        </div>
    `;
}

function showRecordModal(place) {
    // Reset form fields to readonly first (in case previous was manual entry)
    resetModalToReadonly();
    
    // Get place details first for additional information
    const service = new google.maps.places.PlacesService(map);
    service.getDetails({
        placeId: place.place_id,
        fields: ['name', 'formatted_address', 'formatted_phone_number', 'website', 'rating']
    }, function(placeDetails, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
            // Fill modal with place data
            document.getElementById('modal-nama').value = placeDetails.name || place.name || '';
            document.getElementById('modal-alamat').value = placeDetails.formatted_address || place.vicinity || '';
            document.getElementById('modal-rating').value = placeDetails.rating || '';
            document.getElementById('modal-phone').value = placeDetails.formatted_phone_number || '';
            document.getElementById('modal-website').value = placeDetails.website || '';
            document.getElementById('modal-latitude').value = place.geometry.location.lat();
            document.getElementById('modal-longitude').value = place.geometry.location.lng();
            document.getElementById('modal-place-id').value = place.place_id;
            
            // Reset kategori selection
            document.getElementById('modal-kategori').value = '';
            
            // Show modal
            $('#modalRecordLokasi').modal('show');
        } else {
            // Fallback to basic info if details fail
            document.getElementById('modal-nama').value = place.name || '';
            document.getElementById('modal-alamat').value = place.vicinity || '';
            document.getElementById('modal-rating').value = place.rating || '';
            document.getElementById('modal-phone').value = '';
            document.getElementById('modal-website').value = '';
            document.getElementById('modal-latitude').value = place.geometry.location.lat();
            document.getElementById('modal-longitude').value = place.geometry.location.lng();
            document.getElementById('modal-place-id').value = place.place_id;
            
            // Reset kategori selection
            document.getElementById('modal-kategori').value = '';
            
            // Show modal
            $('#modalRecordLokasi').modal('show');
        }
    });
}

function resetModalToReadonly() {
    // Set all fields back to readonly
    document.getElementById('modal-nama').setAttribute('readonly', 'readonly');
    document.getElementById('modal-alamat').setAttribute('readonly', 'readonly');
    document.getElementById('modal-phone').setAttribute('readonly', 'readonly');
    document.getElementById('modal-website').setAttribute('readonly', 'readonly');
    document.getElementById('modal-rating').setAttribute('readonly', 'readonly');
}

function showManualRecordModal(position) {
    // Fill modal with minimal data - user will fill the rest
    document.getElementById('modal-nama').value = '';
    document.getElementById('modal-alamat').value = '';
    document.getElementById('modal-rating').value = '';
    document.getElementById('modal-phone').value = '';
    document.getElementById('modal-website').value = '';
    document.getElementById('modal-latitude').value = position.lat();
    document.getElementById('modal-longitude').value = position.lng();
    document.getElementById('modal-place-id').value = ''; // No place_id for manual entry
    
    // Reset kategori selection
    document.getElementById('modal-kategori').value = '';
    
    // Enable editing for manual entry
    document.getElementById('modal-nama').removeAttribute('readonly');
    document.getElementById('modal-alamat').removeAttribute('readonly');
    document.getElementById('modal-phone').removeAttribute('readonly');
    document.getElementById('modal-website').removeAttribute('readonly');
    document.getElementById('modal-rating').removeAttribute('readonly');
    
    // Show modal
    $('#modalRecordLokasi').modal('show');
    
    // Focus on name field for user convenience
    setTimeout(() => {
        document.getElementById('modal-nama').focus();
    }, 500);
}

// Search places button
document.getElementById('btn-search-places').addEventListener('click', function() {
    console.log('Search button clicked');
    console.log('kantorLocation:', kantorLocation);
    console.log('map:', map);
    console.log('google.maps.places:', google.maps.places);
    searchNearbyPlaces();
});

// Search all button (bypass keyword filtering)
document.getElementById('btn-search-all').addEventListener('click', function() {
    console.log('Search all button clicked');
    // Temporarily clear category selection to get all results
    const categorySelect = document.getElementById('kategori-filter');
    const originalValue = categorySelect.value;
    categorySelect.value = '';
    
    searchNearbyPlaces();
    
    // Restore original category selection but don't apply filter
    setTimeout(() => {
        categorySelect.value = originalValue;
    }, 100);
});

// Category filter functionality
document.getElementById('kategori-filter').addEventListener('change', function() {
    // When category changes, search again with new filter
    if (allPlacesData.length > 0) {
        searchNearbyPlaces();
    }
});

// Reset map button
document.getElementById('btn-reset').addEventListener('click', function() {
    if (kantorLocation && kantorLocation.lati && kantorLocation.longi) {
        map.setCenter({
            lat: parseFloat(kantorLocation.lati),
            lng: parseFloat(kantorLocation.longi)
        });
        map.setZoom(13);
    }
    
    // Clear markers
    lokasiMarkers.forEach(marker => marker.setMap(null));
    lokasiMarkers = [];
    
    // Reset filter and clear results
    document.getElementById('kategori-filter').value = '';
    document.getElementById('lokasi-list').innerHTML = 
        '<div class="text-center p-3"><p class="text-muted">Klik tombol "Cari" untuk mencari lokasi di sekitar kantor</p></div>';
    
    // Reset lazy loading variables
    allPlacesData = [];
    displayedResults = [];
    currentPage = 0;
});

// Save location button
document.getElementById('btn-save-lokasi').addEventListener('click', function() {
    const form = document.getElementById('form-record-lokasi');
    const formData = new FormData(form);
    
    if (!formData.get('kategori_id')) {
        toastr.warning('Silakan pilih kategori terlebih dahulu', 'Peringatan!');
        return;
    }
    
    // Show loading
    this.innerHTML = '<i class="fal fa-spinner fa-spin"></i> Menyimpan...';
    this.disabled = true;
    
    $.ajax({
        url: '<?= base_url('potensiwilayah/kelolalokasi/saveLokasi') ?>',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                toastr.success(response.message, 'Berhasil!', {
                    timeOut: 2000,
                    onHidden: function() {
                        $('#modalRecordLokasi').modal('hide');
                        // Reset form to readonly after successful save
                        resetModalToReadonly();
                        // Optional: refresh data atau update UI
                    }
                });
            }
        },
        error: function(xhr, status, error) {
            try {
                const response = JSON.parse(xhr.responseText);
                if (response.message) {
                    toastr.error(response.message, 'Error!');
                } else {
                    toastr.error('Terjadi kesalahan saat menyimpan data', 'Error!');
                }
            } catch (e) {
                toastr.error('Terjadi kesalahan sistem', 'Error!');
            }
        },
        complete: function() {
            // Reset button
            document.getElementById('btn-save-lokasi').innerHTML = '<i class="fal fa-save"></i> Simpan Lokasi';
            document.getElementById('btn-save-lokasi').disabled = false;
        }
    });
});

// Add modal event listeners
$('#modalRecordLokasi').on('hidden.bs.modal', function() {
    // Reset form to readonly when modal is closed
    resetModalToReadonly();
});

// Initialize map when page loads
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, checking Google Maps API...');
    
    if (typeof google === 'undefined') {
        console.error('Google Maps API not loaded');
        alert('Google Maps API tidak dapat dimuat. Periksa koneksi internet atau API key.');
        return;
    }
    
    if (!google.maps) {
        console.error('google.maps not available');
        return;
    }
    
    if (!google.maps.places) {
        console.error('google.maps.places not available');
        return;
    }
    
    console.log('Google Maps API ready, initializing map...');
    initMap();
    
    // Initialize responsive sidebar behavior
    initResponsiveSidebar();
});

function initResponsiveSidebar() {
    const sidebarPanel = document.getElementById('js-slide-right');
    const backdrop = document.querySelector('.slide-backdrop');
    const openButton = document.querySelector('[data-target="#js-slide-right"]');
    
    // Handle backdrop click to close sidebar
    if (backdrop) {
        backdrop.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            closeSidebar();
        });
    }
    
    // Handle open button click - override existing behavior
    if (openButton) {
        // Remove existing event listeners
        openButton.removeAttribute('data-action');
        openButton.removeAttribute('data-class');
        
        openButton.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            console.log('Open button clicked');
            openSidebar();
        });
    }
    
    // Also handle clicks outside sidebar to close it
    document.addEventListener('click', function(e) {
        if (window.innerWidth <= 991.98) {
            const sidebar = document.getElementById('js-slide-right');
            const isClickInsideSidebar = sidebar.contains(e.target);
            const isOpenButton = openButton && openButton.contains(e.target);
            
            if (!isClickInsideSidebar && !isOpenButton && sidebar.classList.contains('slide-on-mobile-right-show')) {
                closeSidebar();
            }
        }
    });
    
    // Handle window resize
    window.addEventListener('resize', function() {
        if (window.innerWidth > 991.98) {
            // Desktop view - ensure sidebar is visible and backdrop is hidden
            sidebarPanel.classList.remove('slide-on-mobile-right-show');
            if (backdrop) {
                backdrop.classList.remove('show');
            }
        }
    });
    
    // Handle escape key to close sidebar
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && sidebarPanel.classList.contains('slide-on-mobile-right-show')) {
            closeSidebar();
        }
    });
}

function openSidebar() {
    console.log('Opening sidebar...');
    const sidebarPanel = document.getElementById('js-slide-right');
    const backdrop = document.querySelector('.slide-backdrop');
    
    if (sidebarPanel) {
        sidebarPanel.classList.add('slide-on-mobile-right-show');
        console.log('Sidebar class added');
    }
    
    if (backdrop) {
        backdrop.classList.add('show');
        console.log('Backdrop shown');
    }
}

function closeSidebar() {
    const sidebarPanel = document.getElementById('js-slide-right');
    const backdrop = document.querySelector('.slide-backdrop');
    
    sidebarPanel.classList.remove('slide-on-mobile-right-show');
    if (backdrop) {
        backdrop.classList.remove('show');
    }
}
</script>
<?= $this->endSection() ?>
<!-- pageScripts section end-->