<?= $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"><?= ucfirst($segment1) ?></li>
    <li class="breadcrumb-item">Lokasi Kantor</li>
    <li class="position-absolute pos-top pos-right d-none d-sm-block"><span class="js-get-date"></span></li>
</ol>

<div class="p-0 p-sm-3">
    <!-- Mobile panel toggle button -->
    <div class="row d-lg-none 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">
                Open Right Panel
            </a>
        </div>
    </div>
    
    <!-- Main content row -->
    <div class="row">
        <!-- Map column -->
        <div class="col-12 col-lg-8">
            <div class="panel">
                <div class="panel-hdr">
                    <h2>Peta Lokasi 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>
        
        <!-- Desktop panel column -->
        <div class="col-lg-4 d-none d-lg-block">
            <div class="panel h-100 bg-default-200">
                <div class="panel-hdr">
                    <h2>Data Kantor</h2>
                </div>
                <div class="panel-container show" style="height: 600px;">
                    <div class="panel-content p-3">
                        <div class="d-flex align-items-center mb-3">
                            <button type="button" class="btn btn-sm btn-outline-secondary mr-2" id="btn-back-desktop" style="display: none;">
                                <i class="fal fa-arrow-left"></i> Back
                            </button>
                            <span class="badge badge-info" id="current-level-desktop">Level: Pusat & Wilayah</span>
                        </div>
                        <div id="office-data-desktop" class="list-group list-group-flush" style="max-height: 500px; overflow-y: auto;">
                            <!-- Office data will be populated here -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Mobile right slider panel -->
<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 d-lg-none" style="min-width: 320px;">
    <div class="d-flex align-items-center mb-3">
        <button type="button" class="btn btn-sm btn-outline-secondary mr-2" id="btn-back" style="display: none;">
            <i class="fal fa-arrow-left"></i> Back
        </button>
        <span class="badge badge-info" id="current-level">Level: Pusat & Wilayah</span>
    </div>
    
    <div id="office-list" class="mt-3">
        <h6 class="text-muted mb-2">Data Kantor</h6>
        <div id="office-data" class="list-group list-group-flush">
            <!-- Office data will be populated here -->
        </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>

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

<!-- pageScripts section start-->
<?= $this->section('pageScripts') ?>

<script>
// Global variables
let map, currentMarkers = [], infoWindow, currentLevel = 'pusat-wilayah';
let currentWilayahId = null, currentAreaId = null;
let markerIcons; // Declare first
let currentRadiusCircles = []; // For branch office radius circles
let currentOfficeData = []; // Store current office data
let markerOfficeMap = new Map(); // Map office ID to marker
let radiusOfficeMap = new Map(); // Map office ID to radius circle
let officeRadiusVisibility = new Map(); // Track radius visibility for each office

