// Map initialization and management
import { CONFIG } from './config.js';
import { showStatus } from './utils.js';
import { currentUser } from './auth.js';

export let map = null;
export let startLocationMarker = null;
export let isStartLocationVisible = true;

export async function initializeMap() {
    try {
        // Get start location from PUBLIC endpoint (not admin endpoint)
        const response = await fetch('/api/settings/start-location'); // Changed from /api/config/start-location
        const data = await response.json();
        
        let startLat = CONFIG.DEFAULT_LAT;
        let startLng = CONFIG.DEFAULT_LNG;
        let startZoom = CONFIG.DEFAULT_ZOOM;
        
        if (data.success && data.location) {
            startLat = data.location.latitude;
            startLng = data.location.longitude;
            startZoom = data.location.zoom;
        }
        
        // Initialize map
        map = L.map('map').setView([startLat, startLng], startZoom);
        
        // Add tile layer
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
            maxZoom: CONFIG.MAX_ZOOM,
            minZoom: CONFIG.MIN_ZOOM
        }).addTo(map);
        
        // Add start location marker
        addStartLocationMarker(startLat, startLng);
        
        console.log('Map initialized successfully');
        
    } catch (error) {
        console.error('Failed to initialize map:', error);
        showStatus('Failed to initialize map', 'error');
    }
}

function addStartLocationMarker(lat, lng) {
    console.log(`Adding start location marker at: ${lat}, ${lng}`);
    
    // Remove existing start location marker if it exists
    if (startLocationMarker) {
        map.removeLayer(startLocationMarker);
    }
    
    // Create a very distinctive custom icon
    const startIcon = L.divIcon({
        html: `
            <div class="start-location-marker-wrapper">
                <div class="start-location-marker-pin">
                    <div class="start-location-marker-inner">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="white">
                            <path d="M12 2L2 7v10c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V7l-10-5z"/>
                        </svg>
                    </div>
                </div>
                <div class="start-location-marker-pulse"></div>
            </div>
        `,
        className: 'start-location-custom-marker',
        iconSize: [48, 48],
        iconAnchor: [24, 48],
        popupAnchor: [0, -48]
    });
    
    // Create the marker
    startLocationMarker = L.marker([lat, lng], {
        icon: startIcon,
        zIndexOffset: 1000
    }).addTo(map);
    
    // Add popup
    startLocationMarker.bindPopup(`
        <div class="popup-content start-location-popup-enhanced">
            <h3>📍 Map Start Location</h3>
            <p>This is todays starting location!</p>
            ${currentUser?.isAdmin ? '<p><a href="/admin.html">Edit in Admin Panel</a></p>' : ''}
        </div>
    `);
}

export function toggleStartLocationVisibility() {
    if (!startLocationMarker) return;
    
    isStartLocationVisible = !isStartLocationVisible;
    
    if (isStartLocationVisible) {
        map.addLayer(startLocationMarker);
        // Update both desktop and mobile button text
        const desktopBtn = document.querySelector('#toggle-start-location-btn .btn-text');
        if (desktopBtn) desktopBtn.textContent = 'Hide Start Location';
    } else {
        map.removeLayer(startLocationMarker);
        // Update both desktop and mobile button text
        const desktopBtn = document.querySelector('#toggle-start-location-btn .btn-text');
        if (desktopBtn) desktopBtn.textContent = 'Show Start Location';
    }
}
