function formatStatus(status) {
  const map = {
    soumis: 'Soumise',
    prise_en_charge: 'Prise en charge',
    assigne_technicien: 'Technicien assigné',
    en_cours: 'En cours',
    resolu: 'Résolue',
    ferme: 'Fermée',
  };
  return map[status] || status || '—';
}

export async function renderHistory(root, { incidents = [] }) {
  root.innerHTML = `
    <section class="screen-stack">
      <div class="public-section-card public-section-card-hero">
        <div class="public-section-head stacked">
          <div>
            <span class="public-hero-pill">Traçabilité client</span>
            <h2>Historique de vos déclarations</h2>
            <p>Retrouvez ici vos incidents, les tickets FTTH liés et le niveau de prise en charge opérateur.</p>
          </div>
        </div>
      </div>
      <div class="screen-stack">
        ${incidents.length ? incidents.map((item) => `
          <article class="public-history-card">
            <div class="public-history-main">
              <div>
                <strong>${escapeHtml(item.subject || 'Incident client')}</strong>
                <p>${escapeHtml(item.description || '')}</p>
              </div>
              <span class="public-status-chip status-${escapeHtml(item.status || 'soumis')}">${escapeHtml(formatStatus(item.status))}</span>
            </div>
            <div class="public-history-meta">
              <span><i class="fas fa-hashtag"></i> ${escapeHtml(item.ref_code || ('FTTH-' + item.ticket_id))}</span>
              <span><i class="fas fa-location-dot"></i> ${escapeHtml(item.client_address || 'Adresse à confirmer')}</span>
              <span><i class="fas fa-camera"></i> ${Number(item.photo_count || 0)} photo(s)</span>
              <span><i class="fas fa-calendar-day"></i> ${escapeHtml(formatDateTime(item.created_at))}</span>
            </div>
          </article>
        `).join('') : '<div class="public-empty-state">Aucune déclaration n\'a encore été enregistrée.</div>'}
      </div>
    </section>
  `;
}

function formatDateTime(value) {
  if (!value) {
    return '—';
  }
  const date = new Date(String(value).replace(' ', 'T'));
  if (Number.isNaN(date.getTime())) {
    return value;
  }
  return date.toLocaleString('fr-FR', { dateStyle: 'medium', timeStyle: 'short' });
}

function escapeHtml(value) {
  return String(value ?? '')
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#039;');
}
