<!-- Map Location Picker Modal -->
<link rel="stylesheet" href="./leaflet/leaflet.css">
<script src="./leaflet/leaflet.js"></script>

<style>
#mapPickerModal {
    display: none;
    position: fixed;
    z-index: 10000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.7);
}
#mapPickerContent {
    background-color: #1f1f1f;
    margin: 2% auto;
    padding: 0;
    border: 2px solid #667eea;
    border-radius: 8px;
    width: 70%;
    max-width: 900px;
    box-shadow: 0 10px 40px rgba(0,0,0,0.8);
}
#mapPickerHeader {
    background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 6px 12px;
    border-radius: 6px 6px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
#mapPickerClose {
    background: none;
    border: none;
    color: white;
    font-size: 28px;
    cursor: pointer;
    padding: 0;
    width: 30px;
    height: 30px;
    line-height: 26px;
}
#mapPickerClose:hover {
    opacity: 0.8;
}
#mapPickerBody {
    padding: 0;
    background: #2a2a2a;
}
#locationPickerMap {
    width: 100%;
    height: 500px;
    background-color: #1a1a1a;
}
#mapPickerFooter {
    padding: 12px 15px;
    background: #1a1a1a;
    border-radius: 0 0 6px 6px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
#selectedCoords {
    color: #aaa;
    font-size: 13px;
}
.map-picker-btn {
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    margin-left: 8px;
}
#confirmLocationBtn {
    background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
    color: white;
}
#confirmLocationBtn:hover {
    opacity: 0.9;
}
#cancelLocationBtn {
    background: #555;
    color: white;
}
#cancelLocationBtn:hover {
    background: #666;
}
</style>

