/**
 * library.js — YouTube Player
 * ספרייה ראשית: קטגוריות, ערוצים, גרירה, הוספה, ייצוא/ייבוא
 */

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

function showDashboard() {
    document.getElementById('viewChannel').classList.add('hidden');
    document.getElementById('viewFavorites').classList.add('hidden');
    document.getElementById('viewUpdates')?.classList.add('hidden');
    document.getElementById('viewDashboard').classList.remove('hidden');
    window.scrollTo(0, 0);
}

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

// ─── Render library ───────────────────────────────────────────

function renderLibrary() {
    const container   = document.getElementById('categoriesContainer');
    const emptyState  = document.getElementById('emptyState');
    const data        = getLocalData();

    container.innerHTML = '';

    if (!data || data.length === 0) {
        emptyState?.classList.remove('hidden');
        return;
    }
    emptyState?.classList.add('hidden');

    data.forEach(cat => {
        const section = document.createElement('div');
        section.className = 'category-section animate-fade-in';

        const channels = cat.channels || [];
        section.innerHTML = `
            <div class="category-header">
                <div style="display:flex; align-items:center; gap:10px;">
                    <h3 class="category-title">${cat.name}</h3>
                    <span style="font-size:11px; color:var(--text-muted); background:var(--bg-card); padding:2px 8px; border-radius:20px;">${channels.length}</span>
                </div>
                <div style="display:flex; gap:6px; align-items:center;">
                    <button onclick="openCategoryModal('${cat.id}', '${cat.name.replace(/'/g, "\\'")}')"
                        style="background:none; border:none; color:var(--text-muted); cursor:pointer; padding:4px 8px; border-radius:8px; font-size:12px; transition:color 0.15s;"
                        onmouseover="this.style.color='var(--accent)'" onmouseout="this.style.color='var(--text-muted)'">
                        <i class="fas fa-pen"></i>
                    </button>
                    <button onclick="deleteCategory('${cat.id}')"
                        style="background:none; border:none; color:var(--text-muted); cursor:pointer; padding:4px 8px; border-radius:8px; font-size:12px; transition:color 0.15s;"
                        onmouseover="this.style.color='#ef4444'" onmouseout="this.style.color='var(--text-muted)'">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>`;

        const grid = document.createElement('div');
        grid.className = 'channels-grid sortable-list';
        grid.dataset.id = cat.id;

        channels.forEach(ch => grid.appendChild(createMiniCard(ch, cat.id)));

        // כפתור "+" בתוך הגריד כ-tile
        const addTile = document.createElement('div');
        addTile.className = 'add-channel-tile ignore-drag';
        addTile.onclick = () => openAddModal(cat.id, cat.name);
        addTile.innerHTML = `<i class="fas fa-plus" style="font-size:20px; margin-bottom:4px;"></i><span style="font-size:10px; font-weight:600;">ערוץ</span>`;
        grid.appendChild(addTile);

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

    _initSortable(container);
}

function _initSortable(container) {
    if (typeof Sortable === 'undefined') return;

    container.querySelectorAll('.sortable-list').forEach(list => {
        Sortable.create(list, {
            group:      'channels',
            animation:  150,
            ghostClass: 'sortable-ghost',
            onEnd:      handleSortEnd
        });
    });

    Sortable.create(container, {
        animation:  150,
        handle:     '.drag-handle',
        ghostClass: 'sortable-ghost',
        onEnd: async function(evt) {
            if (evt.newIndex === evt.oldIndex) return;
            const data      = getLocalData();
            const movedItem = data.splice(evt.oldIndex, 1)[0];
            data.splice(evt.newIndex, 0, movedItem);
            await saveDataToServer(data);
        }
    });
}

async function handleSortEnd(evt) {
    if (evt.to === evt.from && evt.newIndex === evt.oldIndex) return;
    const fromCatId = evt.from.dataset.id;
    const toCatId   = evt.to.dataset.id;
    const chId      = evt.item.dataset.id;
    const data      = getLocalData();
    const fromCat   = data.find(c => c.id === fromCatId);
    const toCat     = data.find(c => c.id === toCatId);
    if (!fromCat || !toCat) return;
    const chObj = (fromCat.channels || []).find(c => c.id === chId);
    if (!chObj) return;
    fromCat.channels = (fromCat.channels || []).filter(c => c.id !== chId);
    let newIndex = evt.newIndex;
    if (newIndex > (toCat.channels || []).length) newIndex = (toCat.channels || []).length;
    if (!toCat.channels) toCat.channels = [];
    toCat.channels.splice(newIndex, 0, chObj);
    await saveDataToServer(data);
    renderLibrary();
}

// ─── Mini card ────────────────────────────────────────────────

function createMiniCard(ch, catId) {
    const card      = document.createElement('div');
    card.className  = 'channel-mini-card group/card';
    card.dataset.id = ch.id;
    
    // שימוש ב-SVG עם קידוד מושלם (%22 במקום מרכאות) כדי למנוע שבירת קוד HTML או JS
    const fallbackImg = "data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22150%22 height=%22150%22%3E%3Crect width=%22150%22 height=%22150%22 fill=%22%23e5e5e5%22/%3E%3Ctext x=%2250%25%22 y=%2250%25%22 dominant-baseline=%22middle%22 text-anchor=%22middle%22 fill=%22%23aaa%22 font-size=%2240%22%3E%E2%96%B6%3C/text%3E%3C/svg%3E";
    const imgUrl    = ch.image || fallbackImg;
    
    const newBadge  = (ch.newCount && ch.newCount > 0)
        ? `<span style="position:absolute;top:6px;right:6px;background:#ef4444;color:white;font-size:9px;font-weight:700;padding:2px 6px;border-radius:20px;pointer-events:none;">${ch.newCount}</span>`
        : '';

    // הגדרת המעקב: ברירת המחדל היא שערוצים יהיו במעקב (אלא אם הוגדר false במפורש)
    const isTracked = ch.isTracked !== false;
    const bellIcon  = isTracked ? 'fas fa-bell' : 'far fa-bell-slash';
    const bellColor = isTracked ? '#f59e0b' : 'var(--text-muted)';
    const bellTitle = isTracked ? 'בטל מעקב' : 'עקוב אחרי ערוץ זה';

    card.innerHTML = `
        <div style="position:relative; cursor:pointer;">
            <img src="${imgUrl}" alt="${ch.title}" style="width:100%; aspect-ratio:1; object-fit:cover; border-radius:10px; display:block;"
                onerror="this.src='${fallbackImg}'" onclick="openChannel('${ch.id}')">
            ${newBadge}
            <button onclick="toggleTrackChannel('${ch.id}', event)"
                class="bell-btn"
                style="position:absolute; top:0; left:0; background:none; border:none; color:${bellColor}; cursor:pointer; padding:3px 5px; border-radius:6px; font-size:15px; transition:all 0.15s;"
                title="${bellTitle}">
                <i class="${bellIcon}"></i>
            </button>
        </div>
        <div style="display:flex; align-items:center; justify-content:space-between; margin-top:6px; gap:4px;">
            <p style="font-size:11px; font-weight:600; color:var(--text-secondary); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; cursor:pointer; flex:1;"
               onclick="openChannel('${ch.id}')" title="${ch.title}">${ch.title}</p>
            <button onclick="deleteChannel('${ch.id}','${catId}',event)"
                style="background:none; border:none; color:var(--text-muted); cursor:pointer; padding:2px 4px; border-radius:6px; font-size:11px; opacity:0; transition:opacity 0.15s; flex-shrink:0;"
                class="delete-ch-btn" title="מחק">
                <i class="fas fa-times"></i>
            </button>
        </div>`;

    const bellBtn = card.querySelector('.bell-btn');
    bellBtn.addEventListener('mouseenter', function() {
        this.style.background     = 'rgba(0,0,0,0.55)';
        this.style.backdropFilter = 'blur(4px)';
    });
    bellBtn.addEventListener('mouseleave', function() {
        this.style.background     = 'none';
        this.style.backdropFilter = 'none';
    });

    card.addEventListener('mouseenter', () => card.querySelector('.delete-ch-btn').style.opacity = '1');
    card.addEventListener('mouseleave', () => card.querySelector('.delete-ch-btn').style.opacity = '0');
    return card;
}

// ─── Open channel ─────────────────────────────────────────────

async function openChannel(id) {
    const fullData = await getFullData();
    let ch = null, categoryName = '';
    for (const cat of fullData) {
        const found = (cat.channels || []).find(c => c.id === id);
        if (found) { ch = found; categoryName = cat.name; break; }
    }
    if (!ch) return;

    // נקה newCount
    if (ch.newCount > 0) {
        ch.newCount = 0;
        await updateChannelInStorage(ch);
        renderLibrary();
    }

    currentChannelId = id;
    showChannelView();

    // מילוי header הערוץ
    document.getElementById('channelTitle').textContent       = ch.title || '';
    document.getElementById('channelImage').src               = ch.image || '';
    document.getElementById('channelDescription').textContent = cleanHTML(ch.description || '');
    updateChannelStats(ch);

    loadVideosPage(id, 0, categoryName, ch.title, ch.image, true);
}

// ─── Delete & Track Channel ───────────────────────────────────

async function deleteChannel(chId, catId, event) {
    event.stopPropagation();
    if (!confirm('למחוק את הערוץ?')) return;
    const fullData = await getFullData();
    const catIdx   = fullData.findIndex(c => c.id === catId);
    if (catIdx !== -1) {
        fullData[catIdx].channels = (fullData[catIdx].channels || []).filter(c => c.id !== chId);
        await saveDataToServer(fullData);
        await loadDataFromServer();
        renderLibrary();
    }
}

window.toggleTrackChannel = async function(chId, event) {
    event.stopPropagation();
    const fullData = await getFullData();
    let updated = false;
    let newValue = true;
    
    for (const cat of fullData) {
        const ch = (cat.channels || []).find(c => c.id === chId);
        if (ch) {
            ch.isTracked = ch.isTracked === false ? true : false;
            newValue = ch.isTracked;
            updated = true;
            break;
        }
    }
    
    if (updated) {
        await saveDataToServer(fullData);
        await loadDataFromServer();

        // עדכון הכפתור בלבד — ללא רינדור מחדש של הדף
        const btn = document.querySelector(`.channel-mini-card[data-id="${chId}"] .bell-btn`);
        if (btn) {
            const icon     = btn.querySelector('i');
            const color    = newValue ? '#f59e0b' : 'var(--text-muted)';
            const title    = newValue ? 'בטל מעקב' : 'עקוב אחרי ערוץ זה';
            const iconClass = newValue ? 'fas fa-bell' : 'far fa-bell-slash';
            btn.style.color = color;
            btn.title       = title;
            icon.className  = iconClass;
        }

        showToast(newValue ? 'מעקב הופעל ✓' : 'מעקב בוטל ✗', 'info');
    }
};

// ─── Add channel modal ────────────────────────────────────────

let targetCategoryId = null;

function openAddModal(categoryId, categoryName) {
    targetCategoryId = categoryId;
    document.getElementById('targetCategoryName').innerText = categoryName;
    document.getElementById('addStatus').classList.add('hidden');
    document.getElementById('newChannelUrl').value = '';
    document.getElementById('addModal').classList.remove('hidden');
    document.getElementById('newChannelUrl').focus();
}

function closeAddModal() { document.getElementById('addModal').classList.add('hidden'); }

document.addEventListener('DOMContentLoaded', () => {

    // ── Add channel form ───────────────────────────────────────
    document.getElementById('addForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        let url = document.getElementById('newChannelUrl').value.trim();
        const btn = document.getElementById('addBtn');
        if (!url || !targetCategoryId) return;

        if (/^UC[\w-]{22}$/.test(url)) url = `https://www.youtube.com/channel/${url}`;

        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        btn.disabled  = true;

        const addStatus = document.getElementById('addStatus');
        addStatus.textContent = 'טוען נתוני ערוץ...';
        addStatus.classList.remove('hidden', 'text-red-400');
        addStatus.classList.add('text-zinc-400');

        try {
            const maxEpisodes = parseInt(localStorage.getItem('yt_max_episodes') ?? '1500') || 1500;
            const res = await fetch(ENDPOINTS.YOUTUBE, {
                method:  'POST',
                headers: { 'Content-Type': 'application/json' },
                body:    JSON.stringify({ url, maxEpisodes }) // הוסר apiKey
            });
            if (!res.ok) {
                const errJson = await res.json().catch(() => ({}));
                throw new Error(errJson.error || `Server Error ${res.status}`);
            }
            const data = await res.json();

            const fullData = await getFullData();
            const catIdx   = fullData.findIndex(c => c.id === targetCategoryId);
            if (catIdx !== -1) {
                if (!fullData[catIdx].channels) fullData[catIdx].channels = [];
                fullData[catIdx].channels.push({
                    id:              Date.now().toString(),
                    title:           data.title,
                    description:     data.description || '',
                    image:           data.image || '',
                    link:            data.link || '',
                    subscribers:     data.subscribers || null,
                    totalVideoCount: data.totalVideoCount || null,
                    rssUrl:          url,
                    addedAt:         new Date().toISOString(),
                    lastFetch:       new Date().toISOString(),
                    episodes:        data.episodes || [],
                    episodeCount:    (data.episodes || []).length,
                    newCount:        0,
                    isTracked:       true
                });
                await saveDataToServer(fullData);
                await loadDataFromServer();
                closeAddModal();
                renderLibrary();
                showToast(`"${data.title}" נוסף בהצלחה ✓`, 'success');
                // פתיחה אוטומטית של רשימת הפרקים
                const newId = fullData[catIdx].channels[fullData[catIdx].channels.length - 1].id;
                openChannel(newId);
            }
        } catch(err) {
            addStatus.textContent = 'שגיאה: ' + (err.message || 'Unknown Error');
            addStatus.classList.add('text-red-400');
            addStatus.classList.remove('text-zinc-400');
        } finally {
            btn.innerHTML = '<i class="fab fa-youtube" style="margin-left:8px;"></i> הוסף ערוץ';
            btn.disabled  = false;
        }
    });

    // ── Category form ──────────────────────────────────────────
    document.getElementById('categoryForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const name   = document.getElementById('newCategoryName').value.trim();
        const editId = document.getElementById('editCategoryId').value;
        if (!name) return;

        const fullData = await getFullData();
        if (editId) {
            const cat = fullData.find(c => c.id === editId);
            if (cat) cat.name = name;
        } else {
            fullData.push({ id: 'cat_' + Date.now(), name, channels: [] });
        }
        await saveDataToServer(fullData);
        await loadDataFromServer();
        closeCategoryModal();
        renderLibrary();
    });
});

