/**
 * favorites.js — YouTube Player
 * מועדפים עם חלוקה לפי ערוץ וקטגוריה
 */

let favoritesGroupBy = 'channel'; // 'channel' | 'category' | 'date'

// ─── localStorage ─────────────────────────────────────────────

function getFavorites() {
    try {
        const favs = JSON.parse(localStorage.getItem('yt_favorites') || '[]');
        let needsSave = false;
        favs.forEach(f => {
            ['channelTitle', 'channelImage', 'categoryName'].forEach(key => {
                if (f[key] && f[key].includes('%')) {
                    try { f[key] = decodeURIComponent(f[key]); needsSave = true; } catch(e) {}
                }
            });
        });
        if (needsSave) localStorage.setItem('yt_favorites', JSON.stringify(favs));
        return favs;
    } catch(e) { return []; }
}

function saveFavorites(favs) {
    try { localStorage.setItem('yt_favorites', JSON.stringify(favs)); } catch(e) {}
    updateFavBadge();
}

// ─── Badge ───────────────────────────────────────────────────

function updateFavBadge() {
    const favs  = getFavorites();
    const badge = document.getElementById('favBadge');
    if (!badge) return;
    if (favs.length > 0) {
        badge.textContent = favs.length > 99 ? '99+' : favs.length;
        badge.style.display = 'inline-flex';
    } else {
        badge.style.display = 'none';
    }
}

// ─── Identity ─────────────────────────────────────────────────

function getEpisodeId(ep) {
    return (ep.guid || ep.audioUrl || ep.title || '').toString().trim();
}

function isFavorite(epId) {
    return getFavorites().some(f => f.id === epId);
}

// ─── Toggle ──────────────────────────────────────────────────

function toggleFavorite(ep, channelTitle, channelImage, categoryName, btn) {
    try { channelTitle  = decodeURIComponent(channelTitle);  } catch(e) {}
    try { channelImage  = decodeURIComponent(channelImage);  } catch(e) {}
    try { categoryName  = decodeURIComponent(categoryName);  } catch(e) {}

    const epId  = getEpisodeId(ep);
    let   favs  = getFavorites();
    const idx   = favs.findIndex(f => f.id === epId);
    const ytId  = extractYouTubeVideoId(ep.audioUrl) || extractYouTubeVideoId(ep.guid);

    if (idx === -1) {
        favs.unshift({
            id:           epId,
            title:        ep.title,
            description:  ep.description || '',
            image:        ep.image || channelImage || '',
            pubDate:      ep.pubDate  || '',
            duration:     ep.duration || '',
            audioUrl:     ep.audioUrl || '',
            guid:         ep.guid    || '',
            channelTitle,
            channelImage: channelImage || '',
            categoryName: categoryName || '',
            ytVideoId:    ytId || null,
            savedAt:      new Date().toISOString()
        });
        setStarActive(btn, true);
        if (typeof showToast === 'function') showToast('נוסף למועדפים ⭐', 'success');
    } else {
        favs.splice(idx, 1);
        setStarActive(btn, false);
        if (typeof showToast === 'function') showToast('הוסר ממועדפים', 'info');
    }
    saveFavorites(favs);
}

function setStarActive(btn, active) {
    if (!btn) return;
    const icon = btn.querySelector('i');
    if (active) {
        if (icon) icon.className = 'fas fa-star text-amber-400 text-xs transition-all duration-200';
    } else {
        if (icon) icon.className = 'far fa-star text-zinc-400 text-xs transition-all duration-200';
    }
}

// ─── View ────────────────────────────────────────────────────

function showFavoritesView() {
    document.getElementById('viewDashboard').classList.add('hidden');
    document.getElementById('viewChannel').classList.add('hidden');
    document.getElementById('viewUpdates')?.classList.add('hidden');
    document.getElementById('viewFavorites').classList.remove('hidden');

    _setActiveGroupBtn(favoritesGroupBy);
    renderFavoritesList();
    window.scrollTo(0, 0);
}

function setFavGroupBy(mode) {
    favoritesGroupBy = mode;
    _setActiveGroupBtn(mode);
    renderFavoritesList();
}

function _setActiveGroupBtn(mode) {
    document.querySelectorAll('.fav-group-btn').forEach(b => {
        const isActive = b.dataset.group === mode;
        b.style.cssText = isActive
            ? 'background:rgba(245,158,11,0.15); color:#f59e0b; border-color:rgba(245,158,11,0.35); font-weight:700;'
            : 'background:var(--bg-card); color:var(--text-secondary); border-color:var(--border); font-weight:600;';
    });
}

