/**
 * Flexia — espacios compartidos del explorador (comunitario + departamentos).
 */
(function (global) {
    'use strict';

    var cache = null;

    function apiUrl() {
        return '?action=';
    }

    function fetchSpaces(force) {
        if (!force && cache) {
            return Promise.resolve(cache);
        }
        return fetch(apiUrl() + 'explorerSharedSpacesGet', { credentials: 'same-origin', cache: 'no-store' })
            .then(function (res) { return res.json(); })
            .then(function (data) {
                if (!data || !data.success) {
                    throw new Error((data && data.error) || 'explorerSharedSpacesGet');
                }
                cache = data.data || null;
                return cache;
            });
    }

    function saveSpaces(patch) {
        return fetch(apiUrl() + 'explorerSharedSpacesSave', {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ patch: patch || {} }),
        })
            .then(function (res) { return res.json(); })
            .then(function (data) {
                if (!data || !data.success) {
                    throw new Error((data && data.error) || 'explorerSharedSpacesSave');
                }
                cache = data.data || null;
                return cache;
            });
    }

    function invalidateCache() {
        cache = null;
    }

    function withDepartmentId(body, bucket, departmentId) {
        var out = Object.assign({}, body || {});
        if (bucket === 'department' && departmentId) {
            out.departmentId = departmentId;
        }
        return out;
    }

    function withMoveDepartments(body, fromBucket, toBucket, fromDepartmentId, toDepartmentId) {
        var out = Object.assign({}, body || {});
        if (fromBucket === 'department' && fromDepartmentId) {
            out.fromDepartmentId = fromDepartmentId;
        }
        if (toBucket === 'department' && toDepartmentId) {
            out.toDepartmentId = toDepartmentId;
        }
        return out;
    }

    function bindConfigPanel() {
        var panel = document.getElementById('explorerSharedSpacesConfig');
        if (!panel || panel.dataset.bound === '1') {
            return;
        }
        panel.dataset.bound = '1';

        var communityEnabled = document.getElementById('essCommunityEnabled');
        var departmentsEnabled = document.getElementById('essDepartmentsEnabled');
        var communityHidden = document.getElementById('essCommunityHiddenUsers');
        var departmentsHidden = document.getElementById('essDepartmentsHiddenUsers');
        var saveBtn = document.getElementById('essSharedSpacesSaveBtn');
        var statusEl = document.getElementById('essSharedSpacesStatus');

        function setStatus(msg) {
            if (statusEl) statusEl.textContent = msg || '';
        }

        function fill(data) {
            if (!data) return;
            if (communityEnabled) communityEnabled.checked = !!(data.community && data.community.enabled);
            if (departmentsEnabled) departmentsEnabled.checked = !!(data.departments && data.departments.enabled);
            if (communityHidden) {
                communityHidden.value = (data.community && data.community.hiddenForUserIds || []).join('\n');
                communityHidden.disabled = !data.canManage;
            }
            if (departmentsHidden) {
                departmentsHidden.value = (data.departments && data.departments.hiddenForUserIds || []).join('\n');
                departmentsHidden.disabled = !data.canManage;
            }
            if (saveBtn) saveBtn.style.display = data.canManage ? '' : 'none';
            panel.style.display = data.canManage ? '' : 'none';
        }

        function parseUserIds(raw) {
            return String(raw || '')
                .split(/[\s,;]+/)
                .map(function (s) { return s.trim(); })
                .filter(Boolean);
        }

        fetchSpaces(true).then(fill).catch(function () {
            panel.style.display = 'none';
        });

        var tabBtn = document.getElementById('explorerCustomizationTabBtn');
        if (tabBtn) {
            tabBtn.addEventListener('click', function () {
                fetchSpaces(true).then(fill).catch(function () {});
            });
        }

        if (saveBtn) {
            saveBtn.addEventListener('click', function () {
                setStatus('Guardando…');
                saveSpaces({
                    communityEnabled: !!(communityEnabled && communityEnabled.checked),
                    departmentsEnabled: !!(departmentsEnabled && departmentsEnabled.checked),
                    communityHiddenForUserIds: parseUserIds(communityHidden && communityHidden.value),
                    departmentsHiddenForUserIds: parseUserIds(departmentsHidden && departmentsHidden.value),
                })
                    .then(function (data) {
                        fill(data);
                        setStatus('Guardado.');
                        try {
                            document.querySelectorAll('.file-explorer').forEach(function (host) {
                                if (typeof host.__gridRefreshSharedSpaces === 'function') {
                                    host.__gridRefreshSharedSpaces();
                                }
                            });
                        } catch (_) {}
                    })
                    .catch(function (e) {
                        setStatus('');
                        if (global.appDialog && global.appDialog.alert) {
                            void global.appDialog.alert(String(e && e.message ? e.message : e));
                        }
                    });
            });
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', bindConfigPanel);
    } else {
        bindConfigPanel();
    }

    global.GridExplorerSharedSpaces = {
        fetch: fetchSpaces,
        save: saveSpaces,
        invalidate: invalidateCache,
        withDepartmentId: withDepartmentId,
        withMoveDepartments: withMoveDepartments,
    };
})(typeof window !== 'undefined' ? window : this);
