<% layout('layouts/main') %>
<% const adminBase = typeof adminBaseUrl !== 'undefined' ? adminBaseUrl : '/admin'; %>
<% const selectedTeamIds = String(intervention.team_ids || intervention.assigned_user_id || '').split(',').map(Number); %>
<% const quoteStats = clientPipeline[0] || {}; %>
<% const invoiceStats = clientPipeline[1] || {}; %>
<% const interventionStats = clientPipeline[2] || {}; %>
<% const parseChecklist = (value) => { try { const parsed = JSON.parse(value || '[]'); return Array.isArray(parsed) ? parsed : []; } catch (error) { return []; } }; %>
<div class="app-shell record-360-page">
  <%- partial('partials/admin-nav') %>
  <section class="content">
    <div class="page-head compact-page-head">
      <div>
        <p class="eyebrow">Fiche intervention 360</p>
        <h1><%= intervention.service_type || 'Intervention' %></h1>
        <p class="muted"><%= intervention.first_name %> <%= intervention.last_name %> · <%= ui.date(intervention.starts_at, true) %></p>
      </div>
      <div class="actions">
        <a class="button secondary" href="<%= adminBase %>/interventions">Planning</a>
        <a class="button secondary" href="<%= adminBase %>/clients/<%= intervention.user_id %>">Fiche client</a>
        <a class="button secondary" href="<%= adminBase %>/heures-facturables">Heures</a>
      </div>
    </div>

    <section class="record-kpi-row">
      <article><span>Statut</span><strong><%= ui.label(intervention.status) %></strong></article>
      <article><span>Équipe</span><strong><%= intervention.team_names || 'Non assignée' %></strong></article>
      <article><span>Prévu</span><strong><%= ui.money(intervention.expected_price || 0) %></strong></article>
      <article><span>Réalisé</span><strong><%= ui.duration(intervention.actual_duration_minutes) %></strong></article>
    </section>

    <div class="record-layout">
      <section class="panel compact-panel">
        <div class="inline-heading"><h2>Dossier intervention</h2><span class="badge"><%= ui.label(intervention.status) %></span></div>
        <div class="detail-grid compact">
          <div class="detail-item"><span>Client</span><strong><%= intervention.first_name %> <%= intervention.last_name %></strong></div>
          <div class="detail-item"><span>Email</span><strong><%= intervention.email || 'Non renseigné' %></strong></div>
          <div class="detail-item"><span>Téléphone</span><strong><%= intervention.phone || 'Non renseigné' %></strong></div>
          <div class="detail-item"><span>Adresse intervention</span><strong><%= intervention.address || intervention.client_address || 'Non renseignée' %></strong></div>
          <div class="detail-item"><span>Début</span><strong><%= ui.date(intervention.starts_at, true) %></strong></div>
          <div class="detail-item"><span>Fin estimée</span><strong><%= ui.date(intervention.ends_at, true) %></strong></div>
        </div>
        <% if (intervention.admin_comment || intervention.client_comment) { %>
          <div class="record-notes">
            <% if (intervention.admin_comment) { %><p><strong>Note interne</strong><span><%= intervention.admin_comment %></span></p><% } %>
            <% if (intervention.client_comment) { %><p><strong>Message client</strong><span><%= intervention.client_comment %></span></p><% } %>
          </div>
        <% } %>
      </section>

      <section class="panel compact-panel">
        <div class="inline-heading"><h2>Client associé</h2><a href="<%= adminBase %>/clients/<%= intervention.user_id %>">Ouvrir 360</a></div>
        <div class="detail-grid compact">
          <div class="detail-item"><span>Devis</span><strong><%= quoteStats.total || 0 %></strong></div>
          <div class="detail-item"><span>Montant devis</span><strong><%= ui.money(quoteStats.amount || 0) %></strong></div>
          <div class="detail-item"><span>Factures ouvertes</span><strong><%= ui.money(invoiceStats.open_amount || 0) %></strong></div>
          <div class="detail-item"><span>Interventions client</span><strong><%= interventionStats.total || 0 %></strong></div>
        </div>
      </section>
    </div>

    <details class="ops-drawer">
      <summary><span>Modifier intervention</span><small>Équipe, dates, statut, prix prévu et notes</small></summary>
      <form method="post" action="<%= adminBase %>/interventions/<%= intervention.id %>" class="ops-form compact">
        <input type="hidden" name="_csrf" value="<%= csrfToken %>">
        <div class="form-grid two">
          <label>Équipe assignée<select name="assigned_user_ids" multiple size="5"><% staff.forEach(s=>{ %><option value="<%= s.id %>" <%= selectedTeamIds.includes(Number(s.id))?'selected':'' %>><%= s.first_name %> <%= s.last_name %></option><% }) %></select></label>
          <label>Statut<select name="status"><% ['planifiee','confirmee','en_cours','terminee','annulee','reportee'].forEach(s=>{ %><option value="<%= s %>" <%= intervention.status===s?'selected':'' %>><%= ui.label(s) %></option><% }) %></select></label>
        </div>
        <div class="form-grid two">
          <label>Début<input type="datetime-local" name="starts_at" value="<%= ui.datetimeInput(intervention.starts_at) %>"></label>
          <label>Fin estimée<input type="datetime-local" name="ends_at" value="<%= ui.datetimeInput(intervention.ends_at) %>"></label>
        </div>
        <div class="form-grid two">
          <label>Tarif horaire<input name="hourly_rate" value="<%= intervention.hourly_rate || 0 %>"></label>
          <label>Prix prévu<input name="expected_price" value="<%= intervention.expected_price || 0 %>"></label>
        </div>
        <div class="form-grid two">
          <label>Note interne<textarea name="admin_comment"><%= intervention.admin_comment || '' %></textarea></label>
          <label>Commentaire client<textarea name="client_comment"><%= intervention.client_comment || '' %></textarea></label>
        </div>
        <button>Enregistrer</button>
      </form>
    </details>

    <section class="panel compact-panel">
      <div class="inline-heading"><h2>Rapports terrain</h2><span class="badge"><%= (fieldReports || []).length %></span></div>
      <div class="mobile-list compact-list">
        <% (fieldReports || []).forEach((report) => { %>
          <% const checks = parseChecklist(report.checklist_json); %>
          <article class="line-card report-admin-card">
            <strong><%= report.first_name %> <%= report.last_name %></strong>
            <span><%= ui.date(report.created_at, true) %> · <%= checks.length ? `${checks.filter((item) => item.done).length}/${checks.length} points` : 'Checklist non renseignée' %><%= report.client_signature_name ? ` · signé par ${report.client_signature_name}` : '' %></span>
            <a class="button secondary small" href="<%= adminBase %>/interventions/<%= intervention.id %>/rapports/<%= report.id %>/pdf">PDF</a>
          </article>
        <% }) %>
        <% if (!(fieldReports || []).length) { %><div class="empty-state slim"><strong>Aucun rapport terrain</strong><span>Les rapports employés avec photos, checklist et signature apparaîtront ici.</span></div><% } %>
      </div>
    </section>

    <section class="panel compact-panel">
      <div class="inline-heading"><h2>Timeline intervention</h2><span class="badge"><%= activity.length %></span></div>
      <% activity.forEach((item) => { %>
        <div class="result-row"><strong><%= ui.label(item.action) %></strong><span><%= item.first_name || 'Système' %> <%= item.last_name || '' %> · <%= ui.date(item.created_at, true) %></span></div>
      <% }) %>
      <% if (!activity.length) { %><div class="empty-state slim"><strong>Aucune activité détaillée</strong><span>Les actions terrain, signatures et validations seront affichées ici.</span></div><% } %>
    </section>
  </section>
</div>
