/**
 * Reglas de negocio: enlaces YouTube (watch, Shorts, youtu.be, embed) → ID y embed videowallpaper.
 */
(function (global) {
    'use strict';

    function normalizeUrlInput(url) {
        if (!url || typeof url !== 'string') return '';
        const trimmed = url.trim();
        if (!trimmed) return '';
        return /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
    }

    function extractYoutubeId(url) {
        const raw = normalizeUrlInput(url);
        if (!raw) return null;

        try {
            const parsed = new URL(raw);
            let host = parsed.hostname.toLowerCase().replace(/^(www\.|m\.)/, '');
            if (['youtube.com', 'youtu.be', 'youtube-nocookie.com'].includes(host)) {
                const path = parsed.pathname;
                const shorts = path.match(/^\/shorts\/([a-zA-Z0-9_-]{11})/);
                if (shorts) return shorts[1];
                const pathId = path.match(/^\/(embed|v|live)\/([a-zA-Z0-9_-]{11})/);
                if (pathId) return pathId[2];
                if (/^\/watch/.test(path)) {
                    const v = parsed.searchParams.get('v');
                    if (v && /^[a-zA-Z0-9_-]{11}$/.test(v)) return v;
                }
                if (host === 'youtu.be') {
                    const id = path.replace(/^\//, '').split('/')[0].split('?')[0];
                    if (/^[a-zA-Z0-9_-]{11}$/.test(id)) return id;
                }
            }
        } catch (_) {
            /* fallback regex */
        }

        const patterns = [
            /(?:youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/i,
            /(?:youtube\.com\/(?:embed|v|live)\/)([a-zA-Z0-9_-]{11})/i,
            /(?:youtu\.be\/)([a-zA-Z0-9_-]{11})/i,
            /(?:[?&]v=)([a-zA-Z0-9_-]{11})/i,
        ];
        for (const re of patterns) {
            const m = raw.match(re);
            if (m) return m[1];
        }
        return null;
    }

    function isValidYoutubeUrl(url) {
        return extractYoutubeId(url) !== null;
    }

    function getPageOrigin() {
        try {
            if (typeof global.location !== 'undefined' && global.location.origin) {
                return global.location.origin;
            }
        } catch (_) {
            /* ignore */
        }
        return '';
    }

    function buildYoutubeWallpaperEmbedUrl(urlOrId) {
        const id =
            typeof urlOrId === 'string' &&
            /^[a-zA-Z0-9_-]{11}$/.test(urlOrId) &&
            !urlOrId.includes('/')
                ? urlOrId
                : extractYoutubeId(urlOrId);
        if (!id) return null;
        const params = new URLSearchParams({
            autoplay: '1',
            mute: '1',
            loop: '1',
            playlist: id,
            controls: '0',
            modestbranding: '1',
            rel: '0',
            playsinline: '1',
            enablejsapi: '1',
        });
        const origin = getPageOrigin();
        if (origin) {
            params.set('origin', origin);
        }
        // youtube-nocookie + origin evita Error 153 con Referrer-Policy restrictiva del sitio.
        return `https://www.youtube-nocookie.com/embed/${id}?${params.toString()}`;
    }

    /** Atributos obligatorios en iframes wallpaper (Error 153 si faltan). */
    function applyYoutubeWallpaperIframeAttrs(iframe) {
        if (!iframe) return iframe;
        iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');
        iframe.setAttribute('frameborder', '0');
        iframe.setAttribute('allow', 'autoplay; fullscreen; encrypted-media');
        iframe.setAttribute('allowfullscreen', '');
        return iframe;
    }

    function youtubeWallpaperIframeHtml(embedSrc, extraAttrs) {
        const attrs = extraAttrs || '';
        return `<iframe src="${embedSrc}" referrerpolicy="strict-origin-when-cross-origin" frameborder="0" allow="autoplay; fullscreen; encrypted-media" allowfullscreen ${attrs}></iframe>`;
    }

    global.GridYoutubeUrl = {
        normalizeUrlInput,
        extractYoutubeId,
        isValidYoutubeUrl,
        buildYoutubeWallpaperEmbedUrl,
        applyYoutubeWallpaperIframeAttrs,
        youtubeWallpaperIframeHtml,
    };
})(typeof window !== 'undefined' ? window : global);
