let myGallery = null;

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 });

    let searchInput = document.getElementById('searchInput');
    const suppImg = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
    const suppVid = ['mp4', 'webm']; const extVid = ['mkv', 'avi'];
    const suppAudio = ['mp3', 'wav', 'ogg', 'oga', 'flac', 'm4a', 'aac'];
    const suppDoc = ['pdf', 'txt', 'json', 'xml', 'csv', 'html', 'css', 'js'];
    
    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');
            if (q.length >= 3) {
                resDiv.style.display = 'block'; resDiv.innerHTML = '<div class="s-item" style="color: #666;">Szukam...</div>';
                fetch('search.php?q=' + encodeURIComponent(q)).then(r => r.json()).then(data => {
                    resDiv.innerHTML = '';
                    if(data.length === 0) resDiv.innerHTML = '<div class="s-item" style="color: #999;">Brak wynik\u00f3w</div>'; 
                    else {
                        data.forEach(item => {
                            let isDir = item.is_dir; let fExt = item.name.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 || isV || isAud || isD;
                            let link = '';
                            if (isDir) link = `folder.php?folder=${encodeURIComponent(item.folder)}&path=${encodeURIComponent(item.path === '' ? item.name : item.path + '/' + item.name)}`;
                            else if (isImg || canV) link = `view.php?folder=${encodeURIComponent(item.folder)}&path=${encodeURIComponent(item.path)}&file=${encodeURIComponent(item.name)}`;
                            else if (isEV) link = `play.php?folder=${encodeURIComponent(item.folder)}&path=${encodeURIComponent(item.path)}&file=${encodeURIComponent(item.name)}`;
                            else link = `download.php?folder=${encodeURIComponent(item.folder)}&path=${encodeURIComponent(item.path)}&file=${encodeURIComponent(item.name)}`;
                            
                            let icon = isDir ? '&#128193;' : (isImg ? '&#128247;' : ((isV || isEV) ? '&#127916;' : (isAud ? '&#127925;' : (isD ? '&#128214;' : '&#128196;'))));
                            let thumbTag = isImg ? `<img src="thumb.php?folder=${encodeURIComponent(item.folder)}&path=${encodeURIComponent(item.path)}&file=${encodeURIComponent(item.name)}" style="width:30px; height:30px; object-fit:cover; border-radius:4px; margin-right:10px;">` : '';
                            let cssClass = isImg ? 's-item glightbox' : 's-item'; let dataGal = isImg ? 'data-gallery="search-gallery"' : '';
                            resDiv.innerHTML += `<a href="${link}" class="${cssClass}" ${dataGal} target="${isDir || isImg ? '' : '_blank'}">${thumbTag} <span style="margin-right:10px; font-size:18px;">${icon}</span> ${item.name} <span style="color:#888; font-size:0.8em; margin-left:10px;">[${item.folder}]</span></a>`;
                        });
                        if (myGallery) myGallery.reload();
                    }
                }).catch(err => { resDiv.innerHTML = '<div class="s-item" style="color: red; font-size: 13px;">B\u0142\u0105d zapytania.</div>'; });
            } else { resDiv.style.display = 'none'; }
        });
        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 btnUpload = document.getElementById('btnUpload');
    const uploader = document.getElementById('fileUploader');
    if(btnUpload && uploader) {
        btnUpload.addEventListener('click', () => uploader.click());
        uploader.addEventListener('change', function() {
            if(this.files.length === 0) return;
            let fd = new FormData();
            fd.append('action', 'upload'); 
            fd.append('folder', this.dataset.folder);
            fd.append('path', this.dataset.path); 
            
            for (let i = 0; i < this.files.length; i++) {
                fd.append('files[]', this.files[i]);
            }
            
            btnUpload.innerText = "Wgrywanie... (" + this.files.length + ")"; 
            btnUpload.disabled = true;
            
            fetch('admin_ajax.php', { method: 'POST', body: fd })
            .then(r => r.json())
            .then(data => { if(data.status === 'ok') location.reload(); else { alert(data.msg); btnUpload.innerText = "Wgraj"; btnUpload.disabled = false; } })
            .catch(() => { alert('Błąd połączenia.'); btnUpload.innerText = "Wgraj"; btnUpload.disabled = false; });
        });
    }

    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;
            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(r => r.json())
            .then(data => {
                alert(data.msg);
                btnCookies.innerHTML = oldText;
                btnCookies.disabled = false;
            })
            .catch(() => {
                alert('Błąd połączenia z serwerem.');
                btnCookies.innerHTML = oldText;
                btnCookies.disabled = 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);
    }
    fetch('admin_ajax.php', { method: 'POST', body: fd }).then(r => r.json()).then(d => { if(d.status === 'ok') location.reload(); else alert('B\u0142\u0105d operacji.'); });
}

function adminMkdir() {
    let name = prompt('Podaj nazw\u0119 nowego folderu:');
    if(!name) return;
    let fd = getFdBase('mkdir'); fd.append('name', name);
    fetch('admin_ajax.php', { method: 'POST', body: fd }).then(r => r.json()).then(d => { if(d.status === 'ok') location.reload(); else alert(d.msg); });
}

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);
    fetch('admin_ajax.php', { method: 'POST', body: fd }).then(r => r.json()).then(d => { alert(d.msg); });
}

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);

    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(r => r.json()).then(d => { if(d.status === 'ok') location.reload(); else alert(d.msg || 'B\u0142\u0105d.'); });
}

// 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); });
    
    fetch('admin_ajax.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(d => { if(d.status === 'ok') location.reload(); else alert(d.msg || 'B\u0142\u0105d podczas usuwania.'); });
}

function adminYtLog() {
    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(r => r.json())
    .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 = "Wyst\u0105pi\u0142 b\u0142\u0105d.";
        }
    });
}

function adminYtLogClear() {
    if(!confirm("Czy na pewno chcesz wyczy\u015bci\u0107 logi?")) return;
    let fd = getFdBase('yt_log_clear');
    fetch('admin_ajax.php', { method: 'POST', body: fd })
    .then(() => { adminYtLog(); });
}
