(() => {
  const filterForm = document.getElementById('filter-form');
  const dataStatus = document.getElementById('data-status');
  const jsonData = document.getElementById('json-data');
  const resetFilters = document.getElementById('reset-filters');
  const countdown = document.getElementById('reset-countdown');

  function setStatus(text) {
    if (dataStatus) dataStatus.textContent = text;
  }

  function valueOf(form, name) {
    return String(form.get(name) || '').trim();
  }

  function buildQuery() {
    const form = new FormData(filterForm);
    const params = new URLSearchParams();
    ['location', 'abuse_type', 'gender', 'status', 'from', 'to', 'search', 'limit'].forEach((key) => {
      const value = valueOf(form, key);
      if (value) params.set(key, value);
    });
    return params.toString();
  }

  async function renderData(event) {
    if (event) event.preventDefault();
    if (!filterForm || !jsonData) return;

    const query = buildQuery();
    const url = query ? `/demo/registrations?${query}` : '/demo/registrations';
    setStatus('Loading data…');

    try {
      const response = await fetch(url, { headers: { Accept: 'application/json' } });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const rows = await response.json();
      jsonData.textContent = JSON.stringify(rows, null, 2);
      setStatus(`Showing ${rows.length} row${rows.length === 1 ? '' : 's'} from ${url}.`);
    } catch (err) {
      jsonData.textContent = '[]';
      setStatus(`Could not load demo data: ${err.message}`);
    }
  }

  function renderCountdown() {
    if (!countdown) return;
    const resetAt = new Date(countdown.dataset.resetAt);
    if (Number.isNaN(resetAt.getTime())) return;

    function tick() {
      const remainingMs = resetAt.getTime() - Date.now();
      if (remainingMs <= 0) {
        countdown.textContent = 'resetting…';
        window.setTimeout(() => window.location.reload(), 1200);
        return;
      }
      const seconds = Math.floor(remainingMs / 1000);
      const minutes = Math.floor(seconds / 60);
      const rest = seconds % 60;
      countdown.textContent = `${minutes}m ${String(rest).padStart(2, '0')}s`;
      window.setTimeout(tick, 1000);
    }

    tick();
  }

  function setupSingleOpenAccordions() {
    document.querySelectorAll('[data-single-open]').forEach((group) => {
      const panels = Array.from(group.querySelectorAll('details'));
      panels.forEach((panel) => {
        panel.addEventListener('toggle', () => {
          if (!panel.open) return;
          panels.forEach((other) => {
            if (other !== panel) other.open = false;
          });
        });
      });
    });
  }

  if (filterForm) filterForm.addEventListener('submit', renderData);
  if (resetFilters) resetFilters.addEventListener('click', () => {
    filterForm.reset();
    renderData();
  });

  setupSingleOpenAccordions();
  renderCountdown();
  renderData();
})();
