document.addEventListener('DOMContentLoaded', function() {
    wtdp_hideMessage();  // Call the wtdp_hideMessage function after page load

    // Tab navigation logic
    let currentTab = sessionStorage.getItem('activeTab') || '#general-settings-tab'; // Default to "General Settings" tab if no session storage

    // Hide all tab content initially
    document.querySelectorAll('.tab-content').forEach(tab => tab.style.display = 'none');

    // Activate the default or session-stored tab
    const activeTabLink = document.querySelector(`.nav-tab[href="${currentTab}"]`);
    if (activeTabLink) {
        activeTabLink.classList.add('nav-tab-active');
        document.querySelector(currentTab).style.display = 'block';
    }

    // Event listeners for tab links
    document.querySelectorAll('.nav-tab').forEach(tabLink => {
        tabLink.addEventListener('click', function(event) {
            event.preventDefault();
            const tabId = this.getAttribute('href');

            // Hide all tabs and remove active classes
            document.querySelectorAll('.tab-content').forEach(tab => tab.style.display = 'none');
            document.querySelectorAll('.nav-tab').forEach(tab => {
                tab.classList.remove('nav-tab-active');
                tab.setAttribute('aria-selected', 'false'); // Update ARIA state
            });

            // Show the clicked tab and update active state
            document.querySelector(tabId).style.display = 'block';
            this.classList.add('nav-tab-active');
            this.setAttribute('aria-selected', 'true'); // Update ARIA state

            // Store the active tab in sessionStorage
            sessionStorage.setItem('activeTab', tabId);

            // Refresh map if on "General Settings" tab
            if (tabId === '#general-settings-tab') {
                wtdp_refreshMap();
            }
        });

        // Set ARIA attributes for accessibility
        tabLink.setAttribute('role', 'tab');
        tabLink.setAttribute('aria-selected', 'false'); // Default state
    });

    function wtdp_hideMessage() {
        const messageDiv = document.getElementById('messageDiv');
        if (messageDiv) {
            setTimeout(() => {
                messageDiv.style.display = 'none';
            }, 3000);
        }
    }

    // Define a variable to hold the map instance
    let map;
    let markers = []; // Store markers in a global array

    const initializeMap = (lat, lon) => {
        const savedLat = document.getElementById('wtdp_latitude').value || lat;
        const savedLon = document.getElementById('wtdp_longitude').value || lon;

        // Create the map instance if it doesn't exist
        if (!map) {
            map = L.map('map').setView([savedLat, savedLon], 13);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; OpenStreetMap contributors'
            }).addTo(map);

            // Add an initial marker
            const initialMarker = L.marker([savedLat, savedLon]).addTo(map);
            markers.push(initialMarker);

            map.on('dblclick', e => {
                // Handle double-click to place a marker
                markers.forEach(marker => map.removeLayer(marker));
                markers.length = 0;

                const cityName = prompt("Please enter the city name:");
                if (cityName) {
                    const { lat, lng } = e.latlng;
                    document.getElementById('wtdp_latitude').value = lat;
                    document.getElementById('wtdp_longitude').value = lng;
                    document.getElementById('wtdp_default_city').value = cityName;
                    const newMarker = L.marker([lat, lng]).addTo(map);
                    markers.push(newMarker);
                }
            });
        } else {
            // Update the map view if it already exists
            map.setView([savedLat, savedLon], 13);

            // Clear existing markers before adding a new one
            markers.forEach(marker => map.removeLayer(marker));
            markers.length = 0;

            const newMarker = L.marker([savedLat, savedLon]).addTo(map);
            markers.push(newMarker);
        }
    };

    // Initialize the map with default coordinates
    initializeMap(51.505, -0.09);

    // Add event listener for the button to fetch new coordinates
    document.getElementById('get-coordinates').addEventListener('click', function() {
        const city = document.getElementById('wtdp_default_city').value;
        const apiKey = wtdp_PluginData.apiKey;

        if (!city) {
            alert('Please enter a city name.');
            return;
        }

        fetch(`https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(city)}&appid=${apiKey}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('City not found or OpenWeather API Key is not set.');
                }
                return response.json();
            })
            .then(data => {
                const { lat, lon } = data.coord;

                if (confirm(`Coordinates for ${city} found:\nLatitude: ${lat}\nLongitude: ${lon}\nDo you want to fill in the latitude and longitude fields?`)) {
                    document.getElementById('wtdp_latitude').value = lat;
                    document.getElementById('wtdp_longitude').value = lon;
                    // Call initializeMap with new coordinates to update the map
                    initializeMap(lat, lon);
                    wtdp_refreshMap(); // Refresh map size if needed
                }
            })
            .catch(error => {
                alert("" + error.message);
            });
    });








    function wtdp_refreshMap() {
        if (map) {
            map.invalidateSize();
        } else {
            console.log('Leaflet onload refresh error. No map.');
        }
    }

    // Confirm action before proceeding
    function wtdp_confirmAction() {
        return confirm("Are you sure you want to perform this action?");
    }

    // Initialize color picker
    jQuery(document).ready(function($) {
        $('.my-color-picker').wpColorPicker({
            alpha: true,
            change: function(event, ui) {
                $(this).val(ui.color.toString());
            }
        });

        $('.latest-color-picker').wpColorPicker({
            alpha: true,
            change: function(event, ui) {
                $(this).val(ui.color.toString());
            }
        });
    });

    // Auto-hide message after 2 seconds
    setTimeout(function() {
        const messageDiv = document.getElementById("messageDiv");
        if (messageDiv) {
            messageDiv.style.display = "none";
        }
    }, 2000); // 2 seconds
});