// Initialize marker icons
function initMarkerIcons() {
    console.log('Initializing marker icons...');
    markerIcons = {
    pusat: {
        url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(`
            <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24">
                <path fill="#FF6B35" 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(28, 28)
    },
    wilayah: {
        url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(`
            <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24">
                <path fill="#9C27B0" 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(28, 28)
    },
    area: {
        url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(`
            <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24">
                <path fill="#2196F3" 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(28, 28)
    },
    cabang: {
        url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(`
            <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24">
                <path fill="#4CAF50" 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(28, 28)
    }
    };
    console.log('Marker icons initialized:', markerIcons);
}

// Initialize map
function initMap() {
    // Initialize marker icons first
    initMarkerIcons();
    
    map = new google.maps.Map(document.getElementById('mapx'), {
        zoom: 5,
        center: { lat: -2.5489, lng: 118.0149 }, // Indonesia center
        mapTypeId: 'roadmap',
        styles: [
            {
                featureType: 'water',
                elementType: 'geometry',
                stylers: [{ color: '#a2daf2' }]
            },
            {
                featureType: 'landscape.natural',
                elementType: 'geometry',
                stylers: [{ color: '#f5f5dc' }]
            },
            {
                featureType: 'road',
                elementType: 'geometry',
                stylers: [{ color: '#ffffff' }]
            },
            {
                featureType: 'poi',
                elementType: 'geometry',
                stylers: [{ color: '#e5e5e5' }]
            }
        ]
    });

    infoWindow = new google.maps.InfoWindow();
    
    // Load initial data
    loadPusatWilayah();
    
    // Initialize switch handlers for mobile
    initSwitchHandlers();
    
    // Reset button event
    document.getElementById('btn-reset').addEventListener('click', function() {
        resetToInitial();
    });
    
    // Back button events (both mobile and desktop)
    document.getElementById('btn-back').addEventListener('click', function() {
        handleBackButton();
    });
    
    document.getElementById('btn-back-desktop').addEventListener('click', function() {
        handleBackButton();
    });
}

// Clear all markers and circles
function clearMarkers() {
    currentMarkers.forEach(marker => {
        marker.setMap(null);
    });
    currentMarkers = [];
    
    // Clear radius circles
    currentRadiusCircles.forEach(circle => {
        circle.setMap(null);
    });
    currentRadiusCircles = [];
    
    // Clear marker-office mapping
    markerOfficeMap.clear();
    radiusOfficeMap.clear();
    officeRadiusVisibility.clear();
    
    infoWindow.close();
}

// Create marker with events
function createMarker(data, icon) {
    // Validate coordinates
    const lat = parseFloat(data.lati);
    const lng = parseFloat(data.longi);
    
    if (isNaN(lat) || isNaN(lng)) {
        console.warn('Invalid coordinates for:', data.satker);
        return null;
    }
    
    const position = { lat: lat, lng: lng };
    
    const marker = new google.maps.Marker({
        position: position,
        map: map,
        icon: icon,
        title: data.satker,
        animation: google.maps.Animation.DROP
    });

    // Single click - show info window
    marker.addListener('click', function() {
        showInfoWindow(marker, data);
    });

    // Double click - navigate to next level
    marker.addListener('dblclick', function() {
        handleDoubleClick(data);
    });

    currentMarkers.push(marker);
    
    // Store marker-office mapping
    console.log('Storing marker for office ID:', data.id, 'marker:', marker);
    markerOfficeMap.set(parseInt(data.id), marker);
    
    return marker;
}

// Show info window with office details
function showInfoWindow(marker, data) {
    let content = `
        <div style="max-width: 250px;">
            <h6 class="mb-1"><strong>${data.satker}</strong></h6>
            <p class="mb-1"><span class="badge badge-${getBadgeColor(data.tipe)}">${data.tipe}</span></p>
            <p class="mb-1 text-muted small">${data.alamat || 'Alamat tidak tersedia'}</p>
    `;
    
    if (data.tel1) {
        content += `<p class="mb-1 small"><i class="fas fa-phone"></i> ${data.tel1}</p>`;
    }
    
    if (data.mail1) {
        content += `<p class="mb-1 small"><i class="fas fa-envelope"></i> ${data.mail1}</p>`;
    }
    
    content += `
            <hr class="my-2">
            <p class="mb-0 small text-info">
                <i class="fas fa-info-circle"></i> 
                ${data.tipe === 'Wilayah' ? 'Double-click untuk lihat Area' : 
                  data.tipe === 'Area' ? 'Double-click untuk lihat Cabang' : 
                  'Kantor ' + data.tipe}
            </p>
        </div>
    `;

    infoWindow.setContent(content);
    infoWindow.open(map, marker);
}

// Get badge color based on office type
function getBadgeColor(tipe) {
    switch(tipe) {
        case 'Pusat': return 'danger';     // Red/Orange - matches marker
        case 'Wilayah': return 'wilayah';  // Purple - custom class
        case 'Area': return 'area';        // Blue - custom class  
        case 'Cabang': return 'cabang';    // Green - custom class
        case 'Cabang/ UPC/ UPS': return 'cabang';    // Green - custom class
        default: return 'secondary';
    }
}

// Handle double click navigation
function handleDoubleClick(data) {
    if (data.tipe === 'Wilayah') {
        loadWilayahWithArea(data.id);
    } else if (data.tipe === 'Area') {
        loadAreaWithCabang(data.id);
    }
}

// Load Pusat & Wilayah data
function loadPusatWilayah() {
    // Ensure markerIcons is initialized
    if (!markerIcons) {
        initMarkerIcons();
    }
    
    fetch('<?= base_url('dashboard/lokasikantor/getPusatWilayah') ?>')
        .then(response => response.json())
        .then(result => {
            if (result.status === 'success') {
                clearMarkers();
                currentLevel = 'pusat-wilayah';
                currentWilayahId = null;
                currentAreaId = null;
                currentOfficeData = result.data;
                document.getElementById('current-level').textContent = 'Level: Pusat & Wilayah';
                document.getElementById('current-level-desktop').textContent = 'Level: Pusat & Wilayah';
                updateBackButton();
                
                // Bounds for auto-fit
                const bounds = new google.maps.LatLngBounds();
                
                result.data.forEach(office => {
                    const icon = office.tipe === 'Pusat' ? markerIcons.pusat : markerIcons.wilayah;
                    const marker = createMarker(office, icon);
                    if (marker) { // Check if marker was created successfully
                        bounds.extend(marker.getPosition());
                    }
                });
                
                // Fit map to show all markers
                if (currentMarkers.length > 0) {
                    map.fitBounds(bounds);
                    
                    // Set maximum zoom level
                    google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
                        if (map.getZoom() > 10) {
                            map.setZoom(10);
                        }
                    });
                }
                
                // Update office data list
                updateOfficeDataList(result.data);
            } else {
                console.error('API Error:', result.message);
                if (typeof toastr !== 'undefined') {
                    toastr.error(result.message || 'Gagal memuat data kantor');
                } else {
                    alert(result.message || 'Gagal memuat data kantor');
                }
            }
        })
        .catch(error => {
            console.error('Error loading data:', error);
            if (typeof toastr !== 'undefined') {
                toastr.error('Gagal memuat data kantor');
            } else {
                alert('Gagal memuat data kantor');
            }
        });
}

