let myGallery = null;
let adminRequestPending = false;
let convertStatusTimer = null;
let convertStatusLoading = false;
let diskStatusLoading = false;

document.addEventListener('DOMContentLoaded', () => {
    const btnTheme = document.getElementById('btnToggleTheme');
    if (localStorage.getItem('theme') === 'dark') document.body.classList.add('dark-mode');
    if (btnTheme) btnTheme.addEventListener('click', () => { document.body.classList.toggle('dark-mode'); localStorage.setItem('theme', document.body.classList.contains('dark-mode') ? 'dark' : 'light'); });

    const btnView = document.getElementById('btnToggleView');
    if (localStorage.getItem('view') === 'grid') document.body.classList.add('grid-mode');
    if (btnView) btnView.addEventListener('click', () => { document.body.classList.toggle('grid-mode'); localStorage.setItem('view', document.body.classList.contains('grid-mode') ? 'grid' : 'list'); });

    if (typeof GLightbox !== 'undefined') myGallery = GLightbox({ selector: '.glightbox', touchNavigation: true, loop: true, zoomable: true });

    const videoThumbs = document.querySelectorAll('.video-thumb[data-thumb-url]');

    function startVideoThumbPolling(img) {
        if (img.dataset.thumbPolling === '1' || img.dataset.thumbReady === '1') return;
        img.dataset.thumbPolling = '1';
        let attempts = 0;
        const maxAttempts = 90;

        function checkVideoThumb() {
            if (!document.body.contains(img) || img.dataset.thumbReady === '1') return;
            attempts++;

            fetch(img.dataset.thumbUrl + '&status=1&_=' + Date.now(), { cache: 'no-store' })
            .then(response => {
                if (response.status !== 200 && response.status !== 202) throw new Error('HTTP ' + response.status);
                return response.json();
            })
            .then(data => {
                if (data.ready === true && data.url) {
                    img.src = data.url;
                    img.dataset.thumbReady = '1';
                    img.dataset.thumbPolling = '0';
                    return;
                }

                if (attempts < maxAttempts) {
                    setTimeout(checkVideoThumb, data.generating ? 1500 : 2500);
                } else {
                    img.dataset.thumbPolling = '0';
                }
            })
            .catch(() => {
                if (attempts < maxAttempts) {
                    setTimeout(checkVideoThumb, 3000);
                } else {
                    img.dataset.thumbPolling = '0';
                }
            });
        }

        checkVideoThumb();
    }

    if (videoThumbs.length > 0) {
        if ('IntersectionObserver' in window) {
            const videoThumbObserver = new IntersectionObserver(entries => {
                entries.forEach(entry => {
                    if (!entry.isIntersecting) return;
                    videoThumbObserver.unobserve(entry.target);
                    startVideoThumbPolling(entry.target);
                });
            }, { rootMargin: '300px 0px' });

            videoThumbs.forEach(img => videoThumbObserver.observe(img));
        } else {
            videoThumbs.forEach(startVideoThumbPolling);
        }
    }

    let searchInput = document.getElementById('searchInput');
    const suppImg = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    const suppVid = ['mp4', 'webm']; const extVid = ['mkv', 'avi', 'ts', 'mts'];
    const suppAudio = ['mp3', 'wav', 'ogg', 'oga', 'flac', 'm4a', 'aac'];
    const suppDoc = ['pdf', 'txt', 'json', 'xml', 'csv', 'html', 'css', 'js', 'svg'];
    let searchTimer = null;
    let searchController = null;
    let searchRequestId = 0;
    
    if (searchInput) {
        searchInput.addEventListener('keydown', e => { if (e.key === 'Enter') e.preventDefault(); });
        searchInput.addEventListener('input', function(e) {
            let q = e.target.value.trim();
            let resDiv = document.getElementById('searchResults');
            clearTimeout(searchTimer);
            searchRequestId++;
            if (searchController) {
                searchController.abort();
                searchController = null;
            }

            if (q.length >= 3) {
                const requestId = searchRequestId;
                resDiv.style.display = 'block';
                resDiv.innerHTML = '<div class="s-item" style="color: #666;">Szukam...</div>';

                searchTimer = setTimeout(() => {
                    searchController = new AbortController();
                    fetch('search.php?q=' + encodeURIComponent(q), { signal: searchController.signal })
                    .then(readJsonResponse)
                    .then(data => {
                        if (requestId !== searchRequestId || searchInput.value.trim() !== q) return;
                        if (!Array.isArray(data)) throw new Error('Nieprawidłowa odpowiedź wyszukiwarki.');

                        resDiv.innerHTML = '';
                        if(data.length === 0) {
                            resDiv.innerHTML = '<div class="s-item" style="color: #999;">Brak wynik\u00f3w</div>';
                        } else {
                            data.forEach(item => {
                                let itemName = String(item.name ?? '');
                                let itemFolder = String(item.folder ?? '');
                                let itemPath = String(item.path ?? '');
                                let isDir = item.is_dir;
                                let fExt = itemName.includes('.') ? itemName.split('.').pop().toLowerCase() : '';
                                let isImg = suppImg.includes(fExt); let isV = suppVid.includes(fExt); let isEV = extVid.includes(fExt);
                                let isAud = suppAudio.includes(fExt); let isD = suppDoc.includes(fExt); let canV = isImg || isAud || isD;
                                let link = '';
                                if (isDir) link = `folder.php?folder=${encodeURIComponent(itemFolder)}&path=${encodeURIComponent(itemPath === '' ? itemName : itemPath + '/' + itemName)}`;
                                else if (isV || isEV) link = `play.php?folder=${encodeURIComponent(itemFolder)}&path=${encodeURIComponent(itemPath)}&file=${encodeURIComponent(itemName)}`;
                                else if (canV) link = `view.php?folder=${encodeURIComponent(itemFolder)}&path=${encodeURIComponent(itemPath)}&file=${encodeURIComponent(itemName)}`;
                                else link = `download.php?folder=${encodeURIComponent(itemFolder)}&path=${encodeURIComponent(itemPath)}&file=${encodeURIComponent(itemName)}`;
                                
                                let icon = isDir ? '&#128193;' : (isImg ? '&#128247;' : ((isV || isEV) ? '&#127916;' : (isAud ? '&#127925;' : (isD ? '&#128214;' : '&#128196;'))));
                                let resultLink = document.createElement('a');
                                resultLink.href = link;
                                resultLink.className = isImg ? 's-item glightbox' : 's-item';
                                if (isImg) resultLink.setAttribute('data-gallery', 'search-gallery');
                                if (!isDir && !isImg) resultLink.target = '_blank';

                                if (isImg) {
                                    let thumb = document.createElement('img');
                                    thumb.src = `thumb.php?folder=${encodeURIComponent(itemFolder)}&path=${encodeURIComponent(itemPath)}&file=${encodeURIComponent(itemName)}`;
                                    thumb.style.width = '30px';
                                    thumb.style.height = '30px';
                                    thumb.style.objectFit = 'cover';
                                    thumb.style.borderRadius = '4px';
                                    thumb.style.marginRight = '10px';
                                    thumb.alt = '';
                                    resultLink.appendChild(thumb);
                                }

                                let iconSpan = document.createElement('span');
                                iconSpan.style.marginRight = '10px';
                                iconSpan.style.fontSize = '18px';
                                iconSpan.innerHTML = icon;
                                resultLink.appendChild(iconSpan);
                                resultLink.appendChild(document.createTextNode(itemName + ' '));

                                let folderSpan = document.createElement('span');
                                folderSpan.style.color = '#888';
                                folderSpan.style.fontSize = '0.8em';
                                folderSpan.style.marginLeft = '10px';
                                folderSpan.textContent = '[' + itemFolder + ']';
                                resultLink.appendChild(folderSpan);
                                resDiv.appendChild(resultLink);
                            });
                            if (myGallery) myGallery.reload();
                        }
                    })
                    .catch(err => {
                        if (err.name === 'AbortError') return;
                        if (requestId !== searchRequestId || searchInput.value.trim() !== q) return;
                        resDiv.innerHTML = '<div class="s-item" style="color: red; font-size: 13px;">B\u0142\u0105d zapytania.</div>';
                    })
                    .finally(() => {
                        if (requestId === searchRequestId) searchController = null;
                    });
                }, 250);
            } else {
                resDiv.style.display = 'none';
                resDiv.innerHTML = '';
            }
        });
        document.addEventListener('click', function(e) { if (!e.target.closest('.search-container')) document.getElementById('searchResults').style.display = 'none'; });
    }

    const checkAll = document.getElementById('checkAll');
    const chkItems = document.querySelectorAll('.chk-item');
    const multiBar = document.getElementById('multiActionBar');
    const selCount = document.getElementById('selCount');
    
    function updateMultiBar() {
        let count = document.querySelectorAll('.chk-item:checked').length;
        if(count > 0) {
            multiBar.style.display = 'block'; selCount.innerText = 'Zaznaczono plik\u00f3w: ' + count;
        } else { multiBar.style.display = 'none'; }
    }
    if(checkAll) {
        checkAll.addEventListener('change', function() { chkItems.forEach(chk => chk.checked = this.checked); updateMultiBar(); });
        chkItems.forEach(chk => chk.addEventListener('change', updateMultiBar));
    }

    const btnCookies = document.getElementById('btnUploadCookies');
    const cookiesUploader = document.getElementById('cookiesUploader');
    if (btnCookies && cookiesUploader) {
        btnCookies.addEventListener('click', () => cookiesUploader.click());
        cookiesUploader.addEventListener('change', function() {
            if(this.files.length === 0) return;
            if (!beginAdminRequest()) return;

            let fd = new FormData();
            fd.append('action', 'upload_cookies');
            fd.append('cookie_file', this.files[0]);
            
            fd.append('folder', document.querySelector('input[name="folder"]').value);
            fd.append('path', document.querySelector('input[name="path"]').value);
            
            let oldText = btnCookies.innerHTML;
            btnCookies.innerText = "Wgrywanie...";
            btnCookies.disabled = true;
            
            fetch('admin_ajax.php', { method: 'POST', body: fd })
            .then(readJsonResponse)
            .then(data => {
                alert(data.msg || (data.status === 'ok' ? 'Operacja zakończona.' : 'Błąd operacji.'));
            })
            .catch(() => {
                alert('Błąd połączenia z serwerem.');
            })
            .finally(() => {
                btnCookies.innerHTML = oldText;
                btnCookies.disabled = false;
                cookiesUploader.value = '';
                finishAdminRequest();
            });
        });
    }
});

