<?= $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">Pesaing</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 Pesaing 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">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="fw-500 mb-0">Lokasi Pesaing di Sekitar (5km)</h5>
                <div>
                    <button class="btn btn-sm btn-primary" id="btn-search-places">
                        <i class="fal fa-search"></i> Cari
                    </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 pesaing...</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 pesaing 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 Pesaing</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 Pesaing <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>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-12">
                                <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 = 50; // Number of results to show per page - increased for better user experience
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());

        document.getElementById('loading-places').style.display = 'block';
        document.getElementById('lokasi-list').innerHTML = '';
        
        // Update loading text
        const loadingText = document.getElementById('loading-text');
        loadingText.textContent = 'Mencari lokasi pesaing...';

        // Use the legacy PlacesService for better compatibility
        const service = new google.maps.places.PlacesService(map);
        
        // Search for competitor categories (financial institutions, banks, etc.)
        const competitorTypes = [
            'bank', 'atm', 'jewelry_store', 'finance', 'insurance_agency', 
            'money_transfer', 'pawn_shop', 'store', 'establishment'
        ];
        
        const competitorKeywords = [
            // Banking & Finance
            'bank', 'bpr', 'bri', 'bni', 'bca', 'mandiri', 'btn', 'danamon', 'cimb', 'permata',
            'koperasi', 'kredit', 'simpan', 'pinjam', 'tabungan', 'deposito', 'keuangan', 'finance',
            'leasing', 'multifinance', 'adira', 'baf', 'oto', 'astra credit',
            
            // Pawn & Gold
            'gadai', 'emas', 'perhiasan', 'gold', 'jewelry', 'pawn', 'buyback', 
            'logam mulia', 'antam', 'ubs', 'galeri 24', 'semar nusantara',
            
            // Insurance & Investment
            'asuransi', 'insurance', 'prudential', 'allianz', 'axa', 'zurich', 'sinarmas',
            'investasi', 'sekuritas', 'saham', 'reksadana', 'obligasi',
            
            // Money Transfer & Payment
            'money changer', 'transfer', 'remittance', 'western union', 'moneygram',
            'payment', 'fintech', 'e-money', 'gopay', 'ovo', 'dana', 'linkaja',
            
            // Microfinance
            'mikro', 'umkm', 'modal', 'usaha', 'pinjaman online', 'peer to peer',
            'amartha', 'modalku', 'investree', 'funding'
        ];
        
        let allResults = [];
        let completedSearches = 0;
        const totalSearches = competitorTypes.length + competitorKeywords.length + 1; // +1 for general search
        
        // Function to handle search completion
        function handleSearchComplete() {
            completedSearches++;
            console.log(`Search completed: ${completedSearches}/${totalSearches}, current results: ${allResults.length}`);
            
            if (completedSearches >= totalSearches) {
                console.log('All searches completed, processing results...');
                
                // Remove duplicates based on place_id
                const uniqueResults = allResults.filter((place, index, self) => 
                    index === self.findIndex(p => p.place_id === place.place_id)
                );
                console.log(`After deduplication: ${uniqueResults.length} places`);
                
                // Filter out PT Pegadaian and its branches
                const filteredResults = uniqueResults.filter(place => {
                    const name = place.name ? place.name.toLowerCase() : '';
                    const vicinity = place.vicinity ? place.vicinity.toLowerCase() : '';
                    
                    return !(
                        name.includes('pegadaian') || 
                        name.includes('pt pegadaian') ||
                        name.includes('pt. pegadaian') ||
                        vicinity.includes('pegadaian') ||
                        // Add more specific filters for pegadaian branches
                        name.includes('kantor cabang pegadaian') ||
                        name.includes('upc pegadaian')
                    );
                });
                console.log(`After filtering Pegadaian: ${filteredResults.length} places`);
                
                allPlacesData = filteredResults;
                displayResults(filteredResults);
                document.getElementById('loading-places').style.display = 'none';
            }
        }
        
        // Search by types
        competitorTypes.forEach(type => {
            const request = {
                location: location,
                radius: 5000,
                type: type
            };
            
            service.nearbySearch(request, function(results, status) {
                if (status === google.maps.places.PlacesServiceStatus.OK) {
                    allResults = allResults.concat(results);
                }
                handleSearchComplete();
            });
        });
        
        // Search by keywords
        competitorKeywords.forEach(keyword => {
            const request = {
                location: location,
                radius: 5000,
                keyword: keyword
            };
            
            service.nearbySearch(request, function(results, status) {
                if (status === google.maps.places.PlacesServiceStatus.OK) {
                    allResults = allResults.concat(results);
                }
                handleSearchComplete();
            });
        });
        
        // Add general establishment search to catch more places
        const generalRequest = {
            location: location,
            radius: 5000,
            type: 'establishment'
        };
        
        service.nearbySearch(generalRequest, function(results, status) {
            if (status === google.maps.places.PlacesServiceStatus.OK) {
                // Filter general results to only financial-related places
                const financialResults = results.filter(place => {
                    const name = place.name ? place.name.toLowerCase() : '';
                    const types = place.types ? place.types.join(' ').toLowerCase() : '';
                    
                    return (
                        name.includes('bank') || name.includes('finance') || name.includes('kredit') ||
                        name.includes('gadai') || name.includes('emas') || name.includes('gold') ||
                        name.includes('koperasi') || name.includes('simpan') || name.includes('pinjam') ||
                        name.includes('asuransi') || name.includes('insurance') || name.includes('money') ||
                        name.includes('bpr') || name.includes('leasing') || name.includes('investasi') ||
                        types.includes('finance') || types.includes('bank') || types.includes('atm')
                    );
                });
                
                allResults = allResults.concat(financialResults);
            }
            handleSearchComplete();
        });

    } catch (error) {
        console.error('Error in searchNearbyPlaces:', error);
        alert('Terjadi kesalahan saat mencari lokasi: ' + error.message);
        document.getElementById('loading-places').style.display = 'none';
    }
}

