// public/assets/prefs.js
/* English comments: user preference storage and sync */

(function () {
  const DEFAULT_PREFS = {
    language: 'en',
    theme: 'dark',
    table_mode: 'pagination',
    table_page_size: 50,
    tables: {},
  };

  let prefs = { ...DEFAULT_PREFS };
  let loaded = false;
  let saveTimer = null;

  function mergePrefs(next) {
    if (!next || typeof next !== 'object') return;
    prefs = {
      ...prefs,
      ...next,
      tables: { ...(prefs.tables || {}), ...(next.tables || {}) },
    };
  }

  async function load() {
    if (loaded) return prefs;
    const res = await window.Api.request('/api/account', { method: 'GET' });
    const data = res?.data || res || {};
    mergePrefs(data.ui || {});
    loaded = true;
    return prefs;
  }

  function get() {
    return prefs;
  }

  function getTable(id) {
    if (!id) return {};
    return (prefs.tables && prefs.tables[id]) ? prefs.tables[id] : {};
  }

  function scheduleSave() {
    if (!loaded) return;
    if (saveTimer) clearTimeout(saveTimer);
    saveTimer = setTimeout(() => {
      saveTimer = null;
      save().catch(() => {});
    }, 500);
  }

  async function save() {
    if (!loaded) return;
    await window.Api.request('/api/account', {
      method: 'POST',
      body: { ui: prefs },
    });
  }

  function setTable(id, data) {
    if (!id) return;
    prefs.tables = { ...(prefs.tables || {}), [id]: { ...(prefs.tables?.[id] || {}), ...data } };
    scheduleSave();
  }

  function setUi(key, value) {
    if (!key) return;
    prefs[key] = value;
    scheduleSave();
  }

  window.UserPrefs = {
    load,
    get,
    getTable,
    setTable,
    setUi,
  };
})();