function readJsonResponse(response) {
    if (!response.ok) throw new Error('HTTP ' + response.status);
    return response.json();
}

function beginAdminRequest() {
    if (adminRequestPending) {
        alert('Poprzednia operacja nadal trwa. Poczekaj na jej zakończenie.');
        return false;
    }
    adminRequestPending = true;
    return true;
}

function finishAdminRequest() {
    adminRequestPending = false;
}

function getFdBase(action) {
    let fd = new FormData();
    fd.append('action', action);
    fd.append('folder', document.querySelector('input[name="folder"]').value);
    fd.append('path', document.querySelector('input[name="path"]').value);
    return fd;
}

function adminAction(action, filename) {
    let fd = getFdBase(action);
    if (action === 'delete') {
        if(!confirm(`Czy na pewno usun\u0105\u0107 trwale: ${filename}?`)) return;
        fd.append('file', filename);
    } else if (action === 'rename') {
        let nowa = prompt('Podaj now\u0105 nazw\u0119:', filename);
        if(!nowa || nowa === filename) return;
        fd.append('old_name', filename); fd.append('new_name', nowa);
    }
    if (!beginAdminRequest()) return;

    fetch('admin_ajax.php', { method: 'POST', body: fd })
    .then(readJsonResponse)
    .then(d => { if(d.status === 'ok') location.reload(); else alert(d.msg || 'B\u0142\u0105d operacji.'); })
    .catch(() => { alert('Błąd połączenia z serwerem.'); })
    .finally(finishAdminRequest);
}