function displayResults(places) {
    const lokasiList = document.getElementById('lokasi-list');
    
    if (!places || places.length === 0) {
        lokasiList.innerHTML = '<div class="text-center p-3"><p class="text-muted">Tidak ada lokasi pesaing ditemukan dalam radius 5km</p></div>';
        return;
    }

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

    // Reset variables
    displayedResults = [];
    currentPage = 0;
    
    // Sort by distance
    const sortedPlaces = places.map(place => {
        const distance = calculateDistance(
            kantorLocation.lati,
            kantorLocation.longi,
            place.geometry.location.lat(),
            place.geometry.location.lng()
        );
        return { ...place, distance };
    }).sort((a, b) => a.distance - b.distance);

    console.log('Total places to display:', sortedPlaces.length);
    
    // Store sorted places globally 
    window.sortedPlacesData = sortedPlaces;
    
    // Clear sidebar content
    lokasiList.innerHTML = '';
    
    // If we have many results, show first batch with lazy loading
    if (sortedPlaces.length > resultsPerPage) {
        displayWithPagination(sortedPlaces);
    } else {
        // Show all results at once if not too many
        displayAllResults(sortedPlaces);
    }
}

function displayAllResults(sortedPlaces) {
    const lokasiList = document.getElementById('lokasi-list');
    let sidebarHTML = '';
    
    sortedPlaces.forEach((place, index) => {
        // Add marker to map
        addPlaceMarker(place);
        
        // Build sidebar HTML
        sidebarHTML += createListItem(place);
        displayedResults.push(place);
    });
    
    // Set all HTML at once for better performance
    lokasiList.innerHTML = sidebarHTML;
    console.log(`Displayed all ${sortedPlaces.length} results in sidebar`);
}

function displayWithPagination(sortedPlaces) {
    const lokasiList = document.getElementById('lokasi-list');
    
    // Clear existing scroll listeners by cloning element
    const newLokasiList = lokasiList.cloneNode(false);
    lokasiList.parentNode.replaceChild(newLokasiList, lokasiList);
    
    // Display first page
    displayNextPage(sortedPlaces, document.getElementById('lokasi-list'));
    
    // Add lazy loading
    document.getElementById('lokasi-list').addEventListener('scroll', function(e) {
        const target = e.target;
        if (target.scrollTop + target.clientHeight >= target.scrollHeight - 10) {
            displayNextPage(window.sortedPlacesData, target);
        }
    });
}

