/**
 * youtube.js — YouTube Player
 * מודאל צפייה, ניווט בין סרטונים, IFrame API
 */

let currentYtPlaylist = [];
let currentYtIndex    = -1;
let ytPlayer          = null;
let ytApiReady        = false;
let ytPendingVideoId  = null;

// ─── IFrame API ───────────────────────────────────────────────

function loadYTApi() {
    if (window.YT || document.getElementById('yt-iframe-api-script')) return;
    const tag  = document.createElement('script');
    tag.id     = 'yt-iframe-api-script';
    tag.src    = 'https://www.youtube.com/iframe_api';
    document.head.appendChild(tag);
}

window.onYouTubeIframeAPIReady = function () {
    ytApiReady = true;
    if (ytPendingVideoId !== null) {
        _createYTPlayer(ytPendingVideoId);
        ytPendingVideoId = null;
    }
};

// ─── Extract Video ID ─────────────────────────────────────────

function extractYouTubeVideoId(url) {
    if (!url) return null;
    const patterns = [
        /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/)([A-Za-z0-9_-]{11})/,
        /[?&]v=([A-Za-z0-9_-]{11})/
    ];
    for (const re of patterns) {
        const m = url.match(re);
        if (m) return m[1];
    }
    return null;
}

// ─── Modal ────────────────────────────────────────────────────

function openYTModal(videoId, title) {
    loadYTApi();

    let modal = document.getElementById('ytModal');
    if (!modal) {
        modal = document.createElement('div');
        modal.id        = 'ytModal';
        modal.className = 'fixed inset-0 z-[9999] flex items-center justify-center sm:p-4 bg-black/90 backdrop-blur-md';
        modal.innerHTML = `
            <div class="relative w-full max-w-5xl bg-zinc-950 sm:rounded-2xl overflow-hidden shadow-2xl flex flex-col sm:border border-zinc-800"
                 style="height:100svh; max-height:100svh;">

                <!-- Header -->
                <div class="flex items-center justify-between px-3 sm:px-5 py-2.5 sm:py-3 bg-zinc-900 border-b border-zinc-800 flex-shrink-0">
                    <div class="flex-1 min-w-0 pl-2 sm:pl-4">
                        <span id="ytModalTitle" class="text-white text-sm sm:text-base font-medium truncate block" dir="auto"></span>
                    </div>
                    <div class="flex items-center gap-1.5 sm:gap-3 flex-shrink-0" dir="ltr">
                        <button onclick="closeYTModal()" class="text-zinc-400 hover:text-white w-8 h-8 sm:w-10 sm:h-10 rounded-lg hover:bg-zinc-700 transition-colors flex items-center justify-center" title="סגור (Esc)">
                            <i class="fas fa-times text-lg"></i>
                        </button>
                        <div class="w-px h-5 bg-zinc-700 mx-0.5 sm:mx-1"></div>
                        <button id="ytPrevBtn" onclick="navigateYT(1)" class="text-white bg-zinc-800 hover:bg-zinc-700 w-8 h-8 sm:w-10 sm:h-10 rounded-lg disabled:opacity-20 transition-all flex items-center justify-center" title="הקודם">
                            <i class="fas fa-chevron-left text-xs sm:text-sm"></i>
                        </button>
                        <button id="ytNextBtn" onclick="navigateYT(-1)" class="text-white bg-zinc-800 hover:bg-zinc-700 w-8 h-8 sm:w-10 sm:h-10 rounded-lg disabled:opacity-20 transition-all flex items-center justify-center" title="הבא">
                            <i class="fas fa-chevron-right text-xs sm:text-sm"></i>
                        </button>
                        <span id="ytCounter" class="hidden sm:inline-block text-zinc-400 text-xs sm:text-sm font-mono ml-2"></span>
                    </div>
                </div>

                <!-- Video Container — תופס את כל הגובה הנותר -->
                <div class="w-full bg-black relative flex-1 min-h-0" tabindex="0" id="ytPlayerWrapper">
                    <div id="ytPlayerContainer" class="absolute inset-0"></div>
                </div>

                <!-- Autoplay bar -->
                <div id="ytAutoplayBar" class="hidden items-center justify-between px-3 sm:px-5 py-2.5 bg-zinc-900 border-t border-zinc-800 text-xs text-zinc-300 flex-shrink-0">
                    <span id="ytAutoplayMsg" class="flex items-center gap-2 truncate pl-2 min-w-0">
                        <i class="fas fa-forward text-violet-400 flex-shrink-0"></i>
                        <span id="ytAutoplayText" class="truncate"></span>
                    </span>
                    <div class="flex gap-2 flex-shrink-0">
                        <button onclick="_cancelAutoplay()" class="px-3 py-1.5 rounded-lg bg-zinc-700 hover:bg-zinc-600 transition-colors">בטל</button>
                        <button onclick="_playNow()" class="px-3 py-1.5 rounded-lg bg-violet-600 hover:bg-violet-500 transition-colors text-white whitespace-nowrap">הפעל עכשיו</button>
                    </div>
                </div>
            </div>`;
        modal.addEventListener('click', (e) => { if (e.target === modal) closeYTModal(); });
        document.body.appendChild(modal);
    }

    modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';

    // תיקון גובה דינמי — window.innerHeight מחזיר את הגובה האמיתי ללא שורת משימות
    const _setModalHeight = () => {
        const inner = document.getElementById('ytModalInner');
        if (inner) inner.style.height = inner.style.maxHeight = window.innerHeight + 'px';
    };
    _setModalHeight();
    window._ytResizeHandler = _setModalHeight;
    window.addEventListener('resize', window._ytResizeHandler);

    buildYtPlaylist(videoId);
    _loadVideoInPlayer(videoId);
    _updateModalMeta();
}

