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

type StoredInfoPanelData = {
   [key: string]: {
      version: number;
      interval: string;
   };
};

export default class extends Controller<HTMLDivElement> {
   static values = {
      pageId: String,
      version: Number,
      useSessionStorage: Boolean,
   };

   declare readonly pageIdValue: string;
   declare readonly versionValue: number;
   declare readonly useSessionStorageValue: boolean;

   private readonly storageKey = 'info_panels';

   private get storage(): Storage {
      if (this.useSessionStorageValue) {
         return window.sessionStorage;
      }
      return window.localStorage;
   }

   connect() {
      const storedData = this.getStoredData();
      const panelId = `info-panel-${this.pageIdValue}`;
      const storedPanel = storedData[panelId];

      if (storedPanel && storedPanel.version >= this.versionValue) {
         this.element.remove();
         return;
      }
   }

   close(): void {
      this.element.remove();
      this.updateStorage();
   }

   private getStoredData(): StoredInfoPanelData {
      try {
         const data = this.storage.getItem(this.storageKey);
         return data ? JSON.parse(data) : {};
      } catch (e) {
         const storageName = this.useSessionStorageValue ? 'sessionStorage' : 'localStorage';
         console.error(`Error parsing info_panels from ${storageName}`, e);
         return {};
      }
   }

   private updateStorage(): void {
      const storedData = this.getStoredData();
      const panelId = `info-panel-${this.pageIdValue}`;

      storedData[panelId] = {
         version: this.versionValue,
         interval: 'Infinity',
      };

      this.storage.setItem(this.storageKey, JSON.stringify(storedData));
   }
}