function displayNextPage(sortedPlaces, targetElement) {
    const lokasiList = targetElement || document.getElementById('lokasi-list');
    const startIndex = currentPage * resultsPerPage;
    const endIndex = Math.min(startIndex + resultsPerPage, sortedPlaces.length);
    
    console.log(`DisplayNextPage - Page: ${currentPage}, Start: ${startIndex}, End: ${endIndex}, Total: ${sortedPlaces.length}`);
    
    if (startIndex >= sortedPlaces.length) {
        console.log('No more pages to load');
        return;
    }
    
    const pageResults = sortedPlaces.slice(startIndex, endIndex);
    console.log(`Page results count: ${pageResults.length}`);
    
    pageResults.forEach((place, index) => {
        // Check if already displayed
        if (displayedResults.find(p => p.place_id === place.place_id)) {
            console.log(`Skipping duplicate: ${place.name}`);
            return;
        }
        
        displayedResults.push(place);
        
        // Add marker to map
        addPlaceMarker(place);
        
        // Add to sidebar list
        const listItem = createListItem(place);
        if (currentPage === 0 && index === 0) {
            // First item of first page - replace content
            lokasiList.innerHTML = listItem;
            console.log('First item added, replaced content');
        } else {
            // Subsequent items - append
            lokasiList.innerHTML += listItem;
            console.log(`Item ${index + 1} appended: ${place.name}`);
        }
    });
    
    currentPage++;
    
    // Remove existing load more indicator
    const existingLoadMore = lokasiList.querySelector('.load-more-indicator');
    if (existingLoadMore) {
        existingLoadMore.remove();
    }
    
    // Add load more indicator if there are more results
    if (endIndex < sortedPlaces.length) {
        const loadMoreHtml = `
            <div class="text-center p-2 border-top load-more-indicator">
                <small class="text-muted">Scroll untuk memuat ${sortedPlaces.length - endIndex} lokasi lainnya...</small>
            </div>
        `;
        lokasiList.innerHTML += loadMoreHtml;
        console.log(`Load more indicator added. Remaining: ${sortedPlaces.length - endIndex}`);
    } else {
        console.log('All pages loaded');
    }
}

