/**
 * modules/core/storageAdapter.js — Fetch same-origin a includes/api.php + fallback localStorage.
 */
(function (g) {
    g.modules = g.modules || {};
    g.modules.core = g.modules.core || {};

    var LS_PREFIX = 'grid_auth_fallback_';

    function apiUrl(action) {
        var base = typeof BASE_URL !== 'undefined' ? BASE_URL : '';
        return base + '?action=' + encodeURIComponent(action);
    }

    async function fetchJson(action, options) {
        var opts = Object.assign({ credentials: 'same-origin' }, options || {});
        var headers = Object.assign({}, opts.headers || {});
        if (opts.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
        opts.headers = headers;
        var res = await fetch(apiUrl(action), opts);
        var text = await res.text();
        try {
            return JSON.parse(text);
        } catch (_) {
            return { success: false, error: 'Invalid JSON', raw: text };
        }
    }

    function lsSet(key, obj) {
        try {
            localStorage.setItem(LS_PREFIX + key, JSON.stringify(obj));
        } catch (_) {}
    }

    function lsGet(key, fallback) {
        try {
            var raw = localStorage.getItem(LS_PREFIX + key);
            if (!raw) return fallback;
            var p = JSON.parse(raw);
            return p !== null && typeof p === 'object' ? p : fallback;
        } catch (_) {
            return fallback;
        }
    }

    g.modules.core.storageAdapter = {
        fetchJson: fetchJson,

        getAppSettings: async function () {
            var r = await fetchJson('gridAuthGetAppSettings', { method: 'GET' });
            if (r && r.success && r.data) {
                lsSet('appSettings', r.data);
                return r.data;
            }
            return lsGet('appSettings', {
                requireLogin: false,
                publicSignup: true,
                publicDesktopWithoutUsers: false,
                loginScreen: {
                    bgType: 'default',
                    videoUrl: '',
                    imageUrls: [],
                    slideshowMode: 'sequential',
                    fixedImageIndex: 0,
                    slideshowIntervalSec: 18,
                },
            });
        },

        saveAppSettings: async function (partial) {
            var r = await fetchJson('gridAuthSaveAppSettings', { method: 'POST', body: JSON.stringify(partial || {}) });
            if (r && r.success && r.data) {
                lsSet('appSettings', r.data);
                return r.data;
            }
            var cur = lsGet('appSettings', {
                requireLogin: false,
                publicSignup: true,
                publicDesktopWithoutUsers: false,
                loginScreen: {
                    bgType: 'default',
                    videoUrl: '',
                    imageUrls: [],
                    slideshowMode: 'sequential',
                    fixedImageIndex: 0,
                    slideshowIntervalSec: 18,
                },
            });
            var merged = Object.assign({}, cur, partial || {});
            lsSet('appSettings', merged);
            return merged;
        },

        getUsersBlob: async function () {
            var r = await fetchJson('gridAuthGetUsers', { method: 'GET' });
            if (r && r.success && r.data) {
                lsSet('users', r.data);
                return r.data;
            }
            return lsGet('users', { version: 1, users: [] });
        },

        saveUsersBlob: async function (blob) {
            var r = await fetchJson('gridAuthSaveUsers', { method: 'POST', body: JSON.stringify(blob) });
            if (r && r.success && r.data) {
                lsSet('users', r.data);
                return r.data;
            }
            lsSet('users', blob);
            return blob;
        },

        getFolderPermissionsBlob: async function () {
            var r = await fetchJson('gridAuthGetFolderPermissions', { method: 'GET' });
            if (r && r.success && r.data) {
                lsSet('folderPermissions', r.data);
                return r.data;
            }
            return lsGet('folderPermissions', { version: 1, entries: {} });
        },

        saveFolderPermissionsBlob: async function (blob) {
            var r = await fetchJson('gridAuthSaveFolderPermissions', { method: 'POST', body: JSON.stringify(blob) });
            if (r && r.success && r.data) {
                lsSet('folderPermissions', r.data);
                return r.data;
            }
            lsSet('folderPermissions', blob);
            return blob;
        },

        webAuthnBegin: async function (body) {
            return fetchJson('gridAuthWebAuthnBegin', { method: 'POST', body: JSON.stringify(body || {}) });
        },

        webAuthnFinish: async function (body) {
            return fetchJson('gridAuthWebAuthnFinish', { method: 'POST', body: JSON.stringify(body || {}) });
        },
    };
})(typeof window !== 'undefined' ? window : this);