// Load Wilayah with Area data
function loadWilayahWithArea(idWilayah) {
    fetch(`<?= base_url('dashboard/lokasikantor/getWilayahWithArea') ?>/${idWilayah}`)
        .then(response => response.json())
        .then(result => {
            if (result.status === 'success') {
                clearMarkers();
                currentLevel = 'wilayah-area';
                currentWilayahId = idWilayah;
                currentAreaId = null;
                
                const wilayah = result.data.wilayah;
                const areas = result.data.areas;
                
                document.getElementById('current-level').textContent = 'Level: Wilayah & Area';
                document.getElementById('current-level-desktop').textContent = 'Level: Wilayah & Area';
                updateBackButton();
                
                const bounds = new google.maps.LatLngBounds();
                
                // Add wilayah marker
                const wilayahMarker = createMarker(wilayah, markerIcons.wilayah);
                if (wilayahMarker) {
                    bounds.extend(wilayahMarker.getPosition());
                }
                
                // Add area markers
                areas.forEach(area => {
                    const marker = createMarker(area, markerIcons.area);
                    if (marker) {
                        bounds.extend(marker.getPosition());
                    }
                });
                
                // Fit and zoom
                if (currentMarkers.length > 0) {
                    map.fitBounds(bounds);
                    
                    google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
                        if (map.getZoom() > 12) {
                            map.setZoom(12);
                        }
                    });
                }
                
                // Update office data list
                const allOffices = [wilayah, ...areas];
                currentOfficeData = allOffices; // Update current office data
                updateOfficeDataList(allOffices, wilayah);
            }
        })
        .catch(error => {
            console.error('Error loading wilayah data:', error);
            toastr.error('Gagal memuat data wilayah');
        });
}

// Load Area with Cabang data
function loadAreaWithCabang(idArea) {
    fetch(`<?= base_url('dashboard/lokasikantor/getAreaWithCabang') ?>/${idArea}`)
        .then(response => response.json())
        .then(result => {
            if (result.status === 'success') {
                clearMarkers();
                currentLevel = 'area-cabang';
                currentAreaId = idArea;
                
                const area = result.data.area;
                const cabangs = result.data.cabangs;
                
                document.getElementById('current-level').textContent = 'Level: Area & Cabang/UPC/UPS';
                document.getElementById('current-level-desktop').textContent = 'Level: Area & Cabang/UPC/UPS';
                updateBackButton();
                
                const bounds = new google.maps.LatLngBounds();
                
                // Add area marker
                const areaMarker = createMarker(area, markerIcons.area);
                if (areaMarker) {
                    bounds.extend(areaMarker.getPosition());
                }
                
                // Add cabang markers with radius circles
                cabangs.forEach(cabang => {
                    const marker = createMarker(cabang, markerIcons.cabang);
                    if (marker) {
                        bounds.extend(marker.getPosition());
                        // Add 5km radius circle for each cabang
                        createRadiusCircle(marker.getPosition(), 5000, cabang.id);
                    }
                });
                
                // Fit and zoom
                if (currentMarkers.length > 0) {
                    map.fitBounds(bounds);
                    
                    google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
                        if (map.getZoom() > 14) {
                            map.setZoom(14);
                        }
                    });
                }
                
                // Update office data list
                const allOffices = [area, ...cabangs];
                currentOfficeData = allOffices; // Update current office data
                updateOfficeDataList(allOffices, area);
            }
        })
        .catch(error => {
            console.error('Error loading area data:', error);
            toastr.error('Gagal memuat data area');
        });
}