function createListItem(place) {
    const distance = place.distance || calculateDistance(
        kantorLocation.lati,
        kantorLocation.longi,
        place.geometry.location.lat(),
        place.geometry.location.lng()
    );

    return `
        <div class="border-bottom pb-2 mb-2" data-place-id="${place.place_id}">
            <div class="d-flex justify-content-between align-items-start">
                <div class="flex-grow-1">
                    <h6 class="mb-1 cursor-pointer text-primary" onclick="focusOnPlace('${place.place_id}')"
                        style="font-size: 0.9rem; font-weight: 600;">
                        ${place.name || 'Lokasi Tidak Diketahui'}
                    </h6>
                    <p class="mb-1 text-muted small">${place.vicinity || 'Alamat tidak tersedia'}</p>
                    ${place.rating ? `
                        <div class="mb-1">
                            <span class="badge badge-warning badge-sm">
                                <i class="fa fa-star"></i> ${place.rating}
                            </span>
                        </div>
                    ` : ''}
                    <small class="text-info">
                        <i class="fal fa-route"></i> ${distance.toFixed(2)} km
                    </small>
                </div>
                <div class="ml-2">
                    <button class="btn btn-sm btn-outline-primary btn-record-location" 
                            onclick="recordLocation('${place.place_id}')"
                            title="Rekam Lokasi">
                        <i class="fal fa-plus"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
}

function addPlaceMarker(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="#FFA500" 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)
        }
    });

    // Store place data with marker
    marker.placeData = place;
    lokasiMarkers.push(marker);

    // Add click event for info window
    marker.addListener('click', function() {
        closeAllTooltips();
        showPlaceInfoWindow(place, marker);
    });
    
    // Add double-click event for details
    marker.addListener('dblclick', function() {
        closeAllTooltips();
        showRecordModal(place);
    });
    
    // Add right-click event for recording
    marker.addListener('rightclick', function() {
        closeAllTooltips();
        showRecordModal(place);
    });
}

function closeAllTooltips() {
    if (activeInfoWindow) {
        activeInfoWindow.close();
        activeInfoWindow = null;
    }
}

function showPlaceInfoWindow(place, marker) {
    const distance = calculateDistance(
        kantorLocation.lati,
        kantorLocation.longi,
        place.geometry.location.lat(),
        place.geometry.location.lng()
    );
    
    const infoWindow = new google.maps.InfoWindow({
        content: createPlaceInfoContent(place, distance)
    });
    
    infoWindow.open(map, marker);
    activeInfoWindow = infoWindow;
    
    // 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
    infoWindow.addListener('closeclick', function() {
        activeInfoWindow = null;
    });
}

function createPlaceInfoContent(place, distance) {
    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: 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>
                Pesaing potensial ditemukan
            </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 focusOnPlace(placeId) {
    const marker = lokasiMarkers.find(m => m.placeData.place_id === placeId);
    if (marker) {
        map.setCenter(marker.getPosition());
        map.setZoom(16);
        
        // Show info window
        closeAllTooltips();
        showPlaceInfoWindow(marker.placeData, marker);
    }
}

function recordLocation(placeId) {
    const place = allPlacesData.find(p => p.place_id === placeId);
    if (place) {
        showRecordModal(place);
    }
}

function showRecordModal(place) {
    // Reset form fields to readonly first
    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;
            
            // 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;
            
            // 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');
}

// Search places button
document.getElementById('btn-search-places').addEventListener('click', function() {
    console.log('Search button clicked');
    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 = [];
    
    // Clear results
    document.getElementById('lokasi-list').innerHTML = 
        '<div class="text-center p-3"><p class="text-muted">Klik tombol "Cari" untuk mencari lokasi pesaing 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('nama')) {
        toastr.warning('Nama lokasi tidak boleh kosong', 'Peringatan!');
        return;
    }
    
    // Show loading
    this.innerHTML = '<i class="fal fa-spinner fa-spin"></i> Menyimpan...';
    this.disabled = true;
    
    $.ajax({
        url: '<?= base_url('pesaing/kuralokasi/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');
                        resetModalToReadonly();
                    }
                });
            }
        },
        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() {
    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 || !google.maps.places) {
        console.error('Google Maps or Places API not available');
        return;
    }
    
    console.log('Google Maps API ready, initializing map...');
    initMap();
    
    // Initialize responsive sidebar behavior (reuse from original)
    initResponsiveSidebar();
});

function initResponsiveSidebar() {
    // Reuse the responsive sidebar code from the original
    const sidebarPanel = document.getElementById('js-slide-right');
    const backdrop = document.querySelector('.slide-backdrop');
    const openButton = document.querySelector('[data-target="#js-slide-right"]');
    
    if (backdrop) {
        backdrop.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            closeSidebar();
        });
    }
    
    if (openButton) {
        openButton.removeAttribute('data-action');
        openButton.removeAttribute('data-class');
        
        openButton.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            openSidebar();
        });
    }
    
    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();
            }
        }
    });
    
    window.addEventListener('resize', function() {
        if (window.innerWidth > 991.98) {
            sidebarPanel.classList.remove('slide-on-mobile-right-show');
            if (backdrop) {
                backdrop.classList.remove('show');
            }
        }
    });
    
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && sidebarPanel.classList.contains('slide-on-mobile-right-show')) {
            closeSidebar();
        }
    });
}

function openSidebar() {
    const sidebarPanel = document.getElementById('js-slide-right');
    const backdrop = document.querySelector('.slide-backdrop');
    
    if (sidebarPanel) {
        sidebarPanel.classList.add('slide-on-mobile-right-show');
    }
    
    if (backdrop) {
        backdrop.classList.add('show');
    }
}

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-->
