/**
 * Scans the available time slots in the French HTML structure, including pagination through months.
 *
 * @returns {Promise<Object>} A Promise that resolves with an object where keys are
 *                            date strings (YYYY-MM-DD) and values are objects.
 *                            The nested objects have time strings (HH:mm) as keys
 *                            and objects containing 'standard' and 'pta' buttons
 *                            (or null if not available) as values.
 *                            Example:
 *                            {
 *                                "2025-07-02": {
 *                                    "07:00": { standard: ButtonElement, pta: ButtonElement },
 *                                    "07:30": { standard: ButtonElement, pta: null }
 *                                },
 *                                "2025-07-03": { ... }
 *                            }
 */
async function scrapeTimeSlotsFr() {
    const allTimeSlots = {};
    
    // Month name mapping for parsing dates
    const monthMap = {
        "january": 0, "february": 1, "march": 2, "april": 3, "may": 4, "june": 5,
        "july": 6, "august": 7, "september": 8, "october": 9, "november": 10, "december": 11,
        "janvier": 0, "février": 1, "mars": 2, "avril": 3, "mai": 4, "juin": 5,
        "juillet": 6, "août": 7, "septembre": 8, "octobre": 9, "novembre": 10, "décembre": 11
    };

    /**
     * Parse date and time from aria-label text
     * @param {string} ariaLabel - The aria-label text from the button
     * @returns {Object} Object containing date, time, and slot type
     */
    function parseAriaLabel(ariaLabel) {
        try {
            // Example: "Wednesday, July 2, 2025 at 07:00 AM, Prime Time appointment, Premium lounge unavailable"
            const parts = ariaLabel.split(' at ');
            if (parts.length < 2) {
                console.warn(`Could not parse aria-label: ${ariaLabel}`);
                return null;
            }

            // Parse date part: "Wednesday, July 2, 2025"
            const datePart = parts[0].trim();
            const dateMatch = datePart.match(/(\w+),\s+(\w+)\s+(\d+),\s+(\d{4})/);
            
            if (!dateMatch) {
                console.warn(`Could not parse date from: ${datePart}`);
                return null;
            }

            const [, dayName, monthName, day, year] = dateMatch;
            const monthIndex = monthMap[monthName.toLowerCase()];
            
            if (monthIndex === undefined) {
                console.warn(`Unknown month: ${monthName}`);
                return null;
            }

            // Create date object and format as YYYY-MM-DD
            const date = new Date(parseInt(year), monthIndex, parseInt(day), 3);
            const formattedDate = date.toISOString().split('T')[0];

            // Parse time part: "07:00 AM, Prime Time appointment, Premium lounge unavailable"
            const timePart = parts[1].trim();
            const timeMatch = timePart.match(/(\d{1,2}):(\d{2})\s+(AM|PM)/);
            
            if (!timeMatch) {
                console.warn(`Could not parse time from: ${timePart}`);
                return null;
            }

            let [, hours, minutes, period] = timeMatch;
            hours = parseInt(hours);
            
            // Convert to 24-hour format
            if (period === 'PM' && hours !== 12) {
                hours += 12;
            } else if (period === 'AM' && hours === 12) {
                hours = 0;
            }
            
            const formattedTime = `${hours.toString().padStart(2, '0')}:${minutes}`;

            // Determine slot type from the aria-label
            let slotType = 'standard';
            if (ariaLabel.includes('Prime Time appointment')) {
                slotType = 'pta';
            }

            return {
                date: formattedDate,
                time: formattedTime,
                type: slotType
            };
        } catch (error) {
            console.error(`Error parsing aria-label: ${ariaLabel}`, error);
            return null;
        }
    }

    /**
     * Process all slots on the current page
     */
    function processCurrentPage() {
        const slots = document.querySelectorAll('button[data-testid="btn-add-appointment-slot"]:not(:disabled)');
        
        for (const slot of slots) {
            const ariaLabel = slot.getAttribute('aria-label');
            if (!ariaLabel) {
                console.warn('Button without aria-label found');
                continue;
            }

            const parsed = parseAriaLabel(ariaLabel);
            if (!parsed) {
                continue;
            }

            const { date, time, type } = parsed;

            // Initialize the date entry if it doesn't exist
            if (!allTimeSlots[date]) {
                allTimeSlots[date] = {};
            }

            // Initialize the time entry if it doesn't exist
            if (!allTimeSlots[date][time]) {
                allTimeSlots[date][time] = { standard: null, pta: null };
            }

            // Store the button element
            allTimeSlots[date][time][type] = slot;
        }
    }

    // Process the first month (current page)
    processCurrentPage();

    // Get all month buttons for pagination
    const monthButtons = document.querySelectorAll('button[data-testid="btn-month-selector"]:not(:disabled)');
    
    // Start from the second month button (index 1) since we've already processed the first month
    for (let i = 1; i < monthButtons.length; i++) {
        break;
        try {
            // Click the month button
            monthButtons[i].click();
            
            // Wait for the page to load new content
            await new Promise(resolve => setTimeout(resolve, 5000)); // Wait 800ms for content to load
            
            // Process the slots on this new month page
            processCurrentPage();
            
        } catch (error) {
            console.error(`Error clicking month button ${i}:`, error);
            break; // Stop pagination if there's an error
        }
    }

    return allTimeSlots;
}