function clearAllFavorites() {
    if (!confirm('למחוק את כל המועדפים?')) return;
    saveFavorites([]);
    renderFavoritesList();
}

function removeFavoriteById(epId) {
    const favs = getFavorites().filter(f => f.id !== epId);
    saveFavorites(favs);
    renderFavoritesList();
    document.querySelectorAll('.fav-star-btn').forEach(btn => {
        if (btn.dataset.favId === epId) setStarActive(btn, false);
    });
}

// ─── Favorites Playlist ───────────────────────────────────────

/**
 * פותח סרטון ממועדפים — בונה פלייליסט מהסרטונים של אותו ערוץ במועדפים
 */
function openFavVideo(ytVideoId, title, channelTitle) {
    const allFavs    = getFavorites();
    const chFavs     = allFavs.filter(f => f.channelTitle === channelTitle && f.ytVideoId);
    const playlist   = chFavs.map(f => ({ vid: f.ytVideoId, title: f.title }));
    const startIndex = Math.max(0, playlist.findIndex(p => p.vid === ytVideoId));

    // שמירת override — buildYtPlaylist יקרא אותו
    window._favPlaylistOverride = { playlist, startIndex };

    openYTModal(ytVideoId, title);

    // מיד אחרי הפתיחה — החלפת הפלייליסט לפלייליסט המועדפים
    requestAnimationFrame(() => {
        if (window._favPlaylistOverride) {
            currentYtPlaylist = window._favPlaylistOverride.playlist;
            currentYtIndex    = window._favPlaylistOverride.startIndex;
            window._favPlaylistOverride = null;
            if (typeof updateNavButtons   === 'function') updateNavButtons();
            if (typeof _updateCounter     === 'function') _updateCounter();
            if (typeof _updateModalMeta   === 'function') _updateModalMeta();
        }
    });
}



function renderFavoritesList() {
    const container  = document.getElementById('favoritesList');
    const emptyState = document.getElementById('noFavoritesState');
    const countEl    = document.getElementById('favCount');
    if (!container) return;
    container.innerHTML = '';

    const favs = getFavorites();
    if (countEl) countEl.textContent = `${favs.length} סרטונים שמורים`;

    if (favs.length === 0) {
        emptyState?.classList.remove('hidden');
        container.classList.add('hidden');
        return;
    }
    emptyState?.classList.add('hidden');
    container.classList.remove('hidden');

    if (favoritesGroupBy === 'channel') {
        _renderGrouped(favs,
            f => f.channelTitle || 'ערוץ לא ידוע',
            f => ({ image: f.channelImage, sub: f.categoryName || '' })
        );
    } else if (favoritesGroupBy === 'category') {
        _renderGrouped(favs,
            f => f.categoryName || 'ללא קטגוריה',
            (f, allFavs) => ({
                image: null,
                sub: `${allFavs.filter(x => (x.categoryName||'ללא קטגוריה') === (f.categoryName||'ללא קטגוריה')).length} סרטונים`
            })
        );
    } else {
        _renderGrouped(favs,
            f => {
                try {
                    const d = new Date(f.savedAt || f.pubDate);
                    return d.toLocaleDateString('he-IL', { year: 'numeric', month: 'long' });
                } catch(e) { return 'תאריך לא ידוע'; }
            },
            () => ({ image: null, sub: '' })
        );
    }
}