function closeYTModal() {
    _cancelAutoplay();
    if (window._ytResizeHandler) {
        window.removeEventListener('resize', window._ytResizeHandler);
        window._ytResizeHandler = null;
    }
    const modal = document.getElementById('ytModal');
    if (modal) modal.classList.add('hidden');
    if (ytPlayer) { try { ytPlayer.stopVideo(); } catch(e) {} }
    document.body.style.overflow = '';
}

// ─── Player management ────────────────────────────────────────

function _createYTPlayer(videoId) {
    const container = document.getElementById('ytPlayerContainer');
    if (!container) return;
    container.innerHTML = '<div id="ytPlayerEl"></div>';
    ytPlayer = new YT.Player('ytPlayerEl', {
        width: '100%', height: '100%', videoId,
        playerVars: { autoplay: 1, rel: 0, modestbranding: 1 },
        events: {
            onReady: () => window.focus(),
            onStateChange: _onPlayerStateChange,
        }
    });
}

function _loadVideoInPlayer(videoId) {
    if (!ytApiReady || !window.YT) { ytPendingVideoId = videoId; return; }
    if (ytPlayer) {
        try { ytPlayer.loadVideoById(videoId); return; } catch(e) { ytPlayer = null; }
    }
    _createYTPlayer(videoId);
}

// ─── Autoplay ─────────────────────────────────────────────────

let _autoplayTimeout = null;
const AUTOPLAY_DELAY = 3000;

function _onPlayerStateChange(event) {
    if (event.data === YT.PlayerState.ENDED) _triggerAutoplayNext();
}

function _triggerAutoplayNext() {
    if (currentYtIndex === -1 || currentYtIndex >= currentYtPlaylist.length - 1) return;
    const nextItem = currentYtPlaylist[currentYtIndex + 1];
    const bar  = document.getElementById('ytAutoplayBar');
    const text = document.getElementById('ytAutoplayText');
    if (!bar || !text) { navigateYT(1); return; }

    bar.classList.remove('hidden');
    bar.classList.add('flex');

    let remaining = Math.ceil(AUTOPLAY_DELAY / 1000);
    text.textContent = `"${nextItem.title}" בעוד ${remaining} שניות...`;

    const tick = setInterval(() => {
        remaining--;
        text.textContent = `"${nextItem.title}" בעוד ${remaining} שניות...`;
    }, 1000);

    _autoplayTimeout = setTimeout(() => {
        clearInterval(tick);
        _hideAutoplayBar();
        navigateYT(1);
    }, AUTOPLAY_DELAY);
    _autoplayTimeout._tick = tick;
}

function _playNow() {
    if (_autoplayTimeout) { clearInterval(_autoplayTimeout._tick); clearTimeout(_autoplayTimeout); _autoplayTimeout = null; }
    _hideAutoplayBar();
    navigateYT(1);
}

function _cancelAutoplay() {
    if (_autoplayTimeout) { clearInterval(_autoplayTimeout._tick); clearTimeout(_autoplayTimeout); _autoplayTimeout = null; }
    _hideAutoplayBar();
}

