/**
 * Fetch videos from YouTube channel RSS feed
 * @param {string} channelId - YouTube channel ID
 * @param {number} limit - Maximum number of videos to return (default: 15, max: 15)
 * @returns {Promise<Array>} Array of video objects
 */
export async function fetchYouTubeVideos(channelId, limit = 15) {
    const RSS_URL = `https://www.youtube.com/feeds/videos.xml?channel_id=${channelId}`;

    // Try multiple CORS proxies for better reliability
    const CORS_PROXIES = [
        'https://corsproxy.io/?',
        'https://api.allorigins.win/raw?url=',
    ];

    for (const proxy of CORS_PROXIES) {
        try {
            const response = await fetch(proxy + encodeURIComponent(RSS_URL), {
                headers: {
                    'Accept': 'application/xml, text/xml, */*',
                },
            });

            if (!response.ok) {
                console.warn(`Proxy ${proxy} failed with status ${response.status}`);
                continue;
            }

            const xmlText = await response.text();

            if (typeof window !== 'undefined') {
                const parser = new DOMParser();
                const xmlDoc = parser.parseFromString(xmlText, 'text/xml');

                // Parse XML entries
                const entries = xmlDoc.querySelectorAll('entry');
                const videos = [];

                entries.forEach((entry, index) => {
                    if (index >= limit) return;

                    const videoId = entry.querySelector('videoId')?.textContent ||
                        entry.querySelector('yt\\:videoId')?.textContent;
                    const title = entry.querySelector('title')?.textContent;
                    const published = entry.querySelector('published')?.textContent;

                    if (videoId && title) {
                        videos.push({
                            id: videoId,
                            videoId: videoId,
                            title: title,
                            thumbnail: `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`,
                            publishedAt: published
                        });
                    }
                });

                if (videos.length > 0) {
                    return videos;
                }
            }
        } catch (error) {
            console.warn(`Error with proxy ${proxy}:`, error);
            continue;
        }
    }

    // If all proxies fail, return empty array
    console.error('All CORS proxies failed to fetch YouTube videos');
    return [];
}