function _renderGrouped(favs, getGroupKey, getGroupMeta) {
    const container = document.getElementById('favoritesList');
    const groups    = {};
    const order     = [];

    favs.forEach(f => {
        const key = getGroupKey(f);
        if (!groups[key]) { groups[key] = { meta: getGroupMeta(f, favs), items: [] }; order.push(key); }
        groups[key].items.push(f);
    });

    order.forEach((key, gi) => {
        const { meta, items } = groups[key];
        const section = document.createElement('div');
        section.className = 'animate-fade-in';
        section.style.cssText = `margin-bottom:36px; animation-delay:${gi * 0.05}s;`;

        section.innerHTML = `
            <div style="display:flex; align-items:center; gap:12px; margin-bottom:16px; padding-bottom:12px;
                        border-bottom:1px solid var(--border);">
                ${meta.image ? `
                <div style="width:38px; height:38px; border-radius:50%; overflow:hidden; flex-shrink:0;
                             border:2px solid rgba(245,158,11,0.3); box-shadow:0 0 0 3px rgba(245,158,11,0.07);">
                    <img src="${meta.image}" style="width:100%; height:100%; object-fit:cover;"
                         onerror="this.parentElement.innerHTML='<div style=&quot;width:100%;height:100%;background:linear-gradient(135deg,#f59e0b,#d97706);display:flex;align-items:center;justify-content:center;&quot;><i class=&quot;fas fa-tv&quot; style=&quot;color:white;font-size:13px;&quot;></i></div>'">
                </div>` : `
                <div style="width:38px; height:38px; border-radius:50%; flex-shrink:0;
                             background:linear-gradient(135deg,rgba(245,158,11,0.18),rgba(245,158,11,0.05));
                             display:flex; align-items:center; justify-content:center;
                             border:1px solid rgba(245,158,11,0.2);">
                    <i class="fas fa-folder-open" style="color:#f59e0b; font-size:14px;"></i>
                </div>`}
                <div style="flex:1; min-width:0;">
                    <div style="font-size:14px; font-weight:800; color:var(--text-primary);
                                white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">${key}</div>
                    ${meta.sub ? `<div style="font-size:11px; color:var(--text-muted); margin-top:1px;">${meta.sub}</div>` : ''}
                </div>
                <span style="font-size:11px; background:rgba(245,158,11,0.1); color:#f59e0b;
                             padding:3px 10px; border-radius:20px; font-weight:700; flex-shrink:0;
                             border:1px solid rgba(245,158,11,0.2);">
                    ${items.length}
                </span>
            </div>`;

        const grid = document.createElement('div');
        grid.className = 'grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3';
        items.forEach((fav, i) => {
            const card = createFavYTCard(fav);
            card.style.animationDelay = `${gi * 0.05 + i * 0.03}s`;
            grid.appendChild(card);
        });

        section.appendChild(grid);
        container.appendChild(section);
    });
}

// ─── Card ─────────────────────────────────────────────────────

function createFavYTCard(fav) {
    const card     = document.createElement('div');
    card.className = 'group relative rounded-xl overflow-hidden bg-white border border-gray-200 hover:border-amber-300 shadow-sm hover:shadow-md transition-all duration-300 animate-fade-in';
    const thumbUrl = `https://img.youtube.com/vi/${fav.ytVideoId}/mqdefault.jpg`;
    let dateStr    = '';
    try { dateStr = new Date(fav.pubDate).toLocaleDateString('he-IL'); } catch(e) {}
    let chTitle = fav.channelTitle || '';
    try { chTitle = decodeURIComponent(chTitle); } catch(e) {}

    const safeTitle   = (fav.title || '').replace(/"/g, '&quot;');
    const safeId      = (fav.id || '').replace(/'/g, "\\'");
    const safeChTitle = (fav.channelTitle || '').replace(/'/g, "\\'").replace(/"/g, '&quot;');

    card.innerHTML = `
        <div class="relative cursor-pointer" style="aspect-ratio:16/9;"
             data-vid="${fav.ytVideoId}"
             data-title="${safeTitle}"
             onclick="openFavVideo('${fav.ytVideoId}', this.dataset.title, '${safeChTitle}')">
            <img src="${thumbUrl}" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                 loading="lazy" onerror="this.src='${fav.image || ''}'">
            <div class="absolute inset-0 flex items-center justify-center bg-black/5 group-hover:bg-black/20 transition-colors">
                <div class="w-10 h-10 rounded-full bg-red-600/90 flex items-center justify-center shadow-lg opacity-0 group-hover:opacity-100 scale-90 group-hover:scale-100 transition-all duration-200">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" class="w-5 h-5 ml-0.5"><path d="M8 5v14l11-7z"/></svg>
                </div>
            </div>
            ${fav.duration ? `<span class="absolute bottom-1.5 left-1.5 bg-black/60 text-white text-[9px] px-1.5 py-0.5 rounded-md font-mono">${fav.duration}</span>` : ''}
            <div class="absolute top-2 right-2 w-5 h-5 rounded-full bg-amber-400/90 flex items-center justify-center shadow
                        group-hover:opacity-0 transition-opacity duration-150">
                <i class="fas fa-star text-white" style="font-size:8px;"></i>
            </div>
            <button onclick="event.stopPropagation(); removeFavoriteById('${safeId}')"
                class="absolute top-2 right-2 w-6 h-6 flex items-center justify-center rounded-full
                       bg-red-500 text-white shadow-md
                       opacity-0 group-hover:opacity-100 scale-75 group-hover:scale-100
                       transition-all duration-200 hover:bg-red-600"
                title="הסר ממועדפים">
                <i class="fas fa-times" style="font-size:9px;"></i>
            </button>
        </div>
        <div class="p-2.5">
            <p class="text-gray-800 text-[11px] font-medium leading-snug line-clamp-2 mb-1">${fav.title}</p>
            <p class="text-gray-400 text-[10px]">${chTitle}${dateStr ? ' · ' + dateStr : ''}</p>
        </div>`;
    return card;
}