<div id="mapPickerModal">
    <div id="mapPickerContent">
        <div id="mapPickerHeader">
            <span style="font-size:14px; font-weight:600;"><i class="zmdi zmdi-pin"></i> Select Device Location</span>
            <button id="mapPickerClose">&times;</button>
        </div>
        <div id="mapPickerBody">
            <div id="locationPickerMap"></div>
        </div>
        <div id="mapPickerFooter">
            <span id="selectedCoords">Click on the map to select a location</span>
            <div>
                <button id="cancelLocationBtn" class="map-picker-btn">Cancel</button>
                <button id="confirmLocationBtn" class="map-picker-btn">Confirm Location</button>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    var pickerMap = null;
    var currentMarker = null;
    var selectedX = null;
    var selectedY = null;

    // Get current theme
    var bodyClass = document.body.className;
    var themeMatch = bodyClass.match(/bg-theme(\d+)/);
    var theme = themeMatch ? 'bg-theme' + themeMatch[1] : 'bg-theme1';

    // Theme-specific configurations
    var themeConfig = {
        'bg-theme1': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
        'bg-theme2': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
        'bg-theme3': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
        'bg-theme4': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
        'bg-theme5': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
        'bg-theme6': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
        'bg-theme7': { bg: '#0c675e', filter: 'brightness(0.8) contrast(1.1) hue-rotate(-10deg)' },
        'bg-theme8': { bg: '#4a3020', filter: 'brightness(0.75) contrast(1.1) saturate(0.8)' },
        'bg-theme9': { bg: '#29323c', filter: 'brightness(0.7) contrast(1.1)' },
        'bg-theme10': { bg: '#795548', filter: 'brightness(0.8) contrast(1.05) sepia(0.2)' },
        'bg-theme11': { bg: '#1565C0', filter: 'brightness(0.85) contrast(1.05) hue-rotate(-5deg)' },
        'bg-theme12': { bg: '#65379b', filter: 'brightness(0.8) contrast(1.1) hue-rotate(5deg)' },
        'bg-theme13': { bg: '#d03050', filter: 'brightness(0.85) contrast(1.05) saturate(0.9)' },
        'bg-theme14': { bg: '#2a7a2e', filter: 'brightness(0.8) contrast(1.1) saturate(0.95)' },
        'bg-theme15': { bg: '#4643d3', filter: 'brightness(0.85) contrast(1.05) hue-rotate(-5deg)' },
        'bg-theme16': { bg: '#6a11cb', filter: 'brightness(0.8) contrast(1.1)' }
    };

    var config = themeConfig[theme] || { bg: '#1a1a1a', filter: 'brightness(0.7) contrast(1.1)' };

    // Determine which map image to use based on theme
    var lightThemes = ['bg-theme11', 'bg-theme13'];
    var mapImage = lightThemes.includes(theme) ? './images/sitemap2025-light.png' : './images/sitemap2025-dark.png';

    function updateCoordinateDisplay() {
        if (selectedX !== null && selectedY !== null) {
            var displayY = 2550 - selectedY;
            $('#selectedCoords').text('Selected: X=' + Math.round(selectedX) + ', Y=' + Math.round(displayY));
        } else {
            $('#selectedCoords').text('Click on the map to select a location');
        }
    }

    $('#selectLocationBtn').click(function() {
        $('#mapPickerModal').fadeIn(200);

        if (!pickerMap) {
            // Initialize map
            pickerMap = L.map('locationPickerMap', {
                crs: L.CRS.Simple,
                minZoom: -3
            });

            var bounds = [[0, 0], [2550, 3300]];
            var image = L.imageOverlay(mapImage, bounds);

            // Apply theme-specific filter
            image.on('load', function() {
                var imgElement = this.getElement();
                if (imgElement) {
                    imgElement.style.filter = config.filter;
                }
            });

            image.addTo(pickerMap);
            pickerMap.fitBounds(bounds);

            // Add click handler
            pickerMap.on('click', function(e) {
                selectedX = e.latlng.lng;
                selectedY = e.latlng.lat;

                // Remove existing marker
                if (currentMarker) {
                    pickerMap.removeLayer(currentMarker);
                }

                // Add new draggable marker
                currentMarker = L.marker([selectedY, selectedX], {
                    draggable: true,
                    icon: L.divIcon({
                        className: 'custom-marker-icon',
                        html: '<div style="width:20px; height:20px; background:#667eea; border:3px solid #fff; border-radius:50%; box-shadow:0 2px 8px rgba(0,0,0,0.5); cursor:move;"></div>',
                        iconSize: [20, 20],
                        iconAnchor: [10, 10]
                    })
                }).addTo(pickerMap);

                // Update coordinates when dragged
                currentMarker.on('dragend', function(e) {
                    var position = e.target.getLatLng();
                    selectedX = position.lng;
                    selectedY = position.lat;
                    updateCoordinateDisplay();
                });

                updateCoordinateDisplay();
            });
        }

        // Load existing coordinates if available
        var existingLeft = $('#mapleft').val();
        var existingTop = $('#maptop').val();

        if (existingLeft && existingTop && existingLeft != '' && existingTop != '') {
            selectedX = parseFloat(existingLeft);
            selectedY = 2550 - parseFloat(existingTop);

            if (currentMarker) {
                pickerMap.removeLayer(currentMarker);
            }

            currentMarker = L.marker([selectedY, selectedX], {
                draggable: true,
                icon: L.divIcon({
                    className: 'custom-marker-icon',
                    html: '<div style="width:20px; height:20px; background:#667eea; border:3px solid #fff; border-radius:50%; box-shadow:0 2px 8px rgba(0,0,0,0.5); cursor:move;"></div>',
                    iconSize: [20, 20],
                    iconAnchor: [10, 10]
                })
            }).addTo(pickerMap);

            // Update coordinates when dragged
            currentMarker.on('dragend', function(e) {
                var position = e.target.getLatLng();
                selectedX = position.lng;
                selectedY = position.lat;
                updateCoordinateDisplay();
            });

            // Pan to marker
            pickerMap.panTo([selectedY, selectedX]);

            updateCoordinateDisplay();
        }

        setTimeout(function() {
            pickerMap.invalidateSize();
        }, 250);
    });

    $('#confirmLocationBtn').click(function() {
        if (selectedX !== null && selectedY !== null) {
            var convertedY = 2550 - selectedY;
            $('#mapleft').val(Math.round(selectedX));
            $('#maptop').val(Math.round(convertedY));

            // Update the display on the form
            $('#coordinateDisplay').html('Current position: X=' + Math.round(selectedX) + ', Y=' + Math.round(convertedY));

            updateCoordinateDisplay();
            $('#mapPickerModal').fadeOut(200);
        } else {
            alert('Please select a location on the map first.');
        }
    });

    $('#cancelLocationBtn, #mapPickerClose').click(function() {
        $('#mapPickerModal').fadeOut(200);
    });
});
</script>
