/**
 * ChiliColectivo Mic – eingebettete Extension-Einstellungen (2.1.41)
 */
(function () {
  const params = new URLSearchParams(window.location.search);
  const urlDeviceId = String(params.get('device') || '').trim();
  const showDeviceDebug = params.get('debug') === '1';

  const badge = document.getElementById('licenseStatusBadge');
  const statusText = document.getElementById('licenseStatusText');
  const emailInput = document.getElementById('licenseEmailInput');
  const keyInput = document.getElementById('licenseKeyInput');
  const activateBtn = document.getElementById('licenseActivateBtn');
  const clearBtn = document.getElementById('licenseClearBtn');
  const syncStatus = document.getElementById('micWebSyncStatus');
  const deviceIdEl = document.getElementById('micWebDeviceId');
  const versionEl = document.getElementById('micExtVersion');
  const portalLinkWrap = document.getElementById('micPortalLinkWrap');
  const portalLink = document.getElementById('micPortalLink');
  const toast = document.getElementById('toast');
  const hotkeyDisplay = document.getElementById('hotkeyDisplay');
  const hotkeyHint = document.getElementById('hotkeyHint');
  const licenseCountdownBox = document.getElementById('licenseCountdownBox');
  const licenseCountdownLabel = document.getElementById('licenseCountdownLabel');
  const licenseCountdownValue = document.getElementById('licenseCountdownValue');
  const deviceBar = document.getElementById('micWebDeviceBar');
  const micUpdateBanner = document.getElementById('micUpdateBanner');
  const micUpdateBannerText = document.getElementById('micUpdateBannerText');
  const micUpdateBannerHint = document.getElementById('micUpdateBannerHint');
  const micUpdateCurrentVersion = document.getElementById('micUpdateCurrentVersion');
  const micUpdateStatusText = document.getElementById('micUpdateStatusText');
  const micUpdateHint = document.getElementById('micUpdateHint');
  const micUpdateCheckBtn = document.getElementById('micUpdateCheckBtn');
  const micUpdateDownloadLatest = document.getElementById('micUpdateDownloadLatest');
  const micUpdateDownloadPrevious = document.getElementById('micUpdateDownloadPrevious');
  const micUpdateDownloadLatestTop = document.getElementById('micUpdateDownloadLatestTop');
  const micUpdateDownloadPreviousTop = document.getElementById('micUpdateDownloadPreviousTop');
  const updateSection = document.getElementById('updateSection');

  let licenseCounterTimer = null;
  let installedVersion = '';
  let settingsHydrated = false;
  let saveSettingsTimer = null;

  function resolveInstalledVersion() {
    const fromUrl = String(params.get('v') || '').trim();
    if (fromUrl) return fromUrl;
    try {
      return chrome?.runtime?.getManifest?.()?.version || '';
    } catch (_) {
      return '';
    }
  }

  function setDisplayedVersion(version) {
    const v = String(version || resolveInstalledVersion() || '–').trim() || '–';
    installedVersion = v;
    if (versionEl) versionEl.textContent = v;
    if (micUpdateCurrentVersion) micUpdateCurrentVersion.textContent = v;
    return v;
  }

  setDisplayedVersion();

  let settings = {
    speechLang: 'de-CH',
    previewEnabled: true,
    previewColor: '#D46E6E',
    toolColor: '#D46E6E',
    toolOpacity: 100,
    previewOpacity: 100,
    micTipsEnabled: false,
    previewEnterToInsert: false,
    hotkey: { key: 'J', altKey: true, ctrlKey: false, shiftKey: false, metaKey: false },
    outCounterEnabled: true,
    outTarget: 0,
  };
  let recordingHotkey = false;
  let deviceId = urlDeviceId;
  let portalUrl = '';

  function showToast(msg) {
    if (!toast) return;
    toast.textContent = msg;
    toast.classList.remove('hidden');
    clearTimeout(showToast._t);
    showToast._t = setTimeout(() => toast.classList.add('hidden'), 3200);
  }

  function setSyncStatus(text) {
    if (!syncStatus || !showDeviceDebug) return;
    syncStatus.textContent = text;
  }

  if (deviceBar) {
    if (showDeviceDebug) {
      deviceBar.classList.remove('hidden');
      deviceBar.setAttribute('aria-hidden', 'false');
    } else {
      deviceBar.classList.add('hidden');
      deviceBar.setAttribute('aria-hidden', 'true');
    }
  }

  function sendMessage(type, payload = {}) {
    return new Promise((resolve, reject) => {
      try {
        chrome.runtime.sendMessage({ type, ...payload }, (resp) => {
          if (chrome.runtime.lastError) {
            reject(new Error(chrome.runtime.lastError.message));
            return;
          }
          if (resp?.success === false) {
            reject(new Error(resp.error || 'Anfrage fehlgeschlagen'));
            return;
          }
          resolve(resp || {});
        });
      } catch (e) {
        reject(e);
      }
    });
  }

  function formatHotkey(hk) {
    if (!hk?.key) return 'Standard (⌥J)';
    const isMac = navigator.platform.toUpperCase().includes('MAC');
    const key = hk.key.length === 1 ? hk.key.toUpperCase() : hk.key;
    if (isMac) {
      return `${hk.altKey ? '⌥' : ''}${hk.ctrlKey ? '⌃' : ''}${hk.shiftKey ? '⇧' : ''}${hk.metaKey ? '⌘' : ''}${key}`;
    }
    const parts = [];
    if (hk.ctrlKey) parts.push('Ctrl');
    if (hk.altKey) parts.push('Alt');
    if (hk.shiftKey) parts.push('Shift');
    if (hk.metaKey) parts.push('Meta');
    parts.push(key);
    return parts.join('+');
  }

  function normalizeOutTarget(raw) {
    const n = parseInt(String(raw || '').replace(/\D/g, ''), 10);
    return Number.isFinite(n) && n > 0 ? n : 0;
  }

  function formatLicenseKeyInput(raw) {
    const clean = String(raw || '').toUpperCase().replace(/[^A-Z0-9]/g, '');
    const body = clean.startsWith('CMIC') ? clean.slice(4) : clean;
    const parts = body.match(/.{1,4}/g) || [];
    if (!parts.length) return '';
    return ['CMIC', ...parts.slice(0, 4)].join('-');
  }

  function readFormSettings() {
    return {
      ...settings,
      previewEnabled: document.getElementById('previewEnabled')?.checked !== false,
      previewColor: document.getElementById('previewColor')?.value || settings.previewColor,
      toolColor: document.getElementById('toolColor')?.value || settings.toolColor,
      micTipsEnabled: document.getElementById('micTipsEnabled')?.checked === true,
      previewEnterToInsert: document.getElementById('previewEnterToInsert')?.checked === true,
      hotkey: settings.hotkey,
      outCounterEnabled: document.getElementById('outCounterEnabled')?.checked !== false,
      outTarget: normalizeOutTarget(document.getElementById('outTargetInput')?.value),
    };
  }

  function fillForm(data) {
    settings = { ...settings, ...data };
    if (document.getElementById('previewEnabled')) {
      document.getElementById('previewEnabled').checked = settings.previewEnabled !== false;
    }
    if (document.getElementById('previewColor') && settings.previewColor) {
      document.getElementById('previewColor').value = settings.previewColor;
    }
    if (document.getElementById('toolColor') && settings.toolColor) {
      document.getElementById('toolColor').value = settings.toolColor;
    }
    if (document.getElementById('micTipsEnabled')) {
      document.getElementById('micTipsEnabled').checked = !!settings.micTipsEnabled;
    }
    if (document.getElementById('previewEnterToInsert')) {
      document.getElementById('previewEnterToInsert').checked = !!settings.previewEnterToInsert;
    }
    if (document.getElementById('outCounterEnabled')) {
      document.getElementById('outCounterEnabled').checked = settings.outCounterEnabled !== false;
    }
    if (document.getElementById('outTargetInput') && settings.outTarget != null) {
      document.getElementById('outTargetInput').value = settings.outTarget > 0 ? String(settings.outTarget) : '';
    }
    if (hotkeyDisplay) hotkeyDisplay.textContent = formatHotkey(settings.hotkey);
  }

  function normalizeLicensePanelState(licenseState) {
    if (!licenseState) return null;
    if (licenseState.access) return licenseState;
    if (licenseState.valid === true && typeof chillicollectivoBuildLicenseState === 'function') {
      return chillicollectivoBuildLicenseState(licenseState, null);
    }
    return licenseState;
  }

  function stopLicenseCounter() {
    if (licenseCounterTimer) {
      clearInterval(licenseCounterTimer);
      licenseCounterTimer = null;
    }
  }

  function applyCountdownTone(tone) {
    if (!licenseCountdownBox) return;
    licenseCountdownBox.classList.remove('tone-active', 'tone-bonus', 'tone-trial', 'tone-lifetime');
    if (tone === 'active') licenseCountdownBox.classList.add('tone-active');
    else if (tone === 'bonus') licenseCountdownBox.classList.add('tone-bonus');
    else licenseCountdownBox.classList.add('tone-trial');
  }

  function updateLicenseCountdown(state) {
    stopLicenseCounter();
    if (!licenseCountdownBox || !licenseCountdownValue || !licenseCountdownLabel) return;

    const countdown = typeof chillicollectivoResolveLicenseCountdown === 'function'
      ? chillicollectivoResolveLicenseCountdown(state)
      : null;

    if (!countdown) {
      licenseCountdownBox.classList.add('hidden');
      return;
    }

    licenseCountdownLabel.textContent = countdown.label || 'Lizenz – noch';
    applyCountdownTone(countdown.tone || 'active');
    licenseCountdownBox.classList.remove('hidden');

    if (countdown.mode === 'static') {
      licenseCountdownValue.textContent = countdown.staticValue || '—';
      return;
    }

    const anchor = Date.now();
    const initial = Number(countdown.remainingMs || 0);
    const formatValue = (remaining) => (
      (state?.reason === 'trial' && state?.license?.valid !== true)
        || (typeof chillicollectivoCountdownUsesClockFormat === 'function'
          && chillicollectivoCountdownUsesClockFormat(remaining, state))
        ? chillicollectivoFormatTrialCountdown(remaining)
        : chillicollectivoFormatLicenseCountdown(remaining)
    );

    const renderRemaining = () => {
      const remaining = Math.max(0, initial - (Date.now() - anchor));
      licenseCountdownValue.textContent = formatValue(remaining);
      return remaining;
    };

    renderRemaining();
    const intervalMs = initial < 60 * 60 * 1000 ? 250 : 1000;
    licenseCounterTimer = setInterval(() => {
      const remaining = renderRemaining();
      if (remaining <= 0) {
        stopLicenseCounter();
        licenseCountdownBox.classList.add('hidden');
        loadPanel().catch(() => {});
      }
    }, intervalMs);
  }

  function applyMicUpdateDownloadButtons(info) {
    const downloads = typeof chillicollectivoResolveMicUpdateDownloads === 'function'
      ? chillicollectivoResolveMicUpdateDownloads(info)
      : [];
    const latest = downloads.find((entry) => entry.role === 'latest') || downloads[0] || null;
    const previous = downloads.find((entry) => entry.role === 'previous') || downloads[1] || null;
    const showDownloads = !!info?.outdated && downloads.length > 0;

    const pairs = [
      [micUpdateDownloadLatest, latest],
      [micUpdateDownloadLatestTop, latest],
      [micUpdateDownloadPrevious, previous],
      [micUpdateDownloadPreviousTop, previous],
    ];

    for (const [button, entry] of pairs) {
      if (!button) continue;
      const isPrevious = button === micUpdateDownloadPrevious || button === micUpdateDownloadPreviousTop;
      const activeEntry = isPrevious ? previous : latest;
      const visible = showDownloads && !!activeEntry?.url;
      button.classList.toggle('hidden', !visible);
      if (!visible) continue;
      const versionLabel = activeEntry.version ? ` (${activeEntry.version})` : '';
      button.textContent = `${activeEntry.label || (isPrevious ? 'Vorherige Version' : 'Neueste Version')} laden${versionLabel}`;
      button.dataset.downloadUrl = activeEntry.url;
    }
  }

  function renderMicUpdateUi(info, versionOverride) {
    const current = setDisplayedVersion(versionOverride || installedVersion || info?.current);
    const outdated = !!info?.outdated;
    const needsUpgrade = outdated || !!info?.updateRequired;

    if (updateSection) {
      updateSection.classList.toggle('options-collapse-update-shiny', needsUpgrade);
    }

    if (micUpdateStatusText) {
      if (!info) {
        micUpdateStatusText.textContent = 'Update-Status wird geprüft …';
      } else if (!outdated) {
        micUpdateStatusText.textContent = `Aktuelle Version geladen (${info.latest || current}).`;
      } else {
        const downloads = typeof chillicollectivoResolveMicUpdateDownloads === 'function'
          ? chillicollectivoResolveMicUpdateDownloads(info)
          : [];
        const previous = downloads.find((entry) => entry.role === 'previous');
        micUpdateStatusText.textContent = previous
          ? `${info.message || `Version ${info.latest} ist verfügbar.`} Auch Version ${previous.version} steht bereit.`
          : (info.message || `Version ${info.latest} ist verfügbar.`);
      }
    }

    applyMicUpdateDownloadButtons(info);

    if (micUpdateHint) {
      const hint = info?.downloadHint || '';
      micUpdateHint.textContent = hint;
      micUpdateHint.classList.toggle('hidden', !hint || !outdated);
    }

    if (micUpdateBanner && micUpdateBannerText) {
      if (!outdated) {
        micUpdateBanner.classList.add('hidden');
        micUpdateBanner.classList.remove('is-required');
      } else {
        micUpdateBanner.classList.remove('hidden');
        micUpdateBanner.classList.toggle('is-required', !!info.updateRequired);
        const title = micUpdateBanner.querySelector('.mic-update-banner-title');
        if (title) {
          title.textContent = info.updateRequired ? 'Mic-Update erforderlich' : 'Neue Mic-Version verfügbar';
        }
        micUpdateBannerText.textContent = info.message || `Version ${info.latest} ist verfügbar.`;
        if (micUpdateBannerHint) {
          micUpdateBannerHint.textContent = info.downloadHint || 'ZIP laden, Ordner ersetzen, Extension in Chrome neu laden.';
        }
      }
    }
  }

  async function refreshMicUpdateStatus(showResultToast = false) {
    if (micUpdateCheckBtn) micUpdateCheckBtn.disabled = true;
    if (micUpdateStatusText && /wird geladen|wird geprüft/i.test(micUpdateStatusText.textContent || '')) {
      micUpdateStatusText.textContent = 'Update-Status wird geprüft …';
    }
    try {
      const resp = await sendMessage('CHECK_MIC_UPDATE');
      renderMicUpdateUi(resp.micUpdate, installedVersion);
      if (showResultToast) {
        if (resp.micUpdate?.outdated) {
          showToast(`Update verfügbar: Version ${resp.micUpdate.latest}`);
        } else {
          showToast(`Aktuelle Version geladen (${resp.micUpdate?.latest || installedVersion}).`);
        }
      }
      return resp.micUpdate;
    } catch (e) {
      renderMicUpdateUi({
        current: installedVersion,
        latest: installedVersion,
        outdated: false,
        updateRequired: false,
      }, installedVersion);
      if (showResultToast) showToast(e.message || 'Update-Check fehlgeschlagen');
      throw e;
    } finally {
      if (micUpdateCheckBtn) micUpdateCheckBtn.disabled = false;
      if (micUpdateStatusText && /wird geladen|wird geprüft/i.test(micUpdateStatusText.textContent || '')) {
        renderMicUpdateUi({
          current: installedVersion,
          latest: installedVersion,
          outdated: false,
          updateRequired: false,
        }, installedVersion);
      }
    }
  }

  async function openMicUpdateDownload(url) {
    try {
      const resp = await sendMessage('OPEN_MIC_UPDATE_DOWNLOAD', { url: url || '' });
      if (!resp.success) throw new Error(resp.error || 'Download fehlgeschlagen');
      showToast('Download wird geöffnet …');
    } catch (e) {
      showToast(e.message || 'Download nicht verfügbar');
    }
  }

  function renderLicense(licenseState) {
    if (!badge || !statusText) return;
    const state = normalizeLicensePanelState(licenseState);
    const access = state?.access;
    const granted = access === 'granted';
    if (granted) {
      badge.className = 'license-badge license-badge-active';
      badge.textContent = 'Aktiv';
      const email = state?.email || state?.license?.email;
      const key = state?.key || state?.license?.key;
      statusText.textContent = email ? `Lizenz aktiv für ${email}` : (state?.message || 'Lizenz aktiv');
      if (key && keyInput) keyInput.value = formatLicenseKeyInput(key);
      if (email && emailInput) emailInput.value = email;
      updateLicenseCountdown(state);
      return;
    }
    badge.className = 'license-badge license-badge-locked';
    badge.textContent = access === 'expired' ? 'Abgelaufen' : 'Gesperrt';
    statusText.textContent = state?.message || 'Keine aktive Lizenz auf diesem Gerät.';
    updateLicenseCountdown(state);
  }

  async function loadPanel() {
    settingsHydrated = false;
    setSyncStatus('Lade Extension-Daten …');
    const data = await sendMessage('GET_WEB_PANEL_STATE');
    deviceId = data.deviceId || deviceId;
    if (deviceIdEl) deviceIdEl.textContent = deviceId || '–';
    if (versionEl) versionEl.textContent = data.version || installedVersion;
    if (micUpdateCurrentVersion) micUpdateCurrentVersion.textContent = data.version || installedVersion;
    installedVersion = data.version || installedVersion;
    if (data.settings) fillForm(data.settings);
    renderLicense(data.licenseState);
    if (data.licenseState?.email && emailInput && !emailInput.value) {
      emailInput.value = data.licenseState.email;
    }
    renderMicUpdateUi(data.micUpdate, installedVersion);

    if (data.portalOnline && data.portalUrl) {
      portalUrl = data.portalUrl;
      if (portalLinkWrap) portalLinkWrap.classList.remove('hidden');
      if (portalLink) {
        const q = new URLSearchParams({
          device: deviceId || '',
          ext: chrome.runtime.id || '',
          v: data.version || '',
        });
        portalLink.href = `${data.portalUrl}?${q.toString()}`;
      }
      setSyncStatus('Lokal geladen · Server erreichbar');
    } else {
      setSyncStatus('Lokal geladen');
    }
    settingsHydrated = true;
  }

  async function saveSettings(partial = null) {
    const payload = partial ? { ...readFormSettings(), ...partial } : readFormSettings();
    const resp = await sendMessage('SAVE_VOICE_SETTINGS', { settings: payload });
    settings = resp.settings || payload;
    setSyncStatus('Gespeichert (lokal) · ' + new Date().toLocaleString('de-CH'));
  }

  function scheduleSaveSettings(partial = null) {
    if (!settingsHydrated) return;
    clearTimeout(saveSettingsTimer);
    saveSettingsTimer = setTimeout(() => {
      saveSettings(partial).catch(() => {});
    }, 180);
  }

  async function activateLicense() {
    const key = formatLicenseKeyInput(keyInput?.value || '');
    const email = String(emailInput?.value || '').trim().toLowerCase();
    if (!email) throw new Error('Bitte E-Mail eingeben.');
    if (!key) throw new Error('Bitte Lizenzschlüssel eingeben.');

    activateBtn.disabled = true;
    try {
      const resp = await sendMessage('ACTIVATE_LICENSE', { key, email });
      const state = resp.state || (resp.license?.valid && typeof chillicollectivoBuildLicenseState === 'function'
        ? chillicollectivoBuildLicenseState(resp.license, null)
        : null);
      renderLicense(state || resp.license);
      showToast('Lizenz aktiviert');
      setSyncStatus('Lizenz aktiv · ' + new Date().toLocaleString('de-CH'));
    } catch (e) {
      showToast(e.message || 'Aktivierung fehlgeschlagen');
    } finally {
      activateBtn.disabled = false;
    }
  }

  async function clearLicense() {
    const resp = await sendMessage('CLEAR_LICENSE');
    if (keyInput) keyInput.value = '';
    if (emailInput) emailInput.value = '';
    stopLicenseCounter();
    if (licenseCountdownBox) licenseCountdownBox.classList.add('hidden');
    renderLicense(resp.state || { access: 'denied', message: 'Keine aktive Lizenz auf diesem Gerät.' });
    showToast('Lizenz entfernt – Mic gesperrt');
    setSyncStatus('Lizenz entfernt · Mic gesperrt');
  }

  function setupHotkeyCapture() {
    document.getElementById('hotkeyRecord')?.addEventListener('click', () => {
      recordingHotkey = true;
      hotkeyHint?.classList.remove('hidden');
    });
    document.getElementById('hotkeyReset')?.addEventListener('click', () => {
      settings.hotkey = { key: 'J', altKey: true, ctrlKey: false, shiftKey: false, metaKey: false };
      if (hotkeyDisplay) hotkeyDisplay.textContent = formatHotkey(settings.hotkey);
      scheduleSaveSettings({ hotkey: settings.hotkey });
    });
    document.addEventListener('keydown', (e) => {
      if (!recordingHotkey) return;
      e.preventDefault();
      e.stopPropagation();
      if (e.key === 'Escape') {
        recordingHotkey = false;
        hotkeyHint?.classList.add('hidden');
        return;
      }
      settings.hotkey = {
        key: e.key.length === 1 ? e.key.toUpperCase() : e.key,
        altKey: e.altKey,
        ctrlKey: e.ctrlKey,
        shiftKey: e.shiftKey,
        metaKey: e.metaKey,
      };
      if (hotkeyDisplay) hotkeyDisplay.textContent = formatHotkey(settings.hotkey);
      recordingHotkey = false;
      hotkeyHint?.classList.add('hidden');
      scheduleSaveSettings({ hotkey: settings.hotkey });
    }, true);
  }

  function setupAutoSave() {
    const autoSaveIds = [
      'previewEnabled',
      'previewColor',
      'toolColor',
      'micTipsEnabled',
      'previewEnterToInsert',
      'outCounterEnabled',
      'outTargetInput',
    ];
    for (const id of autoSaveIds) {
      const el = document.getElementById(id);
      if (!el) continue;
      const eventName = id === 'outTargetInput' ? 'change' : 'change';
      el.addEventListener(eventName, () => scheduleSaveSettings());
      if (el.type === 'color') {
        el.addEventListener('input', () => scheduleSaveSettings());
      }
    }
  }

  keyInput?.addEventListener('input', () => {
    keyInput.value = formatLicenseKeyInput(keyInput.value);
  });

  activateBtn?.addEventListener('click', () => {
    activateLicense();
  });
  clearBtn?.addEventListener('click', () => {
    clearLicense().catch((e) => showToast(e.message || 'Fehler'));
  });

  function showBackupStatus(text, isError) {
    const el = document.getElementById('unifiedBackupStatus');
    if (!el) return;
    el.textContent = text || '';
    el.classList.toggle('hidden', !text);
    el.classList.toggle('diag-log-export-warn', !!isError);
  }

  async function downloadUnifiedBackup() {
    try {
      await window.ChillicollectivoUnifiedBackup?.download?.();
      showToast('Backup heruntergeladen');
      showBackupStatus('Backup heruntergeladen.');
    } catch (e) {
      showBackupStatus(e?.message || 'Backup fehlgeschlagen', true);
      showToast('Backup fehlgeschlagen');
    }
  }

  async function importUnifiedBackupFromFile(file) {
    if (!file) return;
    try {
      await window.ChillicollectivoUnifiedBackup?.importFile?.(file);
      showToast('Backup geladen – Extension neu laden empfohlen');
      showBackupStatus('Backup geladen.');
      await loadPanel();
    } catch (e) {
      showBackupStatus(e?.message || 'Backup laden fehlgeschlagen', true);
      showToast(e?.message || 'Backup laden fehlgeschlagen');
    } finally {
      const input = document.getElementById('unifiedBackupFile');
      if (input) input.value = '';
    }
  }

  async function exportDiagnosticLog() {
    const result = await window.ChillicollectivoDiagnosticLog?.exportTextFile?.();
    showToast(result?.ok ? 'Log exportiert' : 'Log-Export fehlgeschlagen');
  }

  async function clearDiagnosticLog() {
    await window.ChillicollectivoDiagnosticLog?.clear?.();
    showToast('Log geleert');
  }

  document.getElementById('downloadUnifiedBackup')?.addEventListener('click', () => {
    downloadUnifiedBackup();
  });
  document.getElementById('uploadUnifiedBackup')?.addEventListener('click', () => {
    document.getElementById('unifiedBackupFile')?.click();
  });
  document.getElementById('unifiedBackupFile')?.addEventListener('change', (e) => {
    importUnifiedBackupFromFile(e.target.files?.[0]);
  });
  document.getElementById('exportDiagnosticLog')?.addEventListener('click', () => {
    exportDiagnosticLog();
  });
  document.getElementById('clearDiagnosticLog')?.addEventListener('click', () => {
    clearDiagnosticLog();
  });

  micUpdateCheckBtn?.addEventListener('click', () => {
    refreshMicUpdateStatus(true).catch(() => {});
  });
  for (const button of [
    micUpdateDownloadLatest,
    micUpdateDownloadPrevious,
    micUpdateDownloadLatestTop,
    micUpdateDownloadPreviousTop,
  ]) {
    button?.addEventListener('click', () => {
      openMicUpdateDownload(button.dataset.downloadUrl || '');
    });
  }

  setupHotkeyCapture();
  setupAutoSave();
  refreshMicUpdateStatus(false).catch(() => {});
  loadPanel().catch((e) => {
    setDisplayedVersion();
    renderMicUpdateUi(null, installedVersion);
    if (micUpdateStatusText) {
      micUpdateStatusText.textContent = 'Einstellungen konnten nicht geladen werden – Version oben ist trotzdem aktiv.';
    }
    setSyncStatus(e.message || 'Laden fehlgeschlagen');
    showToast(e.message || 'Laden fehlgeschlagen');
  });
})();
