jQuery(function ($) {
    const currentFolderId = () => {
        return localStorage.getItem("current_folder_id") ?? null
    }

    function loadFolder(folder_id = "") {
        $.post(NIXFILE_AJAX.ajax, {
            action: "nixfile_list",
            _ajax_nonce: NIXFILE_AJAX.nonce,
            folder_id: folder_id
        }, function (res) {
            let box = $("#nixfile-gallery");
            let breadcrumb = $("#breadcrumb");
            box.empty();
            breadcrumb.empty();
            if (!res.success) {
                box.html("<p>Error loading data</p>");
                return;
            }
            let path = res.data.current_folder.path;
            path = Object.entries(path);
            let folders = res.data.folders;
            let files = res.data.files;
            console.log(path)
            path.forEach(([id, title], i) => {
                console.log(id, title);
                breadcrumb.append(`
                    <div class="breadcrumb path ${i === path.length - 1 && 'last'}" data-id="${id}">
                        <p>${title} ${i === path.length - 1 ? '' : '/'}</p>
                    </div>
                `);
            });
            folders.forEach(f => {
                box.append(`
                    <div class="item folder" data-id="${f.id}">
                        <img src="https://cdn-icons-png.flaticon.com/512/716/716784.png">
                        <span>${f.title}</span>
                    </div>
                `);
            });
            files.forEach(file => {
                console.log(file)
                box.append(`
                    <div class="item file">
                        <img src="${file.secure_link}">
                        <span>${file.title}</span>
                    </div>
                `);
            });
        });
    }

    $(document).on("click", ".item.folder", function () {
        let id = $(this).data("id");
        if (id !== currentFolderId()) {
            localStorage.setItem("current_folder_id", id)
            loadFolder(id);
        }
    });
    $(document).on("click", ".breadcrumb.path", function () {
        let id = $(this).data("id");
        if (id !== currentFolderId()) {
            localStorage.setItem("current_folder_id", id)
            loadFolder(id)
        }
    });
    loadFolder(currentFolderId());
    $("#nix-upload-input").on("change", function () {
        let file = this.files[0];
        if (!file) return;
        let tempId = "upload-" + Date.now();
        $("#nixfile-gallery").append(`
        <div class="item uploading" id="${tempId}">
            <div class="thumb preview" style="
                width: 100%;
                height: 120px;
                background-color: #ddd;
                background-size: cover;
                background-position: center;
                border-radius: 6px;
            "></div>
            <div class="upload-progress" style="
                width: 100%;
                background: #eee;
                border-radius: 6px;
                margin-top: 8px;
            ">
                <div class="upload-progress-bar" style="
                    width: 0%;
                    height: 6px;
                    background: #4caf50;
                    border-radius: 6px;
                "></div>
            </div>
            <span style="font-size: 12px; color:#666;">Uploading…</span>
        </div>
    `);
        $("#" + tempId + " .thumb").css(
            "background-image",
            `url(${URL.createObjectURL(file)})`
        );
        let formData = new FormData();
        formData.append("action", "nixfile_upload");
        formData.append("_ajax_nonce", NIXFILE_AJAX.nonce);
        if (currentFolderId)
            formData.append("folder_id", currentFolderId);
        formData.append("file", file);
        $.ajax({
            url: NIXFILE_AJAX.ajax,
            method: "POST",
            data: formData,
            contentType: false,
            processData: false,
            xhr: function () {
                let xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener("progress", function (e) {
                    if (e.lengthComputable) {
                        let percent = Math.round((e.loaded / e.total) * 100);
                        $("#" + tempId + " .upload-progress-bar").css("width", percent + "%");
                    }
                });
                return xhr;
            },
            success: function (res) {
                if (!res.success) {
                    $("#" + tempId + " span").text("Failed");
                    $("#" + tempId + " .upload-progress-bar").css("background", "red");
                    return;
                }
                let fileData = res.data;
                $("#" + tempId).replaceWith(`
                <div class="item file">
                    <img src="${fileData.secure_link}" style="
                        width:100%;
                        height:120px;
                        object-fit:cover;
                        border-radius:6px;
                    ">
                    <span>${fileData.title}</span>
                </div>
            `);
            },
            error: function () {
                $("#" + tempId + " span").text("Upload Error");
                $("#" + tempId + " .upload-progress-bar").css("background", "red");
            }
        });
    });
    $("#nixfile-settings").on("submit", function (e) {
        e.preventDefault();

        const formData = new FormData(this);

        formData.append("action", "nixfile_settings");
        formData.append("_ajax_nonce", NIXFILE_AJAX.nonce);

        $.ajax({
            url: NIXFILE_AJAX.ajax,
            method: "POST",
            data: formData,
            processData: false,
            contentType: false,

            success: function (res) {
                console.log("Settings saved:", res);
                loadFolder(currentFolderId())
            },
            error: function (err) {
                console.error("Error saving settings:", err);
            }
        });
    });
});