// Reset to initial view
function resetToInitial() {
    loadPusatWilayah();
}

// Handle back button navigation
function handleBackButton() {
    if (currentLevel === 'area-cabang') {
        // From area-cabang back to wilayah-area
        loadWilayahWithArea(currentWilayahId);
    } else if (currentLevel === 'wilayah-area') {
        // From wilayah-area back to pusat-wilayah
        loadPusatWilayah();
    }
}

// Update back button visibility
function updateBackButton() {
    const backBtn = document.getElementById('btn-back');
    const backBtnDesktop = document.getElementById('btn-back-desktop');
    
    if (currentLevel === 'pusat-wilayah') {
        backBtn.style.display = 'none';
        backBtnDesktop.style.display = 'none';
    } else {
        backBtn.style.display = 'inline-block';
        backBtnDesktop.style.display = 'inline-block';
    }
}

// Create radius circle for branch offices
function createRadiusCircle(position, radius = 5000, officeId = null) {
    const circle = new google.maps.Circle({
        strokeColor: '#4CAF50',
        strokeOpacity: 0.6,
        strokeWeight: 2,
        fillColor: '#4CAF50',
        fillOpacity: 0.15,
        map: map,
        center: position,
        radius: radius // 5km in meters
    });
    
    currentRadiusCircles.push(circle);
    
    // Store radius-office mapping if officeId provided
    if (officeId) {
        console.log('Storing radius circle for office ID:', officeId, 'circle:', circle);
        radiusOfficeMap.set(parseInt(officeId), circle);
        officeRadiusVisibility.set(parseInt(officeId), true); // Initially visible
    }
    
    return circle;
}

// Calculate distance between two points (Haversine formula)
function calculateDistance(lat1, lng1, lat2, lng2) {
    const R = 6371; // Earth's 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;
}

// Update office data list in sidebar
function updateOfficeDataList(offices, parentOffice = null) {
    const officeDataDiv = document.getElementById('office-data');
    const officeDataDivDesktop = document.getElementById('office-data-desktop');
    let html = '';
    
    // Sort offices - parent first, then by distance from parent
    let sortedOffices = [...offices];
    if (parentOffice) {
        const parentLat = parseFloat(parentOffice.lati);
        const parentLng = parseFloat(parentOffice.longi);
        
        // Add parent office first
        html += createOfficeListItem(parentOffice, 0, true);
        
        // Sort other offices by distance from parent
        sortedOffices = sortedOffices
            .filter(office => office.id !== parentOffice.id)
            .map(office => {
                const distance = calculateDistance(
                    parentLat, parentLng,
                    parseFloat(office.lati), parseFloat(office.longi)
                );
                return { ...office, distance };
            })
            .sort((a, b) => a.distance - b.distance);
    }
    
    // Add other offices
    sortedOffices.forEach(office => {
        const distance = office.distance || 0;
        html += createOfficeListItem(office, distance, false);
    });
    
    // Update both mobile and desktop panels
    officeDataDiv.innerHTML = html;
    officeDataDivDesktop.innerHTML = html;
}

// Bounce marker when office is clicked
function bounceMarker(officeId) {
    console.log('Bouncing marker for office ID:', officeId);
    console.log('Available markers:', markerOfficeMap);
    
    const marker = markerOfficeMap.get(parseInt(officeId));
    console.log('Found marker:', marker);
    
    if (marker) {
        marker.setAnimation(google.maps.Animation.BOUNCE);
        // Stop bouncing after 2 seconds
        setTimeout(() => {
            marker.setAnimation(null);
        }, 2000);
        
        // Center map on marker
        map.panTo(marker.getPosition());
    } else {
        console.error('Marker not found for office ID:', officeId);
    }
}