function adminMkdir() {
    let name = prompt('Podaj nazw\u0119 nowego folderu:');
    if(!name) return;
    let fd = getFdBase('mkdir'); fd.append('name', name);
    if (!beginAdminRequest()) return;

    fetch('admin_ajax.php', { method: 'POST', body: fd })
    .then(readJsonResponse)
    .then(d => { if(d.status === 'ok') location.reload(); else alert(d.msg || 'Błąd operacji.'); })
    .catch(() => { alert('Błąd połączenia z serwerem.'); })
    .finally(finishAdminRequest);
}

function adminYtDlp() {
    let url = prompt('Wklej link (np. YouTube) - wideo/playlista pobierze si\u0119 W TLE na serwerze:');
    if(!url) return;
    let fd = getFdBase('ytdlp'); fd.append('url', url);
    if (!beginAdminRequest()) return;

    fetch('admin_ajax.php', { method: 'POST', body: fd })
    .then(readJsonResponse)
    .then(d => { alert(d.msg || (d.status === 'ok' ? 'Rozpoczęto operację.' : 'Błąd operacji.')); })
    .catch(() => { alert('Błąd połączenia z serwerem.'); })
    .finally(finishAdminRequest);
}

function openMoveCopyModal(action) {
    document.getElementById('mcActionType').value = action;
    document.getElementById('mcTitle').innerHTML = (action === 'move') ? '&#10145;&#65039; Przenie\u015b pliki do...' : '&#128196; Kopiuj pliki do...';
    document.getElementById('mcModal').style.display = 'flex';
}

