(function (global) {
  function init(pageKey, renderFn) {
    if (!global.DashboardLayout || typeof renderFn !== 'function') return Promise.resolve();
    return global.DashboardLayout.loadPrefs().then(function (prefs) {
      var mode = (prefs.viz_modes || {})[pageKey] || prefs.global_viz_mode || 'neo-bars';
      var toolbar = document.getElementById('viz-toolbar');
      if (toolbar) {
        global.DashboardLayout.buildVizSelector(
          toolbar,
          Object.assign({}, prefs, { global_viz_mode: mode }),
          function (m) {
            var vizModes = Object.assign({}, prefs.viz_modes || {}, {});
            vizModes[pageKey] = m;
            global.DashboardLayout.saveViz(prefs.global_viz_mode, vizModes);
            renderFn(m);
          }
        );
      }
      renderFn(mode);
      document.addEventListener('foodlinkk:vizmode', function (ev) {
        renderFn(ev.detail.mode);
      });
    });
  }

  global.PageViz = { init: init };
})(window);