// Handle double click on office data (same as marker double click)
function handleOfficeDoubleClick(officeId) {
    console.log('Double click on office ID:', officeId);
    
    // Find office data from current office data
    const officeData = currentOfficeData.find(office => parseInt(office.id) === parseInt(officeId));
    
    if (officeData) {
        console.log('Found office data:', officeData);
        handleDoubleClick(officeData);
    } else {
        console.error('Office data not found for ID:', officeId);
    }
}

// Toggle radius visibility for an office
function toggleRadiusVisibility(officeId, isVisible) {
    console.log('Toggling radius for office ID:', officeId, 'visible:', isVisible);
    console.log('Available radius circles:', radiusOfficeMap);
    
    const circle = radiusOfficeMap.get(parseInt(officeId));
    console.log('Found circle:', circle);
    
    if (circle) {
        circle.setMap(isVisible ? map : null);
        officeRadiusVisibility.set(parseInt(officeId), isVisible);
        console.log('Radius toggled successfully');
    } else {
        console.error('Radius circle not found for office ID:', officeId);
    }
}

// Enhanced switch handling for mobile
function initSwitchHandlers() {
    // Add delegated event listeners for better mobile support
    document.addEventListener('touchstart', function(e) {
        if (e.target.closest('.switch-container')) {
            e.target.closest('.switch-container').style.backgroundColor = 'rgba(0,0,0,0.1)';
        }
    });
    
    document.addEventListener('touchend', function(e) {
        if (e.target.closest('.switch-container')) {
            e.target.closest('.switch-container').style.backgroundColor = 'transparent';
        }
    });
}

// Create office list item HTML
function createOfficeListItem(office, distance, isParent) {
    const badgeClass = getBadgeColor(office.tipe);
    const distanceText = isParent ? '' : `<small class="text-muted">(${distance.toFixed(1)} km)</small>`;
    const parentIcon = isParent ? '<i class="fas fa-crown text-warning mr-1"></i>' : '';
    
    // Show switch only for area-cabang level and cabang offices
    const showSwitch = currentLevel === 'area-cabang' && office.tipe === 'Cabang/ UPC/ UPS';
    const switchHtml = showSwitch ? `
        <div class="custom-control custom-switch custom-control-sm switch-container" 
             onclick="event.stopPropagation();" 
             ontouchstart="event.stopPropagation();" 
             ontouchend="event.stopPropagation();">
            <input type="checkbox" class="custom-control-input" id="switch-${office.id}" 
                   checked onchange="toggleRadiusVisibility(${office.id}, this.checked)"
                   onclick="event.stopPropagation();" 
                   ontouchstart="event.stopPropagation();">
            <label class="custom-control-label" for="switch-${office.id}" 
                   onclick="event.stopPropagation();" 
                   ontouchstart="event.stopPropagation();"></label>
        </div>
    ` : '';
    
    // Determine if this office can be double-clicked to navigate
    const canNavigate = (office.tipe === 'Wilayah' && currentLevel === 'pusat-wilayah') || 
                       (office.tipe === 'Area' && currentLevel === 'wilayah-area');
    const navigationHint = canNavigate ? `<small class="text-info"><i class="fas fa-hand-pointer"></i> Double-click untuk navigasi</small>` : '';
    
    return `
        <div class="list-group-item list-group-item-action p-2 border-0 ${isParent ? 'bg-light' : ''}" 
             style="cursor: pointer;" title="${canNavigate ? 'Single click: focus marker, Double click: navigate' : 'Single click: focus marker'}">
            <div onclick="bounceMarker(${office.id});" ondblclick="handleOfficeDoubleClick(${office.id}); event.stopPropagation();">
                <h6 class="mb-1 text-truncate" style="font-size: 0.85rem;">
                    ${parentIcon}${office.satker}
                </h6>
                <div class="mb-1">
                    <span class="badge badge-${badgeClass} badge-sm">${office.tipe}</span>
                    ${distanceText}
                </div>
                <p class="mb-1 text-muted small text-truncate">${office.alamat || '-'}</p>
                ${navigationHint}
            </div>
            ${showSwitch ? `
                <div class="mt-2 pt-2 border-top" style="border-color: rgba(0,0,0,0.1) !important;">
                    <div class="d-flex align-items-center justify-content-between">
                        <small class="text-muted">Tampilkan radius 5km:</small>
                        ${switchHtml}
                    </div>
                </div>
            ` : ''}
        </div>
    `;
}

