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 renderDashboard(root, { client, incidents = [], unreadCount = 0 }) {
  const latest = incidents.slice(0, 3);
  root.innerHTML = `
    <section class="screen-stack">
      <div class="public-dashboard-hero">
        <div>
          <span class="public-hero-pill">Bonjour ${escapeHtml((client?.full_name || '').split(' ')[0] || 'client')}</span>
          <h2>Suivi de vos interventions</h2>
          <p>Déclarez un nouvel incident, suivez sa prise en charge et consultez vos notifications de service.</p>
        </div>
        <div class="public-dashboard-actions">
          <a class="btn btn-primary public-cta" href="#/declare"><i class="fas fa-plus"></i> Déclarer un incident</a>
          <a class="btn btn-outline-secondary" href="#/history"><i class="fas fa-clock-rotate-left"></i> Historique</a>
        </div>
      </div>

      <div class="public-kpi-grid">
        <article class="public-kpi-card">
          <span>Abonnement</span>
          <strong>${escapeHtml(client?.subscription_number || '—')}</strong>
          <small>Référence client reconnue côté FTTH B2B</small>
        </article>
        <article class="public-kpi-card accent-warm">
          <span>Demandes actives</span>
          <strong>${incidents.filter((item) => !['resolu', 'ferme'].includes(item.status)).length}</strong>
          <small>Tickets encore en cours de traitement</small>
        </article>
        <article class="public-kpi-card accent-soft">
          <span>Notifications</span>
          <strong>${unreadCount}</strong>
          <small>Nouveaux messages de prise en charge</small>
        </article>
      </div>

      <div class="public-section-card">
        <div class="public-section-head">
          <div>
            <h3>Dernières déclarations</h3>
            <p>Les statuts ci-dessous sont mis à jour depuis le module Maintenance FTTH B2B.</p>
          </div>
          <a class="btn btn-sm btn-outline-secondary" href="#/history">Tout voir</a>
        </div>
        ${latest.length ? latest.map((item) => `
          <article class="public-history-card compact">
            <div class="public-history-main">
              <strong>${escapeHtml(item.subject || 'Incident client')}</strong>
              <span>${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-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 demande soumise pour le moment.</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;');
}
