/**
 * modules/fileSystem/folderPermissions.js — ACL por carpeta (persistencia híbrida).
 * Clave: bucket + ':' + relPath normalizado (sin barra final).
 */
(function (g) {
    g.modules = g.modules || {};
    g.modules.fileSystem = g.modules.fileSystem || {};

    var adapt = g.modules.core.storageAdapter;
    var cache = null;

    function normalizeRelPath(p) {
        return String(p || '')
            .replace(/\\/g, '/')
            .replace(/^\/+|\/+$/g, '');
    }

    function makeKey(bucket, relPath) {
        return String(bucket || 'files') + ':' + normalizeRelPath(relPath);
    }

    async function load() {
        if (cache) return cache;
        cache = await adapt.getFolderPermissionsBlob();
        if (!cache.entries) cache.entries = {};
        return cache;
    }

    g.modules.fileSystem.folderPermissions = {
        makeKey: makeKey,
        normalizeRelPath: normalizeRelPath,

        load: load,

        getEntry: async function (bucket, relPath) {
            var blob = await load();
            var k = makeKey(bucket, relPath);
            return blob.entries[k] || null;
        },

        setEntry: async function (bucket, relPath, entry) {
            var blob = await load();
            var k = makeKey(bucket, relPath);
            blob.entries[k] = Object.assign(
                {
                    requireBiometric: false,
                    acl: { read: true, write: true, delete: true, rename: true },
                },
                entry || {}
            );
            cache = await adapt.saveFolderPermissionsBlob(blob);
            return cache.entries[k];
        },

        removeEntry: async function (bucket, relPath) {
            var blob = await load();
            delete blob.entries[makeKey(bucket, relPath)];
            cache = await adapt.saveFolderPermissionsBlob(blob);
        },

        /** Modal simple de permisos (usa modules/ui/messages + CSS auth). */
        openFolderPermissionsModal: function (ctx) {
            var messages = g.modules.ui.messages;
            var bucket = ctx.bucket || 'files';
            var parentPath = normalizeRelPath(ctx.parentPath || '');
            var folderName = ctx.folderName || '';
            var relTarget = parentPath ? parentPath + '/' + folderName : folderName;

            var wrap = document.createElement('div');
            wrap.className = 'auth-modal-backdrop';
            var box = document.createElement('div');
            box.className = 'auth-modal';
            box.innerHTML =
                '<h3 class="auth-modal-title">' +
                messages.text('permTitle') +
                '</h3>' +
                '<p class="auth-modal-path">' +
                messages.escape(relTarget || '(raíz)') +
                '</p>' +
                '<label class="auth-check"><input type="checkbox" id="permBio" /> ' +
                messages.text('permRequireBio') +
                '</label>' +
                '<div class="auth-perm-grid">' +
                '<label><input type="checkbox" id="permRead" checked /> ' +
                messages.text('permRead') +
                '</label>' +
                '<label><input type="checkbox" id="permWrite" checked /> ' +
                messages.text('permWrite') +
                '</label>' +
                '<label><input type="checkbox" id="permDel" checked /> ' +
                messages.text('permDelete') +
                '</label>' +
                '<label><input type="checkbox" id="permRen" checked /> ' +
                messages.text('permRename') +
                '</label>' +
                '</div>' +
                '<div class="auth-modal-actions">' +
                '<button type="button" class="auth-btn auth-btn-secondary" id="permCancel">' +
                messages.text('cancel') +
                '</button>' +
                '<button type="button" class="auth-btn auth-btn-primary" id="permSave">' +
                messages.text('save') +
                '</button>' +
                '</div>';

            wrap.appendChild(box);
            document.body.appendChild(wrap);

            var api = g.modules.fileSystem.folderPermissions;

            api.getEntry(bucket, relTarget).then(function (ex) {
                var bio = box.querySelector('#permBio');
                var pr = box.querySelector('#permRead');
                var pw = box.querySelector('#permWrite');
                var pd = box.querySelector('#permDel');
                var rn = box.querySelector('#permRen');
                if (ex) {
                    bio.checked = !!ex.requireBiometric;
                    if (ex.acl) {
                        pr.checked = !!ex.acl.read;
                        pw.checked = !!ex.acl.write;
                        pd.checked = !!ex.acl.delete;
                        rn.checked = ex.acl.rename !== false;
                    }
                }
            });

            function close() {
                if (wrap.parentNode) wrap.parentNode.removeChild(wrap);
            }

            box.querySelector('#permCancel').addEventListener('click', close);
            box.querySelector('#permSave').addEventListener('click', function () {
                var bio = box.querySelector('#permBio').checked;
                var acl = {
                    read: box.querySelector('#permRead').checked,
                    write: box.querySelector('#permWrite').checked,
                    delete: box.querySelector('#permDel').checked,
                    rename: box.querySelector('#permRen').checked,
                };
                api.setEntry(bucket, relTarget, { requireBiometric: bio, acl: acl }).then(function () {
                    messages.toast(messages.text('permSaved'));
                    close();
                });
            });
            wrap.addEventListener('click', function (e) {
                if (e.target === wrap) close();
            });
        },
    };
})(typeof window !== 'undefined' ? window : this);