// Example usage:
// scrapeTimeSlotsFr().then(slots => {
//     console.log('All time slots:', slots);
// });


async function checkAppointmentFr(centerName, groupId) {
    try {
        // Get access token from localStorage
        const accessToken = localStorage.getItem('access_token');
        if (!accessToken) {
            console.error('Access token not found in localStorage');
            return null;
        }

        // Generate start date (first day of current month in YYYYMMDD format)
        var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
        var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);
        const startDate = localISOTime.split('T')[0].replace(/-/g, '');
        // Construct the dynamic URL
        const baseUrl = 'https://citizen.visas-fr.tlscontact.com';
        const url = `${baseUrl}/v2/groups/${groupId}/bookings/available-slots?start=${startDate}&labels=pta,premium,walkin,pv,spv,ptaw&location=${centerName}`;

        console.log('Making request to:', url);

        const response = await fetch(url, {
            headers: {
                "accept": "application/json, text/plain, */*",
                "accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7",
                "authorization": `Bearer ${accessToken}`,
                "cache-control": "no-cache",
                "pragma": "no-cache",
                "priority": "u=1, i",
                "sec-ch-ua": "\"Google Chrome\";v=\"137\", \"Chromium\";v=\"137\", \"Not/A)Brand\";v=\"24\"",
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": "\"macOS\"",
                "sec-fetch-dest": "empty",
                "sec-fetch-mode": "cors",
                "sec-fetch-site": "same-site",
                "Referer": "https://visas-fr.tlscontact.com/",
                "Referrer-Policy": "strict-origin-when-cross-origin"
            },
            body: null,
            method: "GET"
        });

        if (!response.ok) {
            console.error(`HTTP error! status: ${response.status}`);
            if (response.status === 401) {
                return 401
            }
            return null;
        }

        const data = await response.json();
        console.log('Appointment data received:', data);
        return data;

    } catch (error) {
        console.error('Error fetching appointment data:', error);
        return null;
    }
}

// Example usage:
// checkAppointmentFr('gbLON2fr', '20169720').then(data => {
//     console.log('Available slots:', data);
// });
// data = await checkAppointmentFr('gbLON2fr', '20169720')

async function checkBookingsFr(groupId) {
    const accessToken = localStorage.getItem('access_token');
    if (!accessToken) {
        console.error('Access token not found in localStorage');
        return null;
    }
    // Construct the dynamic URL
    const baseUrl = 'https://citizen.visas-fr.tlscontact.com';
    const url = `${baseUrl}/groups/${groupId}/bookings`;
    console.log('Making request to:', url);

    const response = await fetch(url, {
        "headers": {
            "accept": "application/json, text/plain, */*",
            "accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7",
            "authorization": `Bearer ${accessToken}`,
            "cache-control": "no-cache",
            "pragma": "no-cache",
            "priority": "u=1, i",
            "sec-ch-ua": "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"macOS\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "Referer": "https://visas-fr.tlscontact.com/"
        },
        "body": null,
        "method": "GET"
    });
    if (!response.ok) {
        console.error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log('Booking data received:', data);
    return data;
}


window.scrapeTimeSlotsFr = scrapeTimeSlotsFr;
window.checkAppointmentFr = checkAppointmentFr;
window.checkBookingsFr = checkBookingsFr;