(() => {
  'use strict';

  const knownDatabaseNames = ['pyro-google-fonts-v1'];
  const list = document.getElementById('databaseList');
  const button = document.getElementById('resetButton');
  const localStorageList = document.getElementById('localStorageList');
  const localStorageButton = document.getElementById('localStorageResetButton');
  const resetAllButton = document.getElementById('resetAllButton');
  const status = document.getElementById('status');
  let databaseNames = [];
  let storageKeys = [];

  const errorMessage = (error, fallback) => error instanceof Error ? error.message : fallback;
  const setStatus = (message, tone = '') => {
    status.textContent = String(message || '');
    if (tone) status.dataset.tone = tone;
    else delete status.dataset.tone;
  };

  const discoverDatabases = async () => {
    if (!globalThis.indexedDB) throw new Error('Dieser Browser unterstützt IndexedDB nicht.');
    if (typeof indexedDB.databases !== 'function') return [...knownDatabaseNames];
    const databases = await indexedDB.databases();
    return databases
      .map((database) => database.name)
      .filter((name) => typeof name === 'string' && name.startsWith('pyro-'));
  };

  const renderDatabases = () => {
    list.replaceChildren();
    if (!databaseNames.length) {
      list.textContent = 'Keine PYRO-Datenbank gefunden.';
      button.disabled = true;
      return;
    }
    const items = document.createElement('ul');
    databaseNames.forEach((name) => {
      const item = document.createElement('li');
      const code = document.createElement('code');
      code.textContent = name;
      item.append(code);
      items.append(item);
    });
    list.append(items);
    button.disabled = false;
  };

  const discoverStorageKeys = () => Object.keys(localStorage)
    .filter((key) => key.startsWith('pyro-') || key === 'paint-studio-theme')
    .sort((left, right) => left.localeCompare(right));

  const renderStorageKeys = () => {
    localStorageList.replaceChildren();
    if (!storageKeys.length) {
      localStorageList.textContent = 'Keine PYRO-localStorage-Einträge gefunden.';
      localStorageButton.disabled = true;
      return;
    }
    const items = document.createElement('ul');
    storageKeys.forEach((key) => {
      const item = document.createElement('li');
      const code = document.createElement('code');
      code.textContent = key;
      item.append(code);
      items.append(item);
    });
    localStorageList.append(items);
    localStorageButton.disabled = false;
  };

  const clearPyroLocalStorage = () => {
    storageKeys.forEach((key) => localStorage.removeItem(key));
    storageKeys = discoverStorageKeys();
    renderStorageKeys();
  };

  const deleteDatabase = (name) => new Promise((resolve, reject) => {
    const request = indexedDB.deleteDatabase(name);
    request.onsuccess = () => resolve({ name, deleted: true });
    request.onerror = () => reject(request.error || new Error(name + ' konnte nicht gelöscht werden.'));
    request.onblocked = () => resolve({ name, deleted: false, blocked: true });
  });

  const refresh = async () => {
    try {
      databaseNames = await discoverDatabases();
      storageKeys = discoverStorageKeys();
      renderDatabases();
      renderStorageKeys();
    } catch (error) {
      const message = errorMessage(error, 'Browserdaten konnten nicht gelesen werden.');
      databaseNames = [];
      list.textContent = message;
      button.disabled = true;
      setStatus(message, 'error');
    }
  };

  button.addEventListener('click', async () => {
    if (!databaseNames.length) return;
    if (!confirm('Wirklich ' + databaseNames.length + ' PYRO-Datenbank(en) löschen?')) return;
    button.disabled = true;
    setStatus('IndexedDB wird gelöscht …');
    try {
      const results = await Promise.all(databaseNames.map(deleteDatabase));
      const blocked = results.filter((result) => result.blocked);
      if (blocked.length) setStatus('Löschen blockiert: ' + blocked.map((result) => result.name).join(', '), 'error');
      else {
        databaseNames = [];
        renderDatabases();
        setStatus('PYRO-IndexedDB wurde vollständig gelöscht.', 'success');
      }
    } catch (error) {
      setStatus('Fehler beim Löschen: ' + errorMessage(error, 'Unbekannter Fehler'), 'error');
      button.disabled = false;
    }
  });

  localStorageButton.addEventListener('click', () => {
    if (!storageKeys.length) return;
    if (!confirm('Wirklich ' + storageKeys.length + ' PYRO-localStorage-Eintrag/Einträge löschen?')) return;
    try {
      clearPyroLocalStorage();
      setStatus('PYRO-localStorage wurde vollständig gelöscht.', 'success');
    } catch (error) {
      setStatus('Fehler beim Löschen: ' + errorMessage(error, 'Unbekannter Fehler'), 'error');
    }
  });

  resetAllButton.addEventListener('click', async () => {
    if (!confirm('Wirklich alle IndexedDB- und localStorage-Daten von PYRO löschen?')) return;
    button.disabled = true;
    localStorageButton.disabled = true;
    resetAllButton.disabled = true;
    setStatus('Alle PYRO-Browserdaten werden gelöscht …');
    try {
      clearPyroLocalStorage();
      const results = await Promise.all(databaseNames.map(deleteDatabase));
      const blocked = results.filter((result) => result.blocked);
      if (blocked.length) setStatus('localStorage gelöscht; IndexedDB blockiert: ' + blocked.map((result) => result.name).join(', '), 'error');
      else {
        databaseNames = [];
        renderDatabases();
        setStatus('Alle PYRO-Browserdaten wurden vollständig gelöscht.', 'success');
      }
    } catch (error) {
      setStatus('Fehler beim Löschen: ' + errorMessage(error, 'Unbekannter Fehler'), 'error');
    } finally {
      resetAllButton.disabled = false;
      if (databaseNames.length) button.disabled = false;
      if (storageKeys.length) localStorageButton.disabled = false;
    }
  });

  void refresh();
})();
