// Google Sheets Configuration for GeoJSON Viewer
// This file connects to the Google Sheet for live mills data

const GOOGLE_SHEETS_CONFIG = {
    // Your Google Sheet ID (from the URL)
    SHEET_ID: '1ZHEIyhupNDHVd1EScBn0DnuiAzMFoZcAPZm3U65abkY',
    
    // The sheet name or gid (the sheet tab you want to read from)
    SHEET_NAME: 'Sheet1', // Change this to your actual sheet name if different
    
    // Auto-refresh interval in milliseconds (5 minutes = 300000ms)
    REFRESH_INTERVAL: 300000,
    
    // Enable auto-refresh (set to false to disable)
    AUTO_REFRESH_ENABLED: true
};

/**
 * Fetch data from Google Sheet via Netlify Function
 * The function keeps credentials secret on the server
 */
async function fetchGoogleSheetData() {
    try {
        // Call Netlify function instead of Google Sheets directly
        // This keeps the Sheet ID and password hidden from browser dev tools
        const response = await fetch('/.netlify/functions/get-mills');
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const csvText = await response.text();
        console.log('✓ Data fetched from Netlify Function (Google Sheet)');
        return csvText;
    } catch (error) {
        console.error('Error fetching data from Netlify Function:', error);
        return null;
    }
}

/**
 * Initialize auto-refresh of data from Google Sheet
 */
function initGoogleSheetsAutoRefresh() {
    if (!GOOGLE_SHEETS_CONFIG.AUTO_REFRESH_ENABLED) {
        console.log('Google Sheets auto-refresh is disabled');
        return;
    }
    
    console.log(`✓ Auto-refresh enabled (every ${GOOGLE_SHEETS_CONFIG.REFRESH_INTERVAL / 1000 / 60} minutes)`);
    
    // Refresh periodically
    setInterval(async () => {
        console.log('🔄 Refreshing mills data from Google Sheet...');
        const csvData = await fetchGoogleSheetData();
        
        if (csvData && millsToggle && millsToggle.checked) {
            // Parse new data
            mills = parseMillsCSV(csvData);
            
            // Render updated mills if layer is visible
            if (millsLayer && map.hasLayer(millsLayer)) {
                renderMills();
            }
            
            console.log(`✓ Updated ${mills.length} mills from Google Sheet`);
        }
    }, GOOGLE_SHEETS_CONFIG.REFRESH_INTERVAL);
}

/**
 * Show notification to user
 */
function showNotification(message, type = 'info') {
    const colors = {
        'success': '#4CAF50',
        'warning': '#FF9800',
        'error': '#F44336',
        'info': '#2196F3'
    };
    
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${colors[type] || colors.info};
        color: white;
        padding: 15px 20px;
        border-radius: 5px;
        z-index: 9999;
        box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        font-weight: 500;
    `;
    notification.textContent = message;
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.transition = 'opacity 0.3s ease';
        notification.style.opacity = '0';
        setTimeout(() => notification.remove(), 300);
    }, 4000);
}

/**
 * Provide setup instructions to the user
 */
function showGoogleSheetsSetup() {
    console.log(`
    ╔════════════════════════════════════════════════════════════╗
    ║   Google Sheets Integration for GeoJSON Viewer Mills       ║
    ╠════════════════════════════════════════════════════════════╣
    ║                                                            ║
    ║  1. Sugar mills data is configured and ready!             ║
    ║                                                            ║
    ║  2. The map will automatically update every 5 minutes      ║
    ║     with new data from the Google Sheet                    ║
    ║                                                            ║
    ║  3. To change refresh interval, edit:                      ║
    ║     GOOGLE_SHEETS_CONFIG.REFRESH_INTERVAL                  ║
    ║                                                            ║
    ║  4. Column headers required (case-sensitive):              ║
    ║     - Mill/Factory                                         ║
    ║     - Country                                              ║
    ║     - Latitude                                             ║
    ║     - Longitude                                            ║
    ║     - Crushing Capacity (tons/year)                        ║
    ║     - Annual Sugar Production (tons)                       ║
    ║     - Province/Region                                      ║
    ║     - Company                                              ║
    ║     - Data Year                                            ║
    ║                                                            ║
    ╚════════════════════════════════════════════════════════════╝
    `);
}
