// Google Sheets Configuration
// This file connects to your Google Sheet for live data updates

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)
    // If using gid=220881066, you can reference it this way
    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);
        showNotification('Could not fetch data. Check your connection.', 'warning');
        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 immediately on load
    // (already done in initApp)
    
    // Then refresh periodically
    setInterval(async () => {
        console.log('🔄 Refreshing data from Google Sheet...');
        const csvData = await fetchGoogleSheetData();
        
        if (csvData) {
            // Clear old markers
            Object.values(millMarkers).forEach(marker => map.removeLayer(marker));
            millMarkers = {};
            
            // Parse new data
            parseCSV(csvData);
            
            // Render updated mills
            renderMills();
            updateLegend();
            
            // Reapply filters
            applyFilters();
            
            console.log(`✓ Updated ${mills.length} mills from Google Sheet`);
            showNotification(`Map updated with latest data (${mills.length} mills)`, 'success');
        }
    }, 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 Setup Instructions         ║
    ╠════════════════════════════════════════════════════════════╣
    ║                                                            ║
    ║  1. Your Google Sheet is configured and ready!            ║
    ║                                                            ║
    ║  2. Share the sheet with your colleagues:                 ║
    ║     - Click "Share" in the top-right                      ║
    ║     - Add their email addresses                           ║
    ║     - They must have "Editor" access                      ║
    ║                                                            ║
    ║  3. Column headers required (case-sensitive):             ║
    ║     - Mill/Factory Name (or similar)                      ║
    ║     - Country                                             ║
    ║     - Latitude                                            ║
    ║     - Longitude                                           ║
    ║     - Crushing Capacity (optional)                        ║
    ║     - Annual Sugar Production (optional)                  ║
    ║     - Notes (optional)                                    ║
    ║     - Data Year (optional)                                ║
    ║                                                            ║
    ║  4. The map will automatically update every 5 minutes     ║
    ║     with new data from the sheet                          ║
    ║                                                            ║
    ║  5. To change refresh interval, edit:                     ║
    ║     GOOGLE_SHEETS_CONFIG.REFRESH_INTERVAL                 ║
    ║                                                            ║
    ╚════════════════════════════════════════════════════════════╝
    `);
}