function executeMoveCopy() {
    let checked = document.querySelectorAll('.chk-item:checked');
    if (checked.length === 0) return;
    
    let fd = getFdBase(document.getElementById('mcActionType').value);
    checked.forEach(cb => { fd.append('files[]', cb.value); });
    fd.append('dest_folder', document.getElementById('mcDestFolder').value);
    fd.append('dest_path', document.getElementById('mcDestPath').value);
    if (!beginAdminRequest()) return;

    document.getElementById('mcModal').style.display = 'none';
    alert('Rozpoczynam operacj\u0119. Okno od\u015bwie\u017cy si\u0119 po zako\u0144czeniu.');
    
    fetch('admin_ajax.php', { method: 'POST', body: fd })
    .then(readJsonResponse)
    .then(d => { if(d.status === 'ok') location.reload(); else alert(d.msg || 'B\u0142\u0105d.'); })
    .catch(() => { alert('Błąd połączenia z serwerem.'); })
    .finally(finishAdminRequest);
}

// NOWA FUNKCJA: MASOWE USUWANIE
function executeMultiDelete() {
    let checked = document.querySelectorAll('.chk-item:checked');
    if (checked.length === 0) return;
    if(!confirm('Czy na pewno chcesz trwale usun\u0105\u0107 ' + checked.length + ' zaznaczonych element\u00f3w?')) return;
    
    let fd = getFdBase('multi_delete');
    checked.forEach(cb => { fd.append('files[]', cb.value); });
    if (!beginAdminRequest()) return;
    
    fetch('admin_ajax.php', { method: 'POST', body: fd })
    .then(readJsonResponse)
    .then(d => { if(d.status === 'ok') location.reload(); else alert(d.msg || 'B\u0142\u0105d podczas usuwania.'); })
    .catch(() => { alert('Błąd połączenia z serwerem.'); })
    .finally(finishAdminRequest);
}