// Add some CSS for better styling
const style = document.createElement('style');
style.textContent = `
    .gm-style-iw-d {
        overflow: hidden !important;
    }
    .gm-style-iw-c {
        padding: 8px !important;
    }
    
    /* Custom badge colors to match markers */
    .badge-wilayah {
        background-color: #9C27B0 !important;
        color: white !important;
    }
    .badge-area {
        background-color: #2196F3 !important;
        color: white !important;
    }
    .badge-cabang {
        background-color: #4CAF50 !important;
        color: white !important;
    }
    
    /* Custom switch styling */
    .custom-control-sm .custom-control-input {
        width: 1.5rem;
        height: 0.875rem;
    }
    .custom-control-sm .custom-control-label {
        font-size: 0.75rem;
        line-height: 1;
        position: relative;
        z-index: 10;
    }
    .custom-control-sm .custom-control-label::before {
        width: 1.5rem;
        height: 0.875rem;
        z-index: 1;
    }
    .custom-control-sm .custom-control-label::after {
        width: 0.625rem;
        height: 0.625rem;
        z-index: 2;
    }
    
    /* Switch container improvements for mobile */
    .switch-container {
        padding: 4px !important;
        margin: 0 !important;
        position: relative;
        z-index: 100;
        background: transparent;
        border-radius: 4px;
    }
    
    /* Mobile specific improvements */
    @media (max-width: 991.98px) {
        .switch-container {
            min-width: 44px;
            min-height: 44px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .custom-control-sm .custom-control-label::before {
            width: 2rem;
            height: 1.2rem;
        }
        
        .custom-control-sm .custom-control-label::after {
            width: 0.8rem;
            height: 0.8rem;
        }
        
        .custom-control-sm .custom-control-input {
            width: 2rem;
            height: 1.2rem;
        }
        
        /* Ensure touch events work */
        .switch-container * {
            pointer-events: auto;
            touch-action: manipulation;
        }
    }
    
    /* Switch section styling */
    .border-top {
        border-top: 1px solid rgba(0,0,0,0.1) !important;
    }
    
    /* Hide scrollbars but keep scroll functionality */
    #office-data-desktop {
        scrollbar-width: none; /* Firefox */
        -ms-overflow-style: none; /* Internet Explorer 10+ */
    }
    
    #office-data-desktop::-webkit-scrollbar {
        width: 0;
        height: 0;
        background: transparent; /* Chrome/Safari/Webkit */
    }
    
    #office-data,
    #office-data-desktop {
        overflow-x: hidden; /* Hide horizontal scroll */
    }
    
    /* Hide scrollbars globally if needed */
    body {
        overflow-x: hidden;
    }
    
    /* Hide scrollbars for mobile panel */
    #js-slide-right {
        overflow-x: hidden;
        scrollbar-width: none; /* Firefox */
        -ms-overflow-style: none; /* Internet Explorer 10+ */
    }
    
    #js-slide-right::-webkit-scrollbar {
        width: 0;
        height: 0;
        background: transparent;
    }
    
    /* Responsive text handling */
    .text-truncate {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    /* Ensure desktop panel doesn't overflow */
    #office-data-desktop .list-group-item {
        word-wrap: break-word;
        overflow-wrap: break-word;
    }
    
    /* Mobile panel adjustments */
    @media (max-width: 991.98px) {
        #js-slide-right {
            max-width: 90vw;
        }
        
        /* Prevent horizontal overflow on mobile */
        body {
            overflow-x: hidden;
        }
        
        .slide-on-mobile-right-show #js-slide-right {
            transform: translateX(0);
        }
    }
    
    /* Prevent long text from breaking layout */
    .list-group-item h6,
    .list-group-item p {
        max-width: 100%;
        word-break: break-word;
        hyphens: auto;
    }
    
    /* Visual feedback for double-clickable items */
    .list-group-item-action:hover .flex-grow-1 {
        background-color: rgba(0,123,255,0.1);
        border-radius: 4px;
        transition: background-color 0.2s ease;
    }
`;
document.head.appendChild(style);
</script>

<!-- Load Google Maps API -->
<script async defer 
    src="https://maps.googleapis.com/maps/api/js?key=<?= $map_api ?>&callback=initMap&libraries=geometry">
</script>

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