(function popupController() {
  'use strict';

  const ext = globalThis.OrbitOneVaultExtension;
  const state = {
    activeTab: null,
    activeUrl: null,
    entries: [],
    destinations: null,
    filterConnectionId: '',
  };

  const setupState = document.getElementById('setup-state');
  const connectedApp = document.getElementById('connected-app');
  const siteHost = document.getElementById('site-host');
  const matchCount = document.getElementById('match-count');
  const resultsList = document.getElementById('results-list');
  const statusLine = document.getElementById('status-line');
  const tenantName = document.getElementById('tenant-name');
  const searchForm = document.getElementById('search-form');
  const searchInput = document.getElementById('search-input');
  const connectionFilter = document.getElementById('connection-filter');
  const saveForm = document.getElementById('save-form');
  const saveConnection = document.getElementById('save-connection');
  const saveWorkspace = document.getElementById('save-workspace');
  const saveVault = document.getElementById('save-vault');
  const saveSecret = document.getElementById('save-secret');
  const savePasswordHealth = document.getElementById('save-password-health');
  const savePasswordHealthBar = document.getElementById('save-password-health-bar');
  const savePasswordHealthLabel = document.getElementById('save-password-health-label');

  function t(key, substitutions, fallback) {
    return ext.t(key, substitutions, fallback);
  }

  function renderIcons() {
    globalThis.lucide?.createIcons({
      attrs: {
        'aria-hidden': 'true',
        'stroke-width': 1.9,
      },
    });
  }

  function escapeHtml(value) {
    return String(value || '')
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }

  function setStatus(message, type = '') {
    statusLine.textContent = String(message || '');
    statusLine.className = `status-line${type ? ` ${type}` : ''}`;
  }

  function pageTitle() {
    return String(state.activeTab?.title || state.activeUrl?.hostname || '').trim();
  }

  function safePageUrl() {
    if (!state.activeUrl) {
      return '';
    }
    const url = new URL(state.activeUrl.toString());
    url.hash = '';
    url.search = '';
    return url.toString();
  }

  async function getDetail(entry) {
    const response = await ext.extension.runtime.sendMessage({
      type: 'orbitone:get-entry-detail',
      entry,
    });
    if (!response?.ok) {
      throw new Error(response?.error?.message || t('errorEntryLoad', undefined, 'Vault-Eintrag konnte nicht geladen werden.'));
    }
    return response.entry;
  }

  async function getHistory(entry) {
    const response = await ext.extension.runtime.sendMessage({
      type: 'orbitone:get-password-history',
      entry,
    });
    if (!response?.ok) {
      throw new Error(response?.error?.message || t('errorHistoryLoad', undefined, 'Passwort-Historie konnte nicht geladen werden.'));
    }
    return response;
  }

  async function fillEntry(entry) {
    if (!state.activeTab?.id) {
      throw new Error(t('errorNoWebsiteTab', undefined, 'Kein Website-Tab aktiv.'));
    }
    const detail = await getDetail(entry);
    const response = await ext.extension.tabs.sendMessage(state.activeTab.id, {
      type: 'orbitone-fill-credentials',
      payload: {
        username: detail?.username || entry.username || '',
        secret: detail?.secret || '',
      },
    });
    if (!response?.ok) {
      throw new Error(response?.message || t('errorFill', undefined, 'Anmeldefelder konnten nicht ausgefüllt werden.'));
    }
    setStatus(t('filled', undefined, 'Anmeldefelder ausgefüllt.'), 'success');
  }

  async function copyValue(value, successMessage) {
    if (!value) {
      throw new Error(t('errorNoValue', undefined, 'Für diesen Eintrag ist kein Wert hinterlegt.'));
    }
    await navigator.clipboard.writeText(String(value));
    setStatus(successMessage, 'success');
  }

  function renderPasswordHealth(secret) {
    const health = ext.evaluatePassword(secret);
    savePasswordHealth.hidden = !secret;
    savePasswordHealthBar.style.width = `${health.percent}%`;
    savePasswordHealthBar.dataset.score = String(health.score);
    savePasswordHealthLabel.textContent = secret
      ? `${t('passwordStrength', undefined, 'Sicherheit')}: ${health.label}`
      : '';
  }

  function historyDate(value) {
    const date = new Date(value || '');
    return Number.isNaN(date.getTime())
      ? t('unknownDate', undefined, 'Unbekannt')
      : date.toLocaleString();
  }

  async function saveRotatedPassword(entry, detail, secret) {
    const response = await ext.extension.runtime.sendMessage({
      type: 'orbitone:save-credential',
      credential: {
        entryId: Number(entry.id || 0),
        connectionId: String(entry.connectionId || ''),
        scope: entry.scope === 'personal' || entry.personal === true ? 'personal' : 'workspace',
        workspaceId: Number(entry.workspaceId || entry.workspace_id || 0),
        vaultId: Number(entry.vaultId || entry.vault_id || 0),
        title: detail.title || entry.title,
        username: detail.username || entry.username || '',
        secret,
        url: detail.url || entry.url || '',
        notes: detail.notes || '',
      },
    });
    if (!response?.ok) {
      throw new Error(response?.error?.message || t('errorPasswordSave', undefined, 'Das neue Passwort konnte nicht gespeichert werden.'));
    }
    setStatus(t('passwordChanged', undefined, 'Neues Passwort gespeichert und bisheriges Passwort archiviert.'), 'success');
    await loadMatches(true);
  }

  async function renderSecurity(entry, card) {
    let security = card.querySelector('.credential-security');
    if (!security) {
      security = document.createElement('section');
      security.className = 'credential-security';
      card.appendChild(security);
    }
    security.innerHTML = `<div class="security-loading">${escapeHtml(t('loadingSecurity', undefined, 'Sicherheitsdaten werden geladen...'))}</div>`;
    try {
      const [detail, historyResponse] = await Promise.all([getDetail(entry), getHistory(entry)]);
      const health = ext.evaluatePassword(detail?.secret || '');
      const age = ext.passwordAge(
        detail?.passwordChangedAt || historyResponse?.entry?.passwordChangedAt,
        detail?.createdAt || entry.createdAt,
      );
      const history = Array.isArray(historyResponse?.history) ? historyResponse.history : [];
      security.innerHTML = `
        <div class="security-summary">
          <div>
            <small>${escapeHtml(t('passwordStrength', undefined, 'Sicherheit'))}</small>
            <strong>${escapeHtml(health.label)}</strong>
            <span class="password-health-track"><span data-score="${health.score}" style="width:${health.percent}%"></span></span>
          </div>
          <div>
            <small>${escapeHtml(t('passwordAge', undefined, 'Passwortalter'))}</small>
            <strong class="age-${escapeHtml(age.level)}">${escapeHtml(age.label)}</strong>
          </div>
        </div>
        ${health.hints.length ? `<p class="security-hint">${escapeHtml(health.hints.join(' '))}</p>` : ''}
        <div class="security-toolbar">
          <button class="button small-button" type="button" data-generate-rotation>
            <i data-lucide="sparkles"></i><span>${escapeHtml(t('generateNewPassword', undefined, 'Neues Passwort'))}</span>
          </button>
          <button class="button small-button" type="button" data-toggle-history ${history.length ? '' : 'disabled'}>
            <i data-lucide="history"></i><span>${escapeHtml(t('passwordHistory', undefined, 'Historie'))} (${history.length})</span>
          </button>
        </div>
        <div class="rotation-box" data-rotation-box hidden>
          <input type="text" readonly data-rotation-secret>
          <button class="icon-button compact" type="button" data-copy-rotation title="${escapeHtml(t('copyPassword', undefined, 'Passwort kopieren'))}" aria-label="${escapeHtml(t('copyPassword', undefined, 'Passwort kopieren'))}">
            <i data-lucide="copy"></i>
          </button>
          <button class="button button-primary small-button" type="button" data-save-rotation>
            <i data-lucide="save"></i><span>${escapeHtml(t('usePassword', undefined, 'Übernehmen'))}</span>
          </button>
        </div>
        <div class="history-list" data-history-list hidden>
          ${history.map((item, index) => `
            <div class="history-row">
              <div>
                <code data-history-secret="${index}">••••••••••••</code>
                <small>${escapeHtml(historyDate(item.archivedAt || item.passwordChangedAt))}</small>
              </div>
              <button class="icon-button compact" type="button" data-reveal-history="${index}" title="${escapeHtml(t('showPassword', undefined, 'Passwort anzeigen'))}" aria-label="${escapeHtml(t('showPassword', undefined, 'Passwort anzeigen'))}">
                <i data-lucide="eye"></i>
              </button>
              <button class="icon-button compact" type="button" data-copy-history="${index}" title="${escapeHtml(t('copyPassword', undefined, 'Passwort kopieren'))}" aria-label="${escapeHtml(t('copyPassword', undefined, 'Passwort kopieren'))}">
                <i data-lucide="copy"></i>
              </button>
            </div>
          `).join('')}
        </div>
      `;
      security.querySelector('[data-generate-rotation]')?.addEventListener('click', () => {
        const box = security.querySelector('[data-rotation-box]');
        const input = security.querySelector('[data-rotation-secret]');
        input.value = ext.generatePassword();
        box.hidden = false;
        input.select();
      });
      security.querySelector('[data-copy-rotation]')?.addEventListener('click', () => {
        copyValue(
          security.querySelector('[data-rotation-secret]')?.value,
          t('passwordCopied', undefined, 'Passwort kopiert.'),
        ).catch((error) => setStatus(error.message, 'error'));
      });
      security.querySelector('[data-save-rotation]')?.addEventListener('click', async (event) => {
        const button = event.currentTarget;
        const secret = security.querySelector('[data-rotation-secret]')?.value || '';
        button.disabled = true;
        try {
          await saveRotatedPassword(entry, detail, secret);
        } catch (error) {
          setStatus(error.message, 'error');
          button.disabled = false;
        }
      });
      security.querySelector('[data-toggle-history]')?.addEventListener('click', () => {
        const list = security.querySelector('[data-history-list]');
        list.hidden = !list.hidden;
      });
      history.forEach((item, index) => {
        security.querySelector(`[data-reveal-history="${index}"]`)?.addEventListener('click', (event) => {
          const target = security.querySelector(`[data-history-secret="${index}"]`);
          const revealed = target.dataset.revealed === '1';
          target.textContent = revealed ? '••••••••••••' : String(item.secret || '');
          target.dataset.revealed = revealed ? '0' : '1';
          event.currentTarget.innerHTML = revealed
            ? '<i data-lucide="eye"></i>'
            : '<i data-lucide="eye-off"></i>';
          renderIcons();
        });
        security.querySelector(`[data-copy-history="${index}"]`)?.addEventListener('click', () => {
          copyValue(item.secret, t('passwordCopied', undefined, 'Passwort kopiert.'))
            .catch((error) => setStatus(error.message, 'error'));
        });
      });
      renderIcons();
    } catch (error) {
      security.innerHTML = `<div class="security-error">${escapeHtml(error?.message || t('errorSecurityLoad', undefined, 'Sicherheitsdaten konnten nicht geladen werden.'))}</div>`;
    }
  }

  function renderEntries(entries, emptyMessage = t('noMatchingCredentials', undefined, 'Keine passenden Zugänge für diese Website.')) {
    state.entries = entries;
    matchCount.hidden = entries.length === 0;
    matchCount.textContent = entries.length ? String(entries.length) : '';

    if (!entries.length) {
      resultsList.innerHTML = `<div class="empty-state">${escapeHtml(emptyMessage)}</div>`;
      return;
    }

    resultsList.innerHTML = entries.map((entry, index) => `
      <article class="credential-card ${entry.exactDomain ? 'exact' : ''}">
        <div class="credential-copy">
          <h2>${escapeHtml(entry.title || t('credential', undefined, 'Zugang'))}</h2>
          <p>${escapeHtml(entry.username || t('noUsername', undefined, 'Kein Benutzername'))}</p>
          <small>${escapeHtml([entry.tenantName || entry.connectionName, entry.workspaceName, entry.vaultName].filter(Boolean).join(' / '))}</small>
        </div>
        <div class="credential-actions">
          <button class="icon-button primary-action" type="button" data-action="fill" data-index="${index}" title="${escapeHtml(t('fill', undefined, 'Ausfüllen'))}" aria-label="${escapeHtml(t('fill', undefined, 'Ausfüllen'))}">
            <i data-lucide="wand-sparkles"></i>
          </button>
          <button class="icon-button" type="button" data-action="open-url" data-index="${index}" title="${escapeHtml(t('openWebsite', undefined, 'Website öffnen'))}" aria-label="${escapeHtml(t('openWebsite', undefined, 'Website öffnen'))}" ${entry.url ? '' : 'disabled'}>
            <i data-lucide="globe"></i>
          </button>
          <button class="icon-button" type="button" data-action="copy-user" data-index="${index}" title="${escapeHtml(t('copyUsername', undefined, 'Benutzername kopieren'))}" aria-label="${escapeHtml(t('copyUsername', undefined, 'Benutzername kopieren'))}">
            <i data-lucide="user-round"></i>
          </button>
          <button class="icon-button" type="button" data-action="copy-secret" data-index="${index}" title="${escapeHtml(t('copyPassword', undefined, 'Passwort kopieren'))}" aria-label="${escapeHtml(t('copyPassword', undefined, 'Passwort kopieren'))}">
            <i data-lucide="key-round"></i>
          </button>
          <button class="icon-button" type="button" data-action="security" data-index="${index}" title="${escapeHtml(t('securityAndHistory', undefined, 'Sicherheit und Historie'))}" aria-label="${escapeHtml(t('securityAndHistory', undefined, 'Sicherheit und Historie'))}">
            <i data-lucide="shield-check"></i>
          </button>
          <button class="icon-button" type="button" data-action="open" data-index="${index}" title="${escapeHtml(t('openInOrbitOne', undefined, 'In OrbitOne öffnen'))}" aria-label="${escapeHtml(t('openInOrbitOne', undefined, 'In OrbitOne öffnen'))}">
            <i data-lucide="external-link"></i>
          </button>
        </div>
      </article>
    `).join('');

    resultsList.querySelectorAll('[data-action]').forEach((button) => {
      button.addEventListener('click', async () => {
        const entry = entries[Number(button.dataset.index || 0)];
        try {
          if (button.dataset.action === 'fill') {
            await fillEntry(entry);
          } else if (button.dataset.action === 'copy-user') {
            await copyValue(entry.username, t('usernameCopied', undefined, 'Benutzername kopiert.'));
          } else if (button.dataset.action === 'copy-secret') {
            const detail = await getDetail(entry);
            await copyValue(detail?.secret, t('passwordCopied', undefined, 'Passwort kopiert.'));
          } else if (button.dataset.action === 'open-url') {
            const response = await ext.extension.runtime.sendMessage({ type: 'orbitone:open-url', entry });
            if (!response?.ok) throw new Error(response?.error?.message || t('errorInvalidWebsite', undefined, 'Website konnte nicht geöffnet werden.'));
          } else if (button.dataset.action === 'security') {
            await renderSecurity(entry, button.closest('.credential-card'));
          } else if (button.dataset.action === 'open') {
            await ext.extension.runtime.sendMessage({ type: 'orbitone:open-entry', entry });
          }
        } catch (error) {
          setStatus(error?.message || t('errorAction', undefined, 'Aktion fehlgeschlagen.'), 'error');
        }
      });
    });
    renderIcons();
  }

  function selectedDestination() {
    const connectionId = String(saveConnection.value || '');
    const connection = state.destinations?.connections?.find((row) => row.connectionId === connectionId);
    const workspaceId = Number(saveWorkspace.value || 0);
    const workspace = connection?.workspaces?.find((row) => Number(row.id) === workspaceId);
    const vaultId = Number(saveVault.value || 0);
    const vault = workspace?.vaults?.find((row) => Number(row.id) === vaultId);
    return { connection, workspace, vault };
  }

  function renderVaultOptions(preferredVaultId = 0) {
    const connection = state.destinations?.connections?.find((row) => (
      row.connectionId === String(saveConnection.value || '')
    ));
    const workspaceId = Number(saveWorkspace.value || 0);
    const workspace = connection?.workspaces?.find((row) => Number(row.id) === workspaceId);
    const vaults = Array.isArray(workspace?.vaults) ? workspace.vaults : [];
    const selected = vaults.find((row) => Number(row.id) === Number(preferredVaultId))
      || vaults.find((row) => row.isDefault)
      || vaults[0];
    saveVault.innerHTML = vaults.map((vault) => `
      <option value="${Number(vault.id)}" ${vault.id === selected?.id ? 'selected' : ''}>${escapeHtml(vault.name)}</option>
    `).join('');
  }

  function renderWorkspaceOptions(preferredWorkspaceId = 0, preferredVaultId = 0) {
    const connection = state.destinations?.connections?.find((row) => (
      row.connectionId === String(saveConnection.value || '')
    ));
    const workspaces = Array.isArray(connection?.workspaces) ? connection.workspaces : [];
    const selected = workspaces.find((workspace) => (
      Number(workspace.id) === Number(preferredWorkspaceId)
      && workspace.scope === connection?.defaultScope
    )) || workspaces[0];
    saveWorkspace.innerHTML = workspaces.map((workspace) => `
      <option value="${Number(workspace.id)}" ${workspace === selected ? 'selected' : ''}>${escapeHtml(workspace.name)}</option>
    `).join('');
    renderVaultOptions(preferredVaultId);
  }

  function renderDestinations(data) {
    state.destinations = data;
    const connections = Array.isArray(data?.connections) ? data.connections : [];
    const activeConnectionId = String(data?.activeConnectionId || connections[0]?.connectionId || '');
    state.filterConnectionId = state.filterConnectionId || '';
    connectionFilter.innerHTML = [
      `<option value="">${escapeHtml(t('allTenants', undefined, 'Alle Mandanten'))}</option>`,
      ...connections.map((connection) => `
        <option value="${escapeHtml(connection.connectionId)}">${escapeHtml(connection.tenant?.name || connection.connectionName)}</option>
      `),
    ].join('');
    connectionFilter.value = connections.some((row) => row.connectionId === state.filterConnectionId)
      ? state.filterConnectionId
      : '';

    saveConnection.innerHTML = connections.map((connection) => `
      <option value="${escapeHtml(connection.connectionId)}" ${connection.connectionId === activeConnectionId ? 'selected' : ''}>${escapeHtml(connection.tenant?.name || connection.connectionName)}</option>
    `).join('');
    const active = connections.find((connection) => connection.connectionId === saveConnection.value)
      || connections[0];
    if (active) {
      saveConnection.value = active.connectionId;
      renderWorkspaceOptions(active.defaultWorkspaceId || 0, active.defaultVaultId || 0);
    }
    tenantName.textContent = connections.length > 1
      ? t('tenantCount', [String(connections.length)], `${connections.length} Mandanten`)
      : String(active?.tenant?.name || active?.connectionName || '');
  }

  function switchTab(tabName) {
    document.querySelectorAll('[data-tab]').forEach((button) => {
      const active = button.dataset.tab === tabName;
      button.classList.toggle('active', active);
      button.setAttribute('aria-selected', String(active));
    });
    document.querySelectorAll('.tab-panel').forEach((panel) => {
      const active = panel.id === `${tabName}-panel`;
      panel.classList.toggle('active', active);
      panel.hidden = !active;
    });
  }

  async function loadMatches(force = false) {
    if (!state.activeUrl) {
      renderEntries([], t('openWebsiteToMatch', undefined, 'Öffne eine Website, um passende Zugänge zu sehen.'));
      return;
    }
    setStatus(t('checkingVault', undefined, 'Vault wird geprüft...'));
    const response = await ext.extension.runtime.sendMessage({
      type: 'orbitone:get-matches',
      url: state.activeUrl.toString(),
      force,
      connectionId: state.filterConnectionId,
    });
    if (!response?.ok) {
      throw new Error(response?.error?.message || t('errorCredentialsLoad', undefined, 'Zugänge konnten nicht geladen werden.'));
    }
    renderEntries(response.entries || []);
    setStatus(response.entries?.length
      ? t('matchingCredentialsLoaded', undefined, 'Passende Zugänge geladen.')
      : t('noDomainMatch', undefined, 'Keine Domain-Treffer.'));
  }

  async function boot() {
    ext.translateDocument();
    renderIcons();
    const tabs = await ext.extension.tabs.query({ active: true, currentWindow: true });
    state.activeTab = tabs[0] || null;
    state.activeUrl = ext.parseWebUrl(state.activeTab?.url || '');
    siteHost.textContent = state.activeUrl?.hostname || t('noWebsiteTab', undefined, 'Kein Website-Tab');

    const stateResponse = await ext.extension.runtime.sendMessage({ type: 'orbitone:get-state' });
    if (!stateResponse?.configured) {
      setupState.hidden = false;
      connectedApp.hidden = true;
      setStatus('');
      return;
    }

    setupState.hidden = true;
    connectedApp.hidden = false;
    const [destinationResponse] = await Promise.all([
      ext.extension.runtime.sendMessage({ type: 'orbitone:get-destinations' }),
      loadMatches(),
    ]);
    if (destinationResponse?.ok) {
      renderDestinations(destinationResponse);
    } else {
      setStatus(destinationResponse?.error?.message || t('errorDestinationsLoad', undefined, 'Speicherziele konnten nicht geladen werden.'), 'error');
    }

    document.getElementById('save-title').value = pageTitle();
    document.getElementById('save-url').value = safePageUrl();
  }

  document.querySelectorAll('[data-tab]').forEach((button) => {
    button.addEventListener('click', () => switchTab(button.dataset.tab));
  });

  document.getElementById('open-options-button')?.addEventListener('click', () => {
    ext.extension.runtime.openOptionsPage().catch(() => null);
  });
  document.getElementById('setup-button')?.addEventListener('click', () => {
    ext.extension.runtime.openOptionsPage().catch(() => null);
  });
  document.getElementById('refresh-button')?.addEventListener('click', () => {
    loadMatches(true).catch((error) => setStatus(error.message, 'error'));
  });

  connectionFilter?.addEventListener('change', async () => {
    state.filterConnectionId = String(connectionFilter.value || '');
    if (state.filterConnectionId) {
      await ext.extension.runtime.sendMessage({
        type: 'orbitone:set-active-connection',
        connectionId: state.filterConnectionId,
      }).catch(() => null);
      saveConnection.value = state.filterConnectionId;
      const connection = state.destinations?.connections?.find((row) => row.connectionId === state.filterConnectionId);
      renderWorkspaceOptions(connection?.defaultWorkspaceId || 0, connection?.defaultVaultId || 0);
    }
    loadMatches(true).catch((error) => setStatus(error.message, 'error'));
  });

  searchForm?.addEventListener('submit', async (event) => {
    event.preventDefault();
    const query = String(searchInput.value || '').trim();
    if (!query) {
      await loadMatches().catch((error) => setStatus(error.message, 'error'));
      return;
    }
    setStatus(t('searchRunning', undefined, 'Suche läuft...'));
    const response = await ext.extension.runtime.sendMessage({
      type: 'orbitone:search',
      query,
      connectionId: state.filterConnectionId,
    });
    if (!response?.ok) {
      setStatus(response?.error?.message || t('errorSearch', undefined, 'Suche fehlgeschlagen.'), 'error');
      return;
    }
    renderEntries(response.entries || [], t('noVaultEntries', undefined, 'Keine Vault-Einträge gefunden.'));
    setStatus(t('resultCount', [String(response.entries?.length || 0)], `${response.entries?.length || 0} Treffer.`));
  });

  saveConnection?.addEventListener('change', async () => {
    const connection = state.destinations?.connections?.find((row) => row.connectionId === saveConnection.value);
    renderWorkspaceOptions(connection?.defaultWorkspaceId || 0, connection?.defaultVaultId || 0);
    if (connection) {
      await ext.extension.runtime.sendMessage({
        type: 'orbitone:set-active-connection',
        connectionId: connection.connectionId,
      }).catch(() => null);
    }
  });
  saveWorkspace?.addEventListener('change', () => renderVaultOptions());
  document.getElementById('toggle-secret-button')?.addEventListener('click', () => {
    saveSecret.type = saveSecret.type === 'password' ? 'text' : 'password';
    document.getElementById('toggle-secret-button').innerHTML = saveSecret.type === 'password'
      ? '<i data-lucide="eye"></i>'
      : '<i data-lucide="eye-off"></i>';
    renderIcons();
  });
  document.getElementById('generate-secret-button')?.addEventListener('click', () => {
    saveSecret.value = ext.generatePassword();
    saveSecret.type = 'text';
    saveSecret.focus();
    renderPasswordHealth(saveSecret.value);
  });
  saveSecret?.addEventListener('input', () => renderPasswordHealth(saveSecret.value));

  saveForm?.addEventListener('submit', async (event) => {
    event.preventDefault();
    const destination = selectedDestination();
    if (!destination.workspace || !destination.vault) {
      setStatus(t('errorWritableDestination', undefined, 'Bitte einen beschreibbaren Speicherort auswählen.'), 'error');
      return;
    }
    const data = new FormData(saveForm);
    setStatus(t('savingCredentialEncrypted', undefined, 'Zugang wird verschlüsselt gespeichert...'));
    const response = await ext.extension.runtime.sendMessage({
      type: 'orbitone:save-credential',
      credential: {
        connectionId: destination.connection.connectionId,
        scope: destination.workspace.scope,
        workspaceId: destination.workspace.id,
        vaultId: destination.vault.id,
        title: data.get('title'),
        username: data.get('username'),
        secret: data.get('secret'),
        url: data.get('url'),
        notes: data.get('notes'),
      },
    });
    if (!response?.ok) {
      setStatus(response?.error?.message || t('errorCredentialSave', undefined, 'Zugang konnte nicht gespeichert werden.'), 'error');
      return;
    }
    saveSecret.value = '';
    renderPasswordHealth('');
    document.getElementById('save-notes').value = '';
    setStatus(t('credentialSaved', undefined, 'Zugang im OrbitOne Vault gespeichert.'), 'success');
    switchTab('credentials');
    await loadMatches(true);
  });

  boot().catch((error) => {
    setupState.hidden = false;
    connectedApp.hidden = true;
    setStatus(error?.message || t('errorVaultLoad', undefined, 'OrbitOne Vault konnte nicht geladen werden.'), 'error');
  });
}());