function adminYtLog() {
    if (!beginAdminRequest()) return;

    document.getElementById('ytLogModal').style.display = 'flex';
    document.getElementById('ytLogContent').innerText = 'Pobieranie log\u00f3w...';
    let fd = getFdBase('yt_log');
    fetch('admin_ajax.php', { method: 'POST', body: fd })
    .then(readJsonResponse)
    .then(d => {
        if(d.status === 'ok') {
            document.getElementById('ytLogContent').innerText = d.log || "Brak log\u00f3w.";
            let elem = document.getElementById('ytLogContent');
            elem.scrollTop = elem.scrollHeight;
        } else {
            document.getElementById('ytLogContent').innerText = d.msg || "Wyst\u0105pi\u0142 b\u0142\u0105d.";
        }
    })
    .catch(() => {
        document.getElementById('ytLogContent').innerText = 'Błąd połączenia z serwerem.';
    })
    .finally(finishAdminRequest);
}

function adminYtLogClear() {
    if(!confirm("Czy na pewno chcesz wyczy\u015bci\u0107 logi?")) return;
    let fd = getFdBase('yt_log_clear');
    if (!beginAdminRequest()) return;

    let refreshLog = false;
    fetch('admin_ajax.php', { method: 'POST', body: fd })
    .then(readJsonResponse)
    .then(d => {
        if (d.status === 'ok') refreshLog = true;
        else alert(d.msg || 'Błąd czyszczenia logów.');
    })
    .catch(() => { alert('Błąd połączenia z serwerem.'); })
    .finally(() => {
        finishAdminRequest();
        if (refreshLog) adminYtLog();
    });
}

function adminDiskStatus() {
    const modal = document.getElementById('diskStatusModal');
    if (!modal) return;
    modal.style.display = 'flex';
    loadDiskStatus();
}

function closeDiskStatus() {
    const modal = document.getElementById('diskStatusModal');
    if (modal) modal.style.display = 'none';
}

function diskStatusFilesystemLines(title, data) {
    const lines = [title];
    if (!data || data.available !== true) {
        lines.push('Brak danych z systemu plików.');
        return lines;
    }
    lines.push('Zajęte: ' + String(data.used_formatted || '-') + ' (' + String(data.percent ?? 0) + '%)');
    lines.push('Wolne:  ' + String(data.free_formatted || '-'));
    lines.push('Razem:  ' + String(data.total_formatted || '-'));
    return lines;
}

function loadDiskStatus() {
    if (diskStatusLoading) return;
    const content = document.getElementById('diskStatusContent');
    if (!content) return;
    diskStatusLoading = true;
    content.textContent = 'Pobieranie informacji o miejscu...';

    let fd = getFdBase('disk_status');
    fetch('admin_ajax.php', { method: 'POST', body: fd })
    .then(readJsonResponse)
    .then(data => {
        if (data.status !== 'ok') {
            content.textContent = data.msg || 'Nie udało się pobrać informacji o miejscu.';
            return;
        }

        const lines = [];
        lines.push(...diskStatusFilesystemLines('DYSK LOKALNY SERWERA', data.local));
        lines.push('');
        lines.push(...diskStatusFilesystemLines('CHMURA /mnt/mega', data.cloud));
        lines.push('');
        lines.push('KATALOGI ROBOCZE I CACHE');
        const cache = data.cache || {};
        lines.push('Miniaturki przewijania: ' + String(cache.thumbnails?.formatted || '0 B'));
        lines.push('Miniaturki filmów:      ' + String(cache.video_thumbs?.formatted || '0 B'));
        lines.push('Miniaturki zdjęć:       ' + String(cache.image_thumbs?.formatted || '0 B'));
        lines.push('Pliki konwersji:        ' + String(cache.convert_temp?.formatted || '0 B'));
        lines.push('Pliki tymczasowe YT:    ' + String(cache.yt_temp?.formatted || '0 B'));
        if (data.checked_at) {
            lines.push('');
            lines.push('Sprawdzono: ' + new Date(Number(data.checked_at) * 1000).toLocaleString());
        }
        content.textContent = lines.join('\n');
    })
    .catch(() => {
        content.textContent = 'Błąd połączenia z serwerem.';
    })
    .finally(() => {
        diskStatusLoading = false;
    });
}

