(() => {
  const container = document.getElementById('toast-container');
  if (!container) return;

  const body = document.body;
  const allowedPositions = new Set([
    'top-left', 'top-center', 'top-right',
    'bottom-left', 'bottom-center', 'bottom-right'
  ]);
  const position = allowedPositions.has(body.dataset.toastPosition)
    ? body.dataset.toastPosition
    : 'top-right';
  const seconds = Math.max(1, Math.min(120, Number.parseInt(body.dataset.toastDuration || '6', 10) || 6));
  container.classList.add(`toast-position-${position}`);

  const params = new URLSearchParams(window.location.search);
  const entries = [
    ['toast_error', 'error'],
    ['toast_warning', 'warning'],
    ['toast_success', 'success']
  ];

  function showToast(message, level) {
    if (!message) return;
    const toast = document.createElement('div');
    toast.className = `toast toast-${level}`;
    const symbol = level === 'success' ? '✓' : level === 'warning' ? '⚠' : '✕';
    toast.innerHTML = `<span class="toast-symbol">${symbol}</span><span class="toast-message"></span><button type="button" class="toast-close" aria-label="Schließen">×</button>`;
    toast.querySelector('.toast-message').textContent = message;
    toast.querySelector('.toast-close').addEventListener('click', () => toast.remove());
    container.appendChild(toast);
    window.setTimeout(() => {
      toast.classList.add('toast-hide');
      window.setTimeout(() => toast.remove(), 350);
    }, seconds * 1000);
  }

  let changed = false;
  entries.forEach(([key, level]) => {
    const values = params.getAll(key);
    values.forEach(value => showToast(value, level));
    if (values.length) {
      params.delete(key);
      changed = true;
    }
  });

  if (changed) {
    const query = params.toString();
    const cleanUrl = `${window.location.pathname}${query ? `?${query}` : ''}${window.location.hash}`;
    window.history.replaceState({}, document.title, cleanUrl);
  }
})();
