/**
 * Centralized Mapbox Configuration
 *
 * This configuration ensures all globe visualizations use a valid token
 * and provides helpful validation and debugging.
 */

export const MAPBOX_CONFIG = {
    // Primary working token (from globe_14)
    accessToken: 'pk.eyJ1IjoibGludXhpc2Nvb2wiLCJhIjoiY2w3ajM1MnliMDV4NDNvb2J5c3V5dzRxZyJ9.wJukH5hVSiO74GM_VSJR3Q',

    /**
     * Validate that the token is properly configured
     * @returns {boolean} True if token is valid, false otherwise
     */
    validateToken() {
        if (!this.accessToken) {
            console.error('❌ MAPBOX TOKEN ERROR: No token configured!');
            console.error('Please set MAPBOX_CONFIG.accessToken in mapbox-config.js');
            return false;
        }

        // Check for placeholder tokens
        const placeholders = ['yourtokenstring', 'YOUR_TOKEN', 'yourtoken', 'yourusername'];
        const hasPlaceholder = placeholders.some(p => this.accessToken.includes(p));

        if (hasPlaceholder) {
            console.error('❌ MAPBOX TOKEN ERROR: Invalid placeholder token detected!');
            console.error('Current token:', this.accessToken);
            console.error('This token will not work. Please use a real Mapbox access token.');
            console.error('Get a free token at: https://account.mapbox.com/');
            return false;
        }

        // Check token format (should start with pk.)
        if (!this.accessToken.startsWith('pk.')) {
            console.warn('⚠️ MAPBOX TOKEN WARNING: Token does not start with "pk."');
            console.warn('This may not be a valid public token.');
        }

        console.log('✅ Mapbox token validated successfully');
        return true;
    },

    /**
     * Apply token to Mapbox GL JS
     * @returns {boolean} True if successful, false if validation failed
     */
    applyToken() {
        if (!this.validateToken()) {
            // Show user-friendly error in the page
            this.showTokenError();
            return false;
        }

        if (typeof mapboxgl !== 'undefined') {
            mapboxgl.accessToken = this.accessToken;
            console.log('✅ Mapbox token applied to mapboxgl');
            return true;
        } else {
            console.error('❌ ERROR: mapboxgl library not loaded!');
            console.error('Make sure Mapbox GL JS script is loaded before this configuration.');
            return false;
        }
    },

    /**
     * Show a user-friendly error message on the page
     */
    showTokenError() {
        const errorDiv = document.createElement('div');
        errorDiv.id = 'mapbox-token-error';
        errorDiv.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(220, 38, 38, 0.95);
            color: white;
            padding: 30px 40px;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
            max-width: 500px;
            z-index: 10000;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        `;

        errorDiv.innerHTML = `
            <h2 style="margin: 0 0 15px 0; font-size: 24px;">⚠️ Mapbox Token Error</h2>
            <p style="margin: 0 0 10px 0; line-height: 1.6;">
                This visualization requires a valid Mapbox access token to display the globe.
            </p>
            <p style="margin: 0 0 15px 0; line-height: 1.6; font-size: 14px;">
                <strong>To fix this:</strong><br>
                1. Visit <a href="https://account.mapbox.com/" target="_blank" style="color: #fbbf24; text-decoration: underline;">account.mapbox.com</a><br>
                2. Create a free account (50,000 map loads/month)<br>
                3. Copy your access token<br>
                4. Update <code>shared/mapbox-config.js</code>
            </p>
            <button onclick="this.parentElement.remove()" style="
                background: white;
                color: #dc2626;
                border: none;
                padding: 10px 20px;
                border-radius: 6px;
                font-weight: 600;
                cursor: pointer;
            ">Dismiss</button>
        `;

        document.body.appendChild(errorDiv);
    },

    /**
     * Common map initialization options for globe visualizations
     */
    defaultMapOptions: {
        projection: 'globe',
        zoom: 1.5,
        center: [20, 20],
        pitch: 0,
        attributionControl: true
    },

    /**
     * Get map options merged with defaults
     * @param {Object} customOptions - Custom options to override defaults
     * @returns {Object} Merged map options
     */
    getMapOptions(customOptions = {}) {
        return {
            ...this.defaultMapOptions,
            ...customOptions,
            style: customOptions.style || 'mapbox://styles/mapbox/dark-v11'
        };
    }
};

/**
 * Auto-apply token when module loads (if mapboxgl is available)
 */
if (typeof mapboxgl !== 'undefined') {
    MAPBOX_CONFIG.applyToken();
}

// Also make available globally for non-module scripts
if (typeof window !== 'undefined') {
    window.MAPBOX_CONFIG = MAPBOX_CONFIG;
}