function _hideAutoplayBar() {
    const bar = document.getElementById('ytAutoplayBar');
    if (bar) { bar.classList.add('hidden'); bar.classList.remove('flex'); }
}

// ─── Playlist ─────────────────────────────────────────────────

function buildYtPlaylist(currentId) {
    currentYtPlaylist = [];
    currentYtIndex    = -1;

    // 1. ננסה קודם להשתמש ברשימה המלאה מהזיכרון (כדי לעקוף את מגבלת 60 הסרטונים של ה-Virtual Scroll)
    const fullList = (typeof vsState !== 'undefined' && vsState?.allEpisodes);
    if (fullList && fullList.length > 0) {
        fullList.forEach((ep, index) => {
            const vid   = (typeof extractYouTubeVideoId === 'function'
                ? extractYouTubeVideoId(ep.audioUrl) || extractYouTubeVideoId(ep.guid)
                : null) || ep.guid || '';
            const title = ep.title || '';
            if (!vid) return;
            currentYtPlaylist.push({ vid, title });
            if (currentYtIndex === -1 && vid === currentId) currentYtIndex = currentYtPlaylist.length - 1;
        });
    }

    // 2. אם הסרטון לא נמצא ברשימה המלאה (למשל, אנחנו בחיפוש גלובלי או מועדפים), 
    // ניקח את הסרטונים מתוך ה-HTML, אבל נוודא שניקח רק מתוך הקונטיינר שגלוי כרגע!
    if (currentYtIndex === -1) {
        currentYtPlaylist = []; // איפוס ובנייה מחדש מה-DOM
        
        let activeContainer = document.body;
        const globalSearch = document.getElementById('globalSearchResults');
        
        if (globalSearch && !globalSearch.classList.contains('hidden')) {
            activeContainer = globalSearch; // אנחנו במצב חיפוש
        } else {
            const videosList = document.getElementById('videosList');
            if (videosList) activeContainer = videosList; // אנחנו ברשימה רגילה
        }

        const nodes = activeContainer.querySelectorAll('[data-vid]');
        nodes.forEach((node, index) => {
            const vid   = node.dataset.vid;
            const title = node.dataset.title || '';
            if (!vid) return;
            currentYtPlaylist.push({ vid, title });
            if (currentYtIndex === -1 && vid === currentId) currentYtIndex = index;
        });
    }

    updateNavButtons();
    _updateCounter();
}

// ─── Navigation ───────────────────────────────────────────────

function navigateYT(direction) {
    if (currentYtIndex === -1) return;
    const newIndex = currentYtIndex + direction;
    if (newIndex < 0 || newIndex >= currentYtPlaylist.length) return;
    _cancelAutoplay();
    currentYtIndex = newIndex;
    _loadVideoInPlayer(currentYtPlaylist[newIndex].vid);
    _updateModalMeta();
    updateNavButtons();
    _updateCounter();
    window.focus();
}

function _updateModalMeta() {
    const item = currentYtPlaylist[currentYtIndex];
    if (!item) return;
    const titleEl = document.getElementById('ytModalTitle');
    if (titleEl) titleEl.textContent = item.title;
}

function updateNavButtons() {
    const prevBtn = document.getElementById('ytPrevBtn'); // chevron-right → navigateYT(1) → סרטון ישן יותר
    const nextBtn = document.getElementById('ytNextBtn'); // chevron-left  → navigateYT(-1) → סרטון חדש יותר
    if (prevBtn) prevBtn.disabled = currentYtIndex === -1 || currentYtIndex >= currentYtPlaylist.length - 1;
    if (nextBtn) nextBtn.disabled = currentYtIndex <= 0;
}

function _updateCounter() {
    const counter = document.getElementById('ytCounter');
    if (!counter) return;
    if (currentYtIndex === -1 || currentYtPlaylist.length === 0) { counter.textContent = ''; return; }
    counter.textContent = `${currentYtIndex + 1} / ${currentYtPlaylist.length}`;
}

// ─── Keyboard ─────────────────────────────────────────────────

document.addEventListener('keydown', (e) => {
    const modal = document.getElementById('ytModal');
    if (!modal || modal.classList.contains('hidden')) return;
    if      (e.key === 'ArrowLeft')  navigateYT(1);
    else if (e.key === 'ArrowRight') navigateYT(-1);
    else if (e.key === 'Escape')     closeYTModal();
});

window.addEventListener('blur', () => {
    const modal = document.getElementById('ytModal');
    if (!modal || modal.classList.contains('hidden')) return;
    requestAnimationFrame(() => window.focus());
});