function executeConvert() {
    let checked = document.querySelectorAll('.chk-item:checked[data-is-video="1"]');
    if (checked.length === 0) {
        alert('Zaznacz przynajmniej jeden film do konwersji.');
        return;
    }
    if (!confirm('Dodać do kolejki konwersji ' + checked.length + ' filmów?\n\nOryginalne pliki pozostaną bez zmian. Gotowe MP4 pojawią się w tym samym katalogu.')) return;

    let fd = getFdBase('convert');
    checked.forEach(cb => fd.append('files[]', cb.value));
    if (!beginAdminRequest()) return;

    fetch('admin_ajax.php', { method: 'POST', body: fd })
    .then(readJsonResponse)
    .then(data => {
        alert(data.msg || (data.status === 'ok' ? 'Dodano do kolejki.' : 'Nie udało się dodać zadania.'));
        if (data.status === 'ok') adminConvertStatus();
    })
    .catch(() => { alert('Błąd połączenia z serwerem.'); })
    .finally(finishAdminRequest);
}

function convertStatusLabel(status) {
    const labels = {
        queued: 'OCZEKUJE',
        probing: 'ANALIZA',
        converting: 'KONWERTOWANIE',
        remuxing: 'PRZEPAKOWYWANIE',
        uploading: 'WYSYŁANIE DO CHMURY',
        done: 'GOTOWE',
        skipped: 'POMINIĘTO',
        error: 'BŁĄD'
    };
    return labels[status] || String(status || 'NIEZNANY').toUpperCase();
}

function adminConvertStatus() {
    const modal = document.getElementById('convertStatusModal');
    if (!modal) return;
    modal.style.display = 'flex';
    loadConvertStatus();
    if (convertStatusTimer) clearInterval(convertStatusTimer);
    convertStatusTimer = setInterval(loadConvertStatus, 5000);
}

function closeConvertStatus() {
    const modal = document.getElementById('convertStatusModal');
    if (modal) modal.style.display = 'none';
    if (convertStatusTimer) {
        clearInterval(convertStatusTimer);
        convertStatusTimer = null;
    }
}

function loadConvertStatus() {
    if (convertStatusLoading) return;
    const content = document.getElementById('convertStatusContent');
    if (!content) return;
    convertStatusLoading = true;

    let fd = getFdBase('convert_status');
    fetch('admin_ajax.php', { method: 'POST', body: fd })
    .then(readJsonResponse)
    .then(data => {
        if (data.status !== 'ok' || !Array.isArray(data.jobs)) {
            content.textContent = data.msg || 'Nie udało się pobrać statusu konwersji.';
            return;
        }
        if (data.jobs.length === 0) {
            content.textContent = 'Brak zadań konwersji.';
            return;
        }

        const lines = [];
        data.jobs.forEach(job => {
            const progress = Math.max(0, Math.min(100, Number(job.progress) || 0));
            const date = job.created_at ? new Date(job.created_at * 1000).toLocaleString() : '-';
            lines.push('[' + convertStatusLabel(job.status) + '] ' + progress + '%');
            lines.push('Plik: ' + String(job.file || '-'));
            if (job.output) lines.push('Wynik: ' + String(job.output));
            if (job.message) lines.push('Informacja: ' + String(job.message));
            lines.push('Dodano: ' + date);
            lines.push('------------------------------------------------------------');
        });
        content.textContent = lines.join('\n');
        content.scrollTop = 0;
    })
    .catch(() => {
        content.textContent = 'Błąd połączenia z serwerem.';
    })
    .finally(() => {
        convertStatusLoading = false;
    });
}