// ─── Category modal ───────────────────────────────────────────

function openCategoryModal(editId = null, currentName = '') {
    const title    = document.getElementById('categoryModalTitle');
    const input    = document.getElementById('newCategoryName');
    const hiddenId = document.getElementById('editCategoryId');
    const btn      = document.getElementById('categorySubmitBtn');
    if (editId) {
        title.innerText = 'עריכת קטגוריה';
        input.value     = currentName;
        hiddenId.value  = editId;
        btn.innerText   = 'עדכן';
    } else {
        title.innerText = 'קטגוריה חדשה';
        input.value     = '';
        hiddenId.value  = '';
        btn.innerText   = 'צור';
    }
    document.getElementById('categoryModal').classList.remove('hidden');
    input.focus();
}

function closeCategoryModal() {
    document.getElementById('categoryModal').classList.add('hidden');
}

async function deleteCategory(id) {
    if (!confirm('למחוק קטגוריה ואת כל הערוצים שבה?')) return;
    const fullData = (await getFullData()).filter(c => c.id !== id);
    await saveDataToServer(fullData);
    await loadDataFromServer();
    renderLibrary();
}

// ─── Export / Import ──────────────────────────────────────────

async function exportData(structureOnly = false) {
    const data      = await getFullData();
    const exportObj = JSON.parse(JSON.stringify(data));
    if (structureOnly) {
        exportObj.forEach(cat => (cat.channels || []).forEach(ch => { ch.episodes = []; ch.newCount = 0; }));
    }
    const blob = new Blob([JSON.stringify(exportObj, null, 2)], { type: 'application/json' });
    const url  = URL.createObjectURL(blob);
    const a    = document.createElement('a');
    a.href     = url;
    a.download = `yt_library_${structureOnly ? 'structure' : 'full'}_${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

function triggerImport() { document.getElementById('importInput').click(); }

function importData(input) {
    const file = input.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = async (e) => {
        try {
            const json = JSON.parse(e.target.result);
            if (confirm('לשחזר נתונים? הנתונים הנוכחיים יוחלפו.')) {
                await saveDataToServer(json);
                await loadDataFromServer();
                renderLibrary();
                showToast('נתונים שוחזרו בהצלחה ✓', 'success');
            }
        } catch(err) { showToast('קובץ לא תקין', 'error'); }
        input.value = '';
    };
    reader.readAsText(file);
}