import { remindIncident } from '../api.js'; 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 renderIncidentDetail(root, { incidentId, incidents = [], fetchIncidentDetail }) { if (!incidentId) { root.innerHTML = '
Demande introuvable.
'; return; } root.innerHTML = `
Suivi détaillé

Détail de votre demande

Retrouvez ici toutes les informations transmises, l’état de prise en charge et les pièces jointes envoyées.

Retour à l’historique
Chargement du détail…
`; const fallbackIncident = incidents.find((item) => Number(item.id || 0) === incidentId) || null; try { const response = await fetchIncidentDetail(incidentId); const incident = response?.incident || fallbackIncident; const photos = response?.photos || []; let currentFollowups = response?.followups || []; const supportEmail = String(response?.support?.email || '').trim(); const canRemind = !['resolu', 'ferme'].includes(String(incident?.status || '')); if (!incident) { root.innerHTML = '
Demande introuvable.
'; return; } root.innerHTML = `
Suivi détaillé

${escapeHtml(incident.subject || 'Incident client')}

${escapeHtml(incident.description || 'Aucun commentaire détaillé transmis.')}

Retour à l’historique
Référence ticket ${escapeHtml(incident.ref_code || ('FTTH-' + incident.ticket_id))} Identifiant FTTH associé à votre demande
Statut actuel ${escapeHtml(formatStatus(incident.status))} ${escapeHtml(incident.updated_at ? 'Mis à jour le ' + formatDateTime(incident.updated_at) : 'En attente de mise à jour')}
Photos envoyées ${Number((response?.photos || []).length || incident.photo_count || 0)} Pièces jointes enregistrées lors de la déclaration

Actions sur la demande

Relancez votre dossier ou contactez le support si vous avez besoin d'un complément de prise en charge.

${supportEmail ? ` Contacter le support ` : ` Créer une nouvelle demande `}

Informations de prise en charge

Les équipes utilisent ces informations pour qualifier et traiter votre demande.

Adresse client${escapeHtml(incident.client_address || 'Adresse à confirmer')}
Nature d’intervention${escapeHtml(incident.nature_intervention || 'Maintenance FTTH B2B')}
Date de création${escapeHtml(formatDateTime(incident.created_at))}
Dernière mise à jour${escapeHtml(formatDateTime(incident.updated_at || incident.created_at))}
${incident.operator_notes ? `
Note opérateur

${escapeHtml(incident.operator_notes)}

` : ''}

Historique des relances

Retrouvez ici les relances que vous avez déjà transmises au support pour cette demande.

${renderFollowups(currentFollowups)}

Photos et commentaires

Chaque pièce jointe correspond à une photo ou un commentaire transmis lors de votre déclaration.

${photos.length ? photos.map((photo, index) => `
${photo.photo_url ? `Photo ${index + 1}` : ''}
Photo ${index + 1} ${escapeHtml(formatDateTime(photo.created_at))}

${escapeHtml(photo.comment || 'Aucun commentaire sur cette photo.')}

`).join('') : '
Aucune photo enregistrée sur cette demande.
'}
`; const remindButton = root.querySelector('#btnRemind'); const feedbackBox = root.querySelector('#detailActionFeedback'); const followupTimeline = root.querySelector('#followupTimeline'); remindButton?.addEventListener('click', async () => { if (!canRemind) { return; } const followupMessage = window.prompt('Précisez si besoin le motif de votre relance.', 'Merci de revenir vers moi sur cette demande.'); if (followupMessage === null) { return; } remindButton.disabled = true; try { const remindResponse = await remindIncident({ incident_id: incidentId, message: followupMessage, }); feedbackBox.hidden = false; feedbackBox.innerHTML = `
${escapeHtml(remindResponse?.message || 'Votre relance a été envoyée au support.')}
`; const followup = remindResponse?.followup; if (followup && followupTimeline) { currentFollowups = [followup, ...currentFollowups]; followupTimeline.innerHTML = renderFollowups(currentFollowups); } } catch (error) { feedbackBox.hidden = false; feedbackBox.innerHTML = `
${escapeHtml(error?.data?.error === 'incident_closed' ? 'Cette demande est déjà clôturée.' : 'Impossible de transmettre la relance pour le moment.')}
`; } finally { remindButton.disabled = false; } }); } catch { if (!fallbackIncident) { root.innerHTML = '
Impossible de charger le détail de cette demande.
'; return; } root.innerHTML = `
Suivi détaillé

${escapeHtml(fallbackIncident.subject || 'Incident client')}

${escapeHtml(fallbackIncident.description || 'Aucun commentaire détaillé transmis.')}

Retour à l’historique
Le détail enrichi est momentanément indisponible, mais votre demande reste visible dans l’historique.
`; } } 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('&', '&') .replaceAll('<', '<') .replaceAll('>', '>') .replaceAll('"', '"') .replaceAll("'", '''); } function renderFollowups(followups) { if (!followups.length) { return '
Aucune relance envoyée pour le moment.
'; } return followups.map((followup) => `
Relance client ${escapeHtml(formatDateTime(followup.created_at))}

${escapeHtml(followup.message || 'Relance demandée depuis l\'application client.')}

`).join(''); }