import { scenarios } from './scenarios.js';

export function init() {
  const showButton = document.getElementById('show-dialog'),
    mapDialog = document.getElementById('map-dialog'),
    selectEl = mapDialog.querySelector('select'),
    confirmBtn = mapDialog.querySelector('#confirm-btn');

  Object.keys(scenarios).reverse().forEach(scenario => {
    const option = document.createElement('option');
    option.setAttribute('value', scenario);
    option.textContent = scenarios[scenario].title;
    selectEl.prepend(option);
  });

  return {
    selectCurrentOptionOnPageLoad() {
      mapDialog.querySelectorAll('option').forEach((option, index) =>
        option.selected = option.value === localStorage.getItem('map') || index === 0
      );

      return this;
    },

    showOnClick() {
      showButton.addEventListener('click', () => {
        mapDialog.showModal();
      });

      return this;
    },

    updateValueOnSelection() {
      selectEl.addEventListener('change', () => {
        confirmBtn.value = selectEl.value;
      });

      return this;
    },

    changeMapOnConfirm(loadFn) {
      confirmBtn.addEventListener('click', e => {
        e.preventDefault();
        localStorage.removeItem('pan-zoom');
        localStorage.setItem('map', selectEl.value);
        loadFn(scenarios[selectEl.value]?.hashed || `assets/images/${selectEl.value}.svg`);
        mapDialog.close();
      });
    }
  };
}

export const defaultMap = scenarios.sideShow;
