document.addEventListener('DOMContentLoaded', () => {
  const patternsButton = document.getElementById('patterns-btn');
  const patternsModal = document.getElementById('patterns-modal');
  const patternsCloseButton = document.getElementById('patterns-close-btn');
  const patternsList = document.getElementById('patterns-list');

  if (!patternsButton || !patternsModal || !patternsList) {
    return;
  }

  const renderPatterns = (patterns) => {
    patternsList.innerHTML = '';
    const entries = Object.entries(patterns || {});
    if (!entries.length) {
      const empty = document.createElement('p');
      empty.className = 'muted-text';
      empty.textContent = 'No patterns found.';
      patternsList.appendChild(empty);
      return;
    }
    entries.forEach(([patternName, data]) => {
      const row = document.createElement('div');
      row.className = 'profiles-row';

      const label = document.createElement('span');
      label.textContent = patternName;

      const details = document.createElement('span');
      const minDelay = data && data.min_delay !== undefined ? data.min_delay : '-';
      const maxDelay = data && data.max_delay !== undefined ? data.max_delay : '-';
      details.textContent = `${minDelay}–${maxDelay} ms`;
      details.style.color = '#aaa';
      details.style.fontSize = '0.85em';

      row.appendChild(label);
      row.appendChild(details);
      patternsList.appendChild(row);
    });
  };

  const loadPatterns = async () => {
    patternsList.innerHTML = '';
    const loading = document.createElement('p');
    loading.className = 'muted-text';
    loading.textContent = 'Loading patterns...';
    patternsList.appendChild(loading);

    try {
      const response = await fetch('/patterns', {
        headers: { Accept: 'application/json' },
      });
      if (!response.ok) {
        throw new Error('Failed to load patterns');
      }
      const patterns = await response.json();
      renderPatterns(patterns);
    } catch (error) {
      console.error('Load patterns failed:', error);
      patternsList.innerHTML = '';
      const errorMessage = document.createElement('p');
      errorMessage.className = 'muted-text';
      errorMessage.textContent = 'Failed to load patterns.';
      patternsList.appendChild(errorMessage);
    }
  };

  const openModal = () => {
    patternsModal.classList.add('active');
    loadPatterns();
  };

  const closeModal = () => {
    patternsModal.classList.remove('active');
  };

  patternsButton.addEventListener('click', openModal);
  if (patternsCloseButton) {
    patternsCloseButton.addEventListener('click', closeModal);
  }

  patternsModal.addEventListener('click', (event) => {
    if (event.target === patternsModal) {
      closeModal();
    }
  });
});
