const healthBtn = document.getElementById('healthBtn');
const healthOutput = document.getElementById('healthOutput');
const form = document.getElementById('scan-form');
const scanOutput = document.getElementById('scanOutput');
const resultInfo = document.getElementById('resultInfo');

// Clear directory inputs on page load and hide output sections
window.addEventListener('DOMContentLoaded', () => {
  document.getElementById('imagesDir').value = '';
  document.getElementById('noPeopleDir').value = '';
  healthOutput.style.display = 'none';
  scanOutput.style.display = 'none';
  resultInfo.style.display = 'none';
});

// Health check endpoint
healthBtn.addEventListener('click', async () => {
  healthOutput.style.display = 'block';
  healthOutput.innerHTML = '<div style="color: #999;">Checking...</div>';
  try {
    const res = await fetch('/health');
    const json = await res.json();
    // Show only the first data row, no table header
    healthOutput.innerHTML = createTable(json, { showHeader: false, rowLimit: 1 });
  } catch (err) {
    healthOutput.innerHTML = `<div style="color: #ff6b6b;">Error: ${err.message}</div>`;
  }
});

// Scan directory endpoint
form.addEventListener('submit', async (e) => {
  e.preventDefault();
  const payload = {
    images_dir: document.getElementById('imagesDir').value.trim(),
    no_people_dir: document.getElementById('noPeopleDir').value.trim() || null,
    conf: parseFloat(document.getElementById('conf').value),
    batch_size: parseInt(document.getElementById('batchSize').value, 10),
  };

  scanOutput.style.display = 'block';
  resultInfo.style.display = 'none';
  scanOutput.innerHTML = '<div style="color: #999;">Running...</div>';
  try {
    const res = await fetch('/scan-dir', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
    const json = await res.json();
    // Rename headers and narrow first column
    scanOutput.innerHTML = createTable(json, {
      headers: { keyLabel: '#', valueLabel: 'Results' },
      showHeader: true,
      narrowFirstCol: true,
    });
    resultInfo.style.display = 'block';
  } catch (err) {
    scanOutput.innerHTML = `<div style="color: #ff6b6b;">Error: ${err.message}</div>`;
  }
});

// Helper function to create HTML table from JSON
function createTable(data, options = {}) {
  const {
    showHeader = true,
    headers = { keyLabel: 'Property', valueLabel: 'Value' },
    rowLimit = null,
    narrowFirstCol = false,
  } = options;

  let html = `<table class="result-table${narrowFirstCol ? ' narrow-first' : ''}">`;
  if (showHeader) {
    html += `<thead><tr><th>${headers.keyLabel}</th><th>${headers.valueLabel}</th></tr></thead>`;
  }
  html += '<tbody>';

  const rows = [];
  function collectRows(obj, prefix = '') {
    for (const [key, value] of Object.entries(obj)) {
      const displayKey = prefix ? `${prefix}.${key}` : key;
      if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
        collectRows(value, displayKey);
      } else {
        const displayValue =
          value === null ? 'null' :
          Array.isArray(value) ? JSON.stringify(value) :
          String(value);
        rows.push({ key: displayKey, value: displayValue });
      }
    }
  }

  collectRows(data);

  const limit = typeof rowLimit === 'number' ? Math.min(rowLimit, rows.length) : rows.length;
  for (let i = 0; i < limit; i++) {
    const r = rows[i];
    html += `<tr><td class="key-cell">${r.key}</td><td class="value-cell">${r.value}</td></tr>`;
  }

  html += '</tbody></table>';
  return html;
}
