import { Controller } from '@hotwired/stimulus';

export default class extends Controller<HTMLDivElement> {
   initialize() {
      const infoPanel: HTMLElement = this.element;
      const closeButton: HTMLButtonElement = this.element.querySelector('[data-close]') as HTMLButtonElement;

      let localInfoPanel = null;
      if (window.localStorage.getItem('info_panels')) {
         const localInfoPanelsData = JSON.parse(window.localStorage.getItem('info_panels'));
         localInfoPanel = localInfoPanelsData[`info-panel-${infoPanel.dataset['infopanel']}`];
      }

      if (localInfoPanel && localInfoPanel['version'] >= infoPanel.dataset['version']) {
         let infoPanelElements = document.querySelectorAll(`[data-infopanel="${infoPanel.dataset['infopanel']}"]`);
         infoPanelElements.forEach(element => {
            element.remove();
         });
      }

      closeButton.onclick = () => {
         const infoPanel_version = infoPanel.dataset['version'];
         infoPanel.remove();
         const localInfoPanelsData = JSON.parse(window.localStorage.getItem('info_panels') ?? '{}');
         localInfoPanelsData[`info-panel-${infoPanel.dataset['infopanel']}`] = {
            version: infoPanel_version,
            interval: 'Infinity'
         };
         window.localStorage.setItem('info_panels', JSON.stringify(localInfoPanelsData));
      }
   }
}
