(function (global) {
  var mode = 'neo-bars';

  function getMode() {
    return mode;
  }

  function setMode(m, persist) {
    mode = m;
    global.__vizMode = m;
    document.querySelectorAll('#global-viz-toolbar .global-viz-btn').forEach(function (btn) {
      btn.classList.toggle('active', btn.dataset.viz === m);
    });
    document.dispatchEvent(new CustomEvent('foodlinkk:vizmode', { detail: { mode: m } }));
    if (persist !== false) {
      fetch('/api/preferences/ui', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ global_viz_mode: m }),
      }).catch(function () {});
    }
  }

  function buildToolbar(container) {
    if (!container || !global.VizEngine) return;
    container.innerHTML = global.VizEngine.MODES.map(function (m) {
      var short = m.label.replace('Neo ', '');
      var active = mode === m.id ? ' active' : '';
      return '<button type="button" class="global-viz-btn' + active + '" data-viz="' + m.id + '" title="' + m.label + '">' + short + '</button>';
    }).join('');
    container.querySelectorAll('.global-viz-btn').forEach(function (btn) {
      btn.addEventListener('click', function () { setMode(btn.dataset.viz); });
    });
  }

  function init() {
    if (global.location && global.location.pathname === '/') return;
    fetch('/api/preferences/ui')
      .then(function (r) { return r.json(); })
      .then(function (prefs) {
        mode = prefs.global_viz_mode || 'neo-bars';
        global.__vizMode = mode;
        buildToolbar(document.getElementById('global-viz-toolbar'));
        document.dispatchEvent(new CustomEvent('foodlinkk:vizmode', { detail: { mode: mode } }));
      })
      .catch(function () {
        buildToolbar(document.getElementById('global-viz-toolbar'));
      });
  }

  global.GlobalViz = { getMode: getMode, setMode: setMode, init: init };
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})(window);
