<?php use App\Core\Auth; 
  $ticketDisplay = $incident['ticket_id'] ?? '';
  if (empty($ticketDisplay)) { $ticketDisplay = $incident['reference'] ?? ('INC-' . (int)$incident['id']); }
  $title = 'Incident ' . htmlspecialchars($ticketDisplay);
?>
<?php
  $cu = Auth::user();
  $role = $cu['role_key'] ?? '';
  $showAdminQuickReportUI = false;
  $isAssigned = false;
  if (!empty($assignedUsers)) { foreach ($assignedUsers as $a) { if (($cu['name'] ?? '') === ($a['name'] ?? '')) { $isAssigned = true; break; } } }
  $canTreat = in_array($role, ['admin','agent'], true) || ($role==='technicien' && $isAssigned && in_array($treatmentState ?? 'none',['none','draft'],true));
  $canViewTreatment = in_array($role, ['admin','manager','superviseur','supervisor','agent','technicien'], true);
  $canFinalReport = ($role==='technicien' && $isAssigned && ($treatmentState==='validated') && !in_array($finalReportState, ['completed','validated'], true));
  $canValidateFinalReport = in_array($role, ['admin','manager','superviseur','supervisor'], true) && ($finalReportState === 'completed');
  
  // Calculs d'état
  $priorityClass = match($incident['priority']) {
    'Urgent' => 'danger', 'Haute' => 'warning', 'Moyenne' => 'info', 'Basse' => 'secondary', default => 'secondary'
  };
  $incidentStatusKey = strtolower($incident['status_key'] ?? '');
  $incidentStatusLabelLow = strtolower($incident['status_label'] ?? '');
  $isIncidentClosed = in_array($incidentStatusKey, ['closed','resolu','resolved','cloture','clôturé'], true)
    || str_contains($incidentStatusLabelLow, 'clôtur') || str_contains($incidentStatusLabelLow, 'clos');
  $isIncidentTreated = in_array($incidentStatusKey, ['treated','traite','processed'], true) || str_contains($incidentStatusLabelLow, 'trait');
  // Couleur de statut (palette centralisée + SLA)
  $statusColor = incident_status_color($incident);
  $canAssignTechnician = in_array($role, ['admin','agent'], true) && !$isIncidentClosed && !$isIncidentTreated;
  $hasRestoration = !empty($finalReport['restoration_at']);
  $forceCompleted = $isIncidentClosed || ($hasRestoration && ($finalReportState === 'completed'));
  $kpiIntervState = $interventionState ?? 'none';
  if ($forceCompleted && $kpiIntervState !== 'completed') { $kpiIntervState = 'completed'; }
  
  // Fallback commentaires
  $tree = isset($commentsTree) && is_array($commentsTree) ? $commentsTree : (isset($commentTree) && is_array($commentTree) ? $commentTree : []);
  if (empty($tree) && (!isset($comments) || !is_array($comments))) {
    try {
      $pdoC = \App\Core\Database::pdo();
      $stC = $pdoC->prepare('SELECT id, author_name, content, created_at FROM incident_comments WHERE incident_id = ? ORDER BY created_at DESC');
      $stC->execute([(int)$incident['id']]);
      $comments = $stC->fetchAll();
    } catch (\Throwable $e) { $comments = []; }
  }

  // Liaison / Sites / Coordonnées (affichage)
  $liaisonDisplay = '';
  $siteA = trim((string)($incident['site_a_label'] ?? ''));
  $siteB = trim((string)($incident['site_b_label'] ?? ''));
  if (!empty($liaison) && is_array($liaison)) {
    $liaisonDisplay = trim((string)($liaison['name'] ?? ''));
    if ($siteA === '' && !empty($liaison['site_a_name'])) { $siteA = trim((string)$liaison['site_a_name']); }
    if ($siteB === '' && !empty($liaison['site_b_name'])) { $siteB = trim((string)$liaison['site_b_name']); }
  }
  // Fallback: parser "[Site A vers Site B]" depuis le nom de liaison
  if (($siteA === '' || $siteB === '') && $liaisonDisplay !== '') {
    if (preg_match('/\[(.*?)\]/', $liaisonDisplay, $m)) {
      $inside = $m[1] ?? '';
      $parts = preg_split('/\s+(?:vers|to)\s+/iu', (string)$inside);
      if (is_array($parts) && count($parts) >= 2) {
        if ($siteA === '') { $siteA = trim((string)$parts[0]); }
        if ($siteB === '') { $siteB = trim((string)$parts[1]); }
      }
    }
  }

  $locationsList = (isset($locations) && is_array($locations)) ? $locations : [];
  $normalizeSiteName = function (string $name): string {
    $n = mb_strtoupper(trim($name));
    $n = str_replace(["\xC2\xA0"], ' ', $n);
    $n = preg_replace('/[\s\t\r\n]+/u', ' ', $n) ?? $n;
    $n = str_replace(['_', '-'], ' ', $n);
    $n = preg_replace('/\s+/u', ' ', $n) ?? $n;
    $n = preg_replace('/[\.,;:!?()\[\]{}"\'`]/u', '', $n) ?? $n;
    return trim($n);
  };
  $locationsIndex = [];
  foreach ($locationsList as $loc) {
    if (!is_array($loc) || empty($loc['name'])) continue;
    $key = $normalizeSiteName((string)$loc['name']);
    if ($key === '') continue;
    $lat = isset($loc['latitude']) ? trim((string)$loc['latitude']) : '';
    $lng = isset($loc['longitude']) ? trim((string)$loc['longitude']) : '';
    $has = ($lat !== '' && $lng !== '');
    if (!isset($locationsIndex[$key]) || (!$locationsIndex[$key]['has'] && $has)) {
      $locationsIndex[$key] = ['lat' => $lat, 'lng' => $lng, 'has' => $has];
    }
  }
  $coordsFor = function (string $siteName) use ($normalizeSiteName, $locationsIndex): string {
    $k = $normalizeSiteName($siteName);
    if ($k === '') return '';
    if (!isset($locationsIndex[$k]) || empty($locationsIndex[$k]['has'])) return '—';
    return $locationsIndex[$k]['lat'] . ', ' . $locationsIndex[$k]['lng'];
  };
  $siteACoords = $siteA !== '' ? $coordsFor($siteA) : '';
  $siteBCoords = $siteB !== '' ? $coordsFor($siteB) : '';
?>

<style>
  /* Design moderne pour la page incident */
  .incident-hero {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 16px;
    color: white;
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: 0 10px 40px rgba(102, 126, 234, 0.2);
  }
  .incident-hero .ticket-id {
    font-size: 1.75rem;
    font-weight: 700;
    margin-bottom: 0.5rem;
  }
  .incident-hero .incident-title {
    font-size: 1.25rem;
    opacity: 0.95;
    font-weight: 500;
  }
  .incident-hero .status-badge {
    padding: 0.5rem 1.25rem;
    border-radius: 50px;
    font-weight: 600;
    font-size: 0.875rem;
    backdrop-filter: blur(10px);
    background: rgba(255,255,255,0.2);
    border: 1px solid rgba(255,255,255,0.3);
  }
  
  /* Cartes KPI modernes */
  .kpi-card-modern {
    border-radius: 12px;
    border: none;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
  }
  .kpi-card-modern:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 24px rgba(0,0,0,0.1);
  }
  .kpi-card-modern::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
  }
  .kpi-card-modern.priority::before { background: linear-gradient(90deg, #ef4444, #f97316); }
  .kpi-card-modern.status::before { background: linear-gradient(90deg, #3b82f6, #06b6d4); }
  .kpi-card-modern.sla::before { background: linear-gradient(90deg, #8b5cf6, #a855f7); }
  .kpi-card-modern.intervention::before { background: linear-gradient(90deg, #10b981, #059669); }
  .kpi-card-modern.rapport::before { background: linear-gradient(90deg, #f59e0b, #d97706); }
  .kpi-card-modern.pauses::before { background: linear-gradient(90deg, #6366f1, #4f46e5); }
  
  .kpi-card-modern .kpi-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    margin-bottom: 1rem;
  }
  .kpi-card-modern.priority .kpi-icon { background: linear-gradient(135deg, #fecaca, #fca5a5); color: #dc2626; }
  .kpi-card-modern.status .kpi-icon { background: linear-gradient(135deg, #bfdbfe, #93c5fd); color: #2563eb; }
  .kpi-card-modern.sla .kpi-icon { background: linear-gradient(135deg, #ddd6fe, #c4b5fd); color: #7c3aed; }
  .kpi-card-modern.intervention .kpi-icon { background: linear-gradient(135deg, #bbf7d0, #86efac); color: #059669; }
  .kpi-card-modern.rapport .kpi-icon { background: linear-gradient(135deg, #fed7aa, #fdba74); color: #d97706; }
  .kpi-card-modern.pauses .kpi-icon { background: linear-gradient(135deg, #c7d2fe, #a5b4fc); color: #4f46e5; }
  
  .kpi-card-modern .kpi-label {
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: #64748b;
    margin-bottom: 0.5rem;
  }
  .kpi-card-modern .kpi-value {
    font-size: 1.5rem;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 0.25rem;
  }
  .kpi-card-modern .kpi-subtitle {
    font-size: 0.875rem;
    color: #64748b;
  }
  
  /* Onglets modernes */
  .nav-tabs-modern {
    border: none;
    gap: 0.5rem;
  }
  .nav-tabs-modern .nav-link {
    border: none;
    border-radius: 12px;
    padding: 0.875rem 1.5rem;
    font-weight: 600;
    color: #64748b;
    transition: all 0.3s ease;
    position: relative;
  }
  .nav-tabs-modern .nav-link:hover {
    background: #f1f5f9;
    color: #475569;
  }
  .nav-tabs-modern .nav-link.active {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  }
  .nav-tabs-modern .nav-link i {
    margin-right: 0.5rem;
  }
  
  /* Cards sidebar modernes */
  .sidebar-card {
    border-radius: 12px;
    border: none;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    margin-bottom: 1.5rem;
  }
  .sidebar-card .card-header {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border: none;
    border-radius: 12px 12px 0 0;
    padding: 1rem 1.25rem;
  }
  .sidebar-card .card-header h6 {
    margin: 0;
    font-weight: 700;
    color: #1e293b;
  }
  
  /* Timeline historique */
  .timeline {
    position: relative;
    padding-left: 2rem;
  }
  .timeline::before {
    content: '';
    position: absolute;
    left: 0.5rem;
    top: 0;
    bottom: 0;
    width: 2px;
    background: linear-gradient(180deg, #667eea 0%, #764ba2 100%);
  }
  .timeline-item {
    position: relative;
    margin-bottom: 1.5rem;
  }
  .timeline-item::before {
    content: '';
    position: absolute;
    left: -1.6rem;
    top: 0.25rem;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: white;
    border: 3px solid #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  }
  
  /* Commentaires style chat */
  .comment-item {
    display: flex;
    gap: 1rem;
    margin-bottom: 1.5rem;
  }
  .comment-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    flex-shrink: 0;
  }
  .comment-content {
    flex: 1;
    background: #f8fafc;
    border-radius: 12px;
    padding: 1rem;
  }
  .comment-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.5rem;
  }
  .comment-author {
    font-weight: 700;
    color: #1e293b;
  }
  .comment-time {
    font-size: 0.875rem;
    color: #64748b;
  }
  .comment-text {
    color: #475569;
    line-height: 1.6;
  }
  
  /* Animations */
  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  .fade-in-up {
    animation: fadeInUp 0.5s ease;
  }
  
  /* Responsive */
  @media (max-width: 768px) {
    .incident-hero {
      padding: 1.5rem;
    }
    .incident-hero .ticket-id {
      font-size: 1.5rem;
    }
  }
</style>

<!-- Hero Section -->
<div class="incident-hero fade-in-up">
  <div class="container-fluid px-0">
    <?php if (!empty($_GET['success']) || !empty($_GET['error'])): ?>
      <div class="mb-3">
        <?php if (!empty($_GET['success'])): ?>
          <div class="alert alert-success mb-0">
            <?php if ($_GET['success'] === 'unassigned'): ?>Technicien désassigné avec succès.<?php else: ?>Action réussie.<?php endif; ?>
          </div>
        <?php elseif (!empty($_GET['error'])): ?>
          <div class="alert alert-danger mb-0">
            <?php if ($_GET['error'] === 'already_assigned'): ?>Une assignation active existe déjà.<?php elseif($_GET['error']==='assignment_not_allowed'): ?>Assignation interdite pour cet état d'incident.<?php elseif($_GET['error']==='unassign_not_allowed'): ?>Désassignation interdite pour cet état d'incident.<?php else: ?>Action impossible.<?php endif; ?>
          </div>
        <?php endif; ?>
      </div>
    <?php endif; ?>
    <div class="row align-items-center">
      <div class="col-lg-8">
        <a href="<?= htmlspecialchars(route_url('/incidents')) ?>" class="btn btn-sm btn-light mb-3">
          <i class="fas fa-arrow-left me-2"></i>Retour aux incidents
        </a>
        <div class="ticket-id">
          <i class="fas fa-ticket-alt me-2"></i><?= htmlspecialchars($ticketDisplay) ?>
        </div>
        <div class="incident-title"><?= htmlspecialchars($incident['title']) ?></div>
        <?php if (!empty($incident['incident_number'])): ?>
          <div class="mt-2 opacity-75">
            <small><i class="fas fa-hashtag me-1"></i>Référence: <?= htmlspecialchars($incident['incident_number']) ?></small>
          </div>
        <?php endif; ?>
        <div class="mt-3 d-flex flex-wrap gap-2 align-items-center">
          <div><i class="fas fa-user me-1"></i><?= htmlspecialchars($incident['client_name']) ?></div>
          <div><i class="fas fa-location-dot me-1"></i><?= htmlspecialchars($incident['location_name']) ?></div>
          <div><i class="fas fa-calendar me-1"></i><?= date('d/m/Y H:i', strtotime($incident['declared_at'])) ?></div>
        </div>
      </div>
      <div class="col-lg-4 text-lg-end mt-3 mt-lg-0">
        <div class="status-badge mb-3" style="background:<?= htmlspecialchars($statusColor) ?>;">
          <?= htmlspecialchars($incident['status_label']) ?>
        </div>
        <div class="d-flex flex-wrap gap-2 justify-content-lg-end">
          <?php if ($canTreat): ?>
            <a href="<?= htmlspecialchars(route_url('/incidents/treatment',['id'=>$incident['id']])) ?>" class="btn btn-light btn-sm">
              <i class="fas fa-wrench me-1"></i>Traiter
            </a>
          <?php endif; ?>
          <?php if ($canViewTreatment): ?>
            <a href="<?= htmlspecialchars(route_url('/incidents/treatment',['id'=>$incident['id'],'view'=>1])) ?>" class="btn btn-light btn-sm">
              <i class="fas fa-eye me-1"></i>Voir
            </a>
          <?php endif; ?>
          <?php if ($canFinalReport): ?>
            <a href="#" class="btn btn-light btn-sm" data-bs-toggle="modal" data-bs-target="#finalReportModal">
              <i class="fas fa-file-signature me-1"></i>Clôturer
            </a>
          <?php endif; ?>
          <?php if ($canValidateFinalReport): ?>
            <button type="button" class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#finalReportValidateModal">
              <i class="fas fa-check-circle me-1"></i>Valider la clôture
            </button>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- KPI Cards -->
<div class="row g-3 mb-4 fade-in-up" style="animation-delay: 0.1s">
  <!-- Priorité -->
  <div class="col-6 col-lg-4 col-xl-2">
    <div class="card kpi-card-modern priority h-100">
      <div class="card-body">
        <div class="kpi-icon">
          <i class="fas fa-flag"></i>
        </div>
        <div class="kpi-label">Priorité</div>
        <div class="kpi-value">
          <span class="badge bg-<?= $priorityClass ?> bg-gradient"><?= htmlspecialchars($incident['priority'] ?? '—') ?></span>
        </div>
      </div>
    </div>
  </div>
  
  <!-- Statut -->
  <div class="col-6 col-lg-4 col-xl-2">
    <div class="card kpi-card-modern status h-100">
      <div class="card-body">
        <div class="kpi-icon">
          <i class="fas fa-circle-check"></i>
        </div>
        <div class="kpi-label">Statut</div>
        <div class="kpi-value">
          <span class="badge" style="background:<?= htmlspecialchars($statusColor) ?>;"><?= htmlspecialchars((string)($incident['status_label'] ?? '')) ?></span>
        </div>
      </div>
    </div>
  </div>
  
  <!-- SLA -->
  <div class="col-6 col-lg-4 col-xl-2">
    <div class="card kpi-card-modern sla h-100">
      <div class="card-body">
        <div class="kpi-icon">
          <i class="fas fa-clock"></i>
        </div>
        <div class="kpi-label">SLA Résolution</div>
        <div class="kpi-subtitle">
          <?php $expRes = $incident['expected_resolution_at'] ?? null; echo $expRes ? date('d/m H:i', strtotime($expRes)) : '—'; ?>
        </div>
      </div>
    </div>
  </div>
  
  <!-- Intervention -->
  <div class="col-6 col-lg-4 col-xl-2">
    <div class="card kpi-card-modern intervention h-100">
      <div class="card-body">
        <div class="kpi-icon">
          <i class="fas fa-person-digging"></i>
        </div>
        <div class="kpi-label">Intervention</div>
        <div class="kpi-subtitle">
          <?php
            $intervLabel = match($kpiIntervState) {
              'active' => 'En cours', 'paused' => 'En pause', 'completed' => 'Terminée', default => 'Aucune'
            };
          ?>
          <?= $intervLabel ?> • <?= htmlspecialchars($interventionDurationHuman ?? '0m') ?>
        </div>
      </div>
    </div>
  </div>
  
  <!-- Rapport final -->
  <div class="col-6 col-lg-4 col-xl-2">
    <div class="card kpi-card-modern rapport h-100">
      <div class="card-body">
        <div class="kpi-icon">
          <i class="fas fa-file-signature"></i>
        </div>
        <div class="kpi-label">Rapport final</div>
        <div class="kpi-subtitle">
          <?php
            $frLabel = match($finalReportState ?? 'none') {
              'validated' => 'Clôture validée',
              'completed' => 'Clôturé (à valider)',
              'pending' => 'En attente',
              default => 'Aucun'
            };
          ?>
          <?= $frLabel ?>
        </div>
      </div>
    </div>
  </div>
  
  <!-- Pauses -->
  <div class="col-6 col-lg-4 col-xl-2">
    <div class="card kpi-card-modern pauses h-100">
      <div class="card-body">
        <div class="kpi-icon">
          <i class="fas fa-pause"></i>
        </div>
        <div class="kpi-label">Pauses</div>
        <div class="kpi-value"><?= (int)($pauseCount ?? 0) ?></div>
      </div>
    </div>
  </div>
</div>

<!-- Main Content avec Tabs -->
<div class="row g-4 fade-in-up" style="animation-delay: 0.2s">
  <div class="col-xl-8">
    <!-- Tabs Navigation -->
    <ul class="nav nav-tabs-modern mb-4" id="incidentTabs" role="tablist">
      <li class="nav-item" role="presentation">
        <button class="nav-link active" id="tab-overview" data-bs-toggle="tab" data-bs-target="#pane-overview" type="button" role="tab">
          <i class="fas fa-circle-info"></i>Aperçu
        </button>
      </li>
      <li class="nav-item" role="presentation">
        <button class="nav-link" id="tab-comments" data-bs-toggle="tab" data-bs-target="#pane-comments" type="button" role="tab">
          <i class="fas fa-comments"></i>Commentaires
        </button>
      </li>
      <li class="nav-item" role="presentation">
        <button class="nav-link" id="tab-history" data-bs-toggle="tab" data-bs-target="#pane-history" type="button" role="tab">
          <i class="fas fa-clock-rotate-left"></i>Historique
        </button>
      </li>
    </ul>

    <!-- Tabs Content -->
    <div class="tab-content" id="incidentTabsContent">
      <!-- Aperçu -->
      <div class="tab-pane fade show active" id="pane-overview" role="tabpanel">
        <div class="card sidebar-card">
          <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-circle-info me-2"></i>Détails de l'incident</h5>
          </div>
          <div class="card-body">
            <div class="row g-3">
              <div class="col-md-6">
                <div class="mb-3">
                  <label class="text-muted small mb-1">Client</label>
                  <div class="fw-semibold"><?= htmlspecialchars($incident['client_name']) ?></div>
                </div>
              </div>
              <div class="col-md-6">
                <div class="mb-3">
                  <label class="text-muted small mb-1">Localisation</label>
                  <div class="fw-semibold"><?= htmlspecialchars((string)($incident['location_name'] ?? '')) ?></div>
                  <?php if (!empty($incident['location_address'])): ?>
                    <small class="text-muted"><?= htmlspecialchars((string)$incident['location_address']) ?></small>
                  <?php endif; ?>
                </div>
              </div>
              <div class="col-md-6">
                <div class="mb-3">
                  <label class="text-muted small mb-1">Cause</label>
                  <div class="fw-semibold"><?= !empty($incident['cause_name']) ? htmlspecialchars((string)$incident['cause_name']) : '<em class="text-muted">Non identifiée</em>' ?></div>
                </div>
              </div>
              <div class="col-md-6">
                <div class="mb-3">
                  <label class="text-muted small mb-1">Déclaré par</label>
                  <div class="fw-semibold"><?= htmlspecialchars((string)($incident['declared_by_name'] ?? '')) ?></div>
                  <small class="text-muted"><?= date('d/m/Y à H:i', strtotime($incident['declared_at'])) ?></small>
                </div>
              </div>

              <div class="col-md-6">
                <div class="mb-3">
                  <label class="text-muted small mb-1">Liaison</label>
                  <div class="fw-semibold"><?= $liaisonDisplay !== '' ? htmlspecialchars($liaisonDisplay) : '<em class="text-muted">—</em>' ?></div>
                </div>
              </div>
              <div class="col-md-6">
                <div class="mb-3">
                  <label class="text-muted small mb-1">Site A</label>
                  <div class="fw-semibold"><?= $siteA !== '' ? htmlspecialchars($siteA) : '<em class="text-muted">—</em>' ?></div>
                  <?php if ($siteA !== ''): ?><small class="text-muted">Coordonnées: <?= htmlspecialchars($siteACoords) ?></small><?php endif; ?>
                </div>
              </div>
              <div class="col-md-6">
                <div class="mb-3">
                  <label class="text-muted small mb-1">Site B</label>
                  <div class="fw-semibold"><?= $siteB !== '' ? htmlspecialchars($siteB) : '<em class="text-muted">—</em>' ?></div>
                  <?php if ($siteB !== ''): ?><small class="text-muted">Coordonnées: <?= htmlspecialchars($siteBCoords) ?></small><?php endif; ?>
                </div>
              </div>
              <?php if (!empty($incident['description'])): ?>
              <div class="col-12">
                <div class="mb-3">
                  <label class="text-muted small mb-1">Description</label>
                  <div class="p-3 bg-light rounded"><?= nl2br(htmlspecialchars((string)$incident['description'])) ?></div>
                </div>
              </div>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>

      <!-- Commentaires -->
      <div class="tab-pane fade" id="pane-comments" role="tabpanel">
        <?php
          $canAdd = false;
          $canSeeInternal = false;
          try {
            $me = \App\Core\Auth::user();
            $roleX = $me['role_key'] ?? '';
            $canSeeInternal = in_array($roleX, ['admin','agent','manager','superviseur','supervisor'], true);
            if (in_array($roleX, ['admin','agent'], true)) { $canAdd = true; }
            elseif ($roleX === 'technicien') {
              $pdoX = \App\Core\Database::pdo();
              $chkX = $pdoX->prepare('SELECT COUNT(*) FROM incident_assignments WHERE incident_id=? AND user_id=? AND active=1');
              $chkX->execute([(int)$incident['id'], (int)$me['id']]);
              $canAdd = ((int)$chkX->fetchColumn() > 0);
            }
          } catch (\Throwable $e) { }

          $treePublic = [];
          $treeInternal = [];
          if (!empty($tree) && is_array($tree)) {
            foreach ($tree as $n) {
              $isInt = (int)($n['is_internal'] ?? 0);
              if ($isInt === 1) { $treeInternal[] = $n; }
              else { $treePublic[] = $n; }
            }
          }

          $mentionUsersSafe = [];
          if (!empty($mentionUsers) && is_array($mentionUsers)) {
            foreach ($mentionUsers as $mu) {
              if (!is_array($mu)) { continue; }
              $h = trim((string)($mu['handle'] ?? ''));
              if ($h === '') { continue; }
              $mentionUsersSafe[] = [
                'handle' => $h,
                'label' => (string)($mu['label'] ?? $h),
              ];
            }
          }
        ?>
        
        <?php if ($canAdd): ?>
        <div class="card sidebar-card mb-4">
          <div class="card-body">
            <form method="post" action="<?= htmlspecialchars(route_url('/incidents/comment')) ?>" enctype="multipart/form-data">
              <input type="hidden" name="incident_id" value="<?= (int)$incident['id'] ?>">
              <input type="hidden" name="parent_id" id="commentParentId" value="">

              <div class="alert alert-info py-2 small mb-3 d-none" id="commentReplyBanner">
                <div class="d-flex align-items-center justify-content-between gap-2">
                  <div>
                    <i class="fas fa-reply me-1"></i>
                    Réponse à <span class="fw-semibold" id="commentReplyTo">—</span>
                  </div>
                  <button type="button" class="btn btn-sm btn-outline-secondary" id="commentCancelReplyBtn">
                    <i class="fas fa-xmark me-1"></i>Annuler
                  </button>
                </div>
              </div>

              <div class="mb-3">
                <label class="form-label fw-semibold">Ajouter un commentaire</label>
                <textarea name="comment" class="form-control" rows="3" required placeholder="Votre commentaire... (tapez @ pour mentionner)"></textarea>
                <div class="position-relative">
                  <div id="mentionSuggest" class="list-group position-absolute w-100 shadow-sm" style="z-index: 20; display:none; max-height: 220px; overflow:auto;"></div>
                </div>
              </div>
              <div class="row g-3 mb-3">
                <div class="col-md-6">
                  <?php if ($canSeeInternal): ?>
                    <div class="form-check">
                      <input class="form-check-input" type="checkbox" value="1" id="isInternalCheck" name="is_internal">
                      <label class="form-check-label" for="isInternalCheck">
                        <small>Interne (visible encadrement)</small>
                      </label>
                    </div>
                  <?php else: ?>
                    <small class="text-muted"><i class="fas fa-globe me-1"></i>Commentaire public</small>
                  <?php endif; ?>
                </div>
                <div class="col-md-6">
                  <input type="file" name="attachments[]" class="form-control form-control-sm" multiple>
                </div>
              </div>
              <button type="submit" class="btn btn-primary">
                <i class="fas fa-paper-plane me-1"></i>Publier
              </button>
            </form>
          </div>
        </div>
        <?php endif; ?>

        <div class="card sidebar-card">
          <div class="card-body">
            <?php
              if (!function_exists('render_incident_comment_node')) {
                function render_incident_comment_node(array $c, int $level, bool $canAdd): void {
                  $indent = max(0, min(8, $level));
                  $ms = $indent * 22;
                  $text = (string)($c['comment'] ?? $c['content'] ?? '');
                  $userName = (string)($c['user_name'] ?? $c['author_name'] ?? 'Utilisateur');
                  $createdAt = !empty($c['created_at']) ? date('d/m H:i', strtotime((string)$c['created_at'])) : '';
                  $commentId = (int)($c['id'] ?? 0);
                  $isInternal = (int)($c['is_internal'] ?? 0);
                  $children = (!empty($c['children']) && is_array($c['children'])) ? $c['children'] : [];

                  $wrapStyle = $indent > 0
                    ? 'margin-left:' . $ms . 'px; border-left: 2px solid rgba(13,110,253,.25); padding-left: 12px;'
                    : '';

                  $rendered = '';
                  if ($text !== '') {
                    $esc = htmlspecialchars($text);
                    // Mise en évidence des @mentions (sans HTML non maîtrisé)
                    $esc = preg_replace('/(^|\s)@([A-Za-z0-9._-]{2,40})\b/u', '$1<span class="fw-semibold text-primary">@$2</span>', $esc);
                    $rendered = nl2br($esc);
                  }
            ?>
              <div class="comment-item" style="<?= htmlspecialchars($wrapStyle) ?>">
                <div class="comment-avatar">
                  <?= strtoupper(substr($userName !== '' ? $userName : 'U', 0, 1)) ?>
                </div>
                <div class="comment-content">
                  <div class="comment-header">
                    <span class="comment-author"><?= htmlspecialchars($userName) ?></span>
                    <span class="comment-time"><?= htmlspecialchars($createdAt) ?></span>
                    <?php if ($isInternal === 1): ?>
                      <span class="badge bg-warning text-dark ms-2">Interne</span>
                    <?php endif; ?>
                  </div>
                  <div class="comment-text">
                    <?= $text !== '' ? $rendered : '<em class="text-muted">(Vide)</em>' ?>
                  </div>

                  <div class="mt-1 d-flex align-items-center gap-2">
                    <?php if ($canAdd && $commentId > 0): ?>
                      <button type="button"
                              class="btn btn-link btn-sm p-0 js-reply-comment"
                              data-comment-id="<?= $commentId ?>"
                              data-comment-user="<?= htmlspecialchars($userName) ?>"
                              data-is-internal="<?= $isInternal ?>">
                        <i class="fas fa-reply me-1"></i>Répondre
                      </button>
                    <?php endif; ?>
                  </div>

                  <?php if (!empty($c['attachments']) && is_array($c['attachments'])): ?>
                    <div class="mt-2 d-flex flex-wrap gap-2">
                      <?php foreach ($c['attachments'] as $att):
                        $raw = is_array($att) ? ($att['path'] ?? '') : $att;
                        $clean = ltrim((string)$raw, '/');
                        if (str_starts_with($clean, 'storage/uploads/')) { $clean = substr($clean, strlen('storage/uploads/')); }
                        $url = upload_url($clean);
                        $ext = strtolower(pathinfo($clean, PATHINFO_EXTENSION));
                        $isImg = in_array($ext, ['jpg','jpeg','png','gif','webp'], true);
                      ?>
                        <?php if ($isImg): ?>
                          <a href="<?= htmlspecialchars($url) ?>" data-file-url="<?= htmlspecialchars($url) ?>" class="js-open-file">
                            <img src="<?= htmlspecialchars($url) ?>" class="img-thumbnail" style="max-height:80px; border-radius:8px;" alt="pièce jointe">
                          </a>
                        <?php else: ?>
                          <a href="<?= htmlspecialchars($url) ?>" data-file-url="<?= htmlspecialchars($url) ?>" class="btn btn-sm btn-outline-secondary js-open-file">
                            <i class="fas fa-paperclip me-1"></i>Fichier
                          </a>
                        <?php endif; ?>
                      <?php endforeach; ?>
                    </div>
                  <?php endif; ?>
                </div>
              </div>
              <?php if (!empty($children)):
                foreach ($children as $child) {
                  if (is_array($child)) { render_incident_comment_node($child, $level + 1, $canAdd); }
                }
              endif; ?>
            <?php
                }
              }
            ?>
            <?php if (!empty($tree)): ?>
              <?php if ($canSeeInternal): ?>
                <ul class="nav nav-pills mb-3" id="commentsModeTabs" role="tablist">
                  <li class="nav-item" role="presentation">
                    <button class="nav-link active" type="button" data-comments-mode="public">Public</button>
                  </li>
                  <li class="nav-item" role="presentation">
                    <button class="nav-link" type="button" data-comments-mode="internal">Interne</button>
                  </li>
                </ul>
              <?php endif; ?>

              <div id="commentsBlockPublic">
                <?php if (!empty($treePublic)):
                  foreach ($treePublic as $c) {
                    if (is_array($c)) { render_incident_comment_node($c, 0, $canAdd); }
                  }
                else: ?>
                  <p class="text-muted text-center mb-0">Aucun commentaire public</p>
                <?php endif; ?>
              </div>

              <div id="commentsBlockInternal" style="display:none">
                <?php if ($canSeeInternal && !empty($treeInternal)):
                  foreach ($treeInternal as $c) {
                    if (is_array($c)) { render_incident_comment_node($c, 0, $canAdd); }
                  }
                elseif ($canSeeInternal): ?>
                  <p class="text-muted text-center mb-0">Aucun commentaire interne</p>
                <?php endif; ?>
              </div>
            <?php elseif (!empty($comments) && is_array($comments)): ?>
              <ul class="list-unstyled mb-0" id="commentsList">
                <?php foreach ($comments as $c): ?>
                  <div class="comment-item">
                    <div class="comment-avatar">
                      <?= strtoupper(substr($c['user_name'] ?? 'U', 0, 1)) ?>
                    </div>
                    <div class="comment-content">
                      <div class="comment-header">
                        <span class="comment-author"><?= htmlspecialchars($c['user_name'] ?? $c['author_name'] ?? 'Utilisateur') ?></span>
                        <span class="comment-time">
                          <?= !empty($c['created_at']) ? date('d/m H:i', strtotime($c['created_at'])) : '' ?>
                        </span>
                      </div>
                      <div class="comment-text">
                        <?= !empty($c['comment'] ?? $c['content'] ?? '') ? nl2br(htmlspecialchars($c['comment'] ?? $c['content'])) : '<em class="text-muted">(Vide)</em>' ?>
                      </div>
                    </div>
                  </div>
                <?php endforeach; ?>
              </ul>
            <?php else: ?>
              <p class="text-muted text-center mb-0" id="noCommentsMsg">
                <i class="fas fa-comments fa-2x mb-2 opacity-25"></i><br>
                Aucun commentaire pour le moment
              </p>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <!-- Historique -->
      <div class="tab-pane fade" id="pane-history" role="tabpanel">
        <div class="card sidebar-card">
          <div class="card-body">
            <?php if (!empty($history) && is_array($history)): ?>
              <div class="timeline">
                <?php foreach ($history as $h): ?>
                  <?php
                    $field = trim($h['field_name'] ?? ($h['event_label'] ?? ''));
                    $newVal = trim($h['new_value'] ?? ($h['details'] ?? ''));
                    $oldVal = trim($h['old_value'] ?? '');
                    $when = $h['changed_at'] ?? ($h['created_at'] ?? null);
                    $by = trim($h['changed_by_name'] ?? '');
                    $label = $field !== '' ? $field : 'Événement';
                    $details = '';
                    if ($newVal !== '' && $oldVal !== '') {
                      $details = 'De <strong>' . htmlspecialchars($oldVal) . '</strong> à <strong>' . htmlspecialchars($newVal) . '</strong>';
                    } elseif ($newVal !== '') { $details = htmlspecialchars($newVal); }
                    elseif ($oldVal !== '') { $details = 'Ancien: ' . htmlspecialchars($oldVal); }
                    if ($label === '' && $details === '') { continue; }
                  ?>
                  <div class="timeline-item">
                    <div class="d-flex justify-content-between align-items-start mb-1">
                      <span class="badge bg-primary bg-gradient"><?= htmlspecialchars($label) ?></span>
                      <small class="text-muted">
                        <?= $when ? date('d/m H:i', strtotime($when)) : '' ?>
                      </small>
                    </div>
                    <?php if ($details !== ''): ?>
                      <div class="small text-muted"><?= $details ?></div>
                    <?php endif; ?>
                    <?php if ($by !== ''): ?>
                      <div class="small text-muted mt-1">
                        <i class="fas fa-user me-1"></i><?= htmlspecialchars($by) ?>
                      </div>
                    <?php endif; ?>
                  </div>
                <?php endforeach; ?>
              </div>
            <?php else: ?>
              <p class="text-muted text-center mb-0">
                <i class="fas fa-clock-rotate-left fa-2x mb-2 opacity-25"></i><br>
                Aucun événement historisé
              </p>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Sidebar -->
  <div class="col-xl-4">
    <!-- Intervention -->
    <?php if (in_array($role, ['technicien','admin','agent'])): ?>
      <?php
        $origInterventionState = $interventionState ?? 'none';
        $state = $origInterventionState;
        if ($forceCompleted && $state !== 'completed') { $state = 'completed'; }
        $durHuman = htmlspecialchars($interventionDurationHuman ?? '0m');
        $pauseCountInt = (int)($pauseCount ?? 0);
      ?>
      <div class="sidebar-card card shadow-sm mb-3">
        <div class="card-header">
          <h6><i class="fas fa-toolbox me-2"></i>Intervention</h6>
        </div>
        <div class="card-body" id="interventionCardBody">
          <?php if ($state === 'active'): ?>
            <div class="alert alert-success mb-3">
              <i class="fas fa-person-digging me-2"></i>Intervention en cours
            </div>
            <div class="mb-3">
              <small class="text-muted">Durée</small>
              <div class="fw-semibold"><?= $durHuman ?></div>
            </div>
            <button type="button" id="btnInterventionPause" class="btn btn-warning btn-sm w-100">
              <i class="fas fa-pause me-1"></i>Mettre en pause
            </button>
          <?php elseif ($state === 'paused'): ?>
            <div class="alert alert-warning mb-3">
              <i class="fas fa-pause me-2"></i>Intervention en pause
            </div>
            <button type="button" id="btnInterventionResume" class="btn btn-success btn-sm w-100">
              <i class="fas fa-play me-1"></i>Reprendre
            </button>
          <?php elseif ($state === 'completed'): ?>
            <div class="alert alert-info mb-3">
              <i class="fas fa-flag-checkered me-2"></i>Intervention terminée
            </div>
            <div class="mb-3">
              <small class="text-muted">Durée totale</small>
              <div class="fw-semibold"><?= $durHuman ?></div>
            </div>
          <?php else: ?>
            <div class="alert alert-secondary py-2 small mb-3">
              <i class="fas fa-info-circle me-1"></i>Aucune intervention en cours
            </div>
            <button type="button" id="btnInterventionStart" class="btn btn-primary btn-sm w-100">
              <i class="fas fa-play me-1"></i>Démarrer l'intervention
            </button>
          <?php endif; ?>
          
          <div class="mt-3 d-flex gap-2">
            <a class="btn btn-sm btn-outline-secondary" href="<?= htmlspecialchars(route_url('/incidents/intervention/export-csv',['id'=>$incident['id']])) ?>">
              <i class="fas fa-file-csv"></i>
            </a>
            <a class="btn btn-sm btn-outline-secondary" href="<?= htmlspecialchars(route_url('/incidents/intervention/export-pdf',['id'=>$incident['id']])) ?>">
              <i class="fas fa-file-pdf"></i>
            </a>
            <a class="btn btn-sm btn-outline-info" href="<?= htmlspecialchars(route_url('/incidents/intervention/metrics-pdf',['id'=>$incident['id']])) ?>">
              <i class="fas fa-chart-line"></i>
            </a>
          </div>
        </div>
      </div>
    <?php endif; ?>

    <!-- Rapport (Admin) -->
    <?php if ($showAdminQuickReportUI && $role === 'admin' && !($isIncidentClosed && ($finalReportState ?? 'none') === 'validated')): ?>
      <div class="sidebar-card">
        <div class="card-header">
          <h6><i class="fas fa-file-circle-plus me-2"></i>Rapport de traitement (Admin)</h6>
        </div>
        <div class="card-body">
          <p class="small text-muted mb-2">Créer rapidement un rapport de traitement sans passer par l'écran dédié.</p>
          <button type="button" class="btn btn-sm btn-primary w-100" data-bs-toggle="modal" data-bs-target="#adminReportModal">
            <i class="fas fa-plus me-1"></i>Ajouter un rapport (Admin)
          </button>
        </div>
      </div>
    <?php endif; ?>

    <!-- Techniciens assignés -->
    <?php if ((!empty($assignedUsers) && is_array($assignedUsers)) || $canAssignTechnician): ?>
      <div class="sidebar-card card shadow-sm mb-3">
        <div class="card-header">
          <h6><i class="fas fa-users me-2"></i>Techniciens</h6>
        </div>
        <div class="card-body">
          <?php if (!empty($assignedUsers) && is_array($assignedUsers)): ?>
            <div class="list-group list-group-flush mb-3">
              <?php foreach ($assignedUsers as $u): ?>
                <div class="list-group-item small d-flex align-items-center gap-2 px-0">
                  <div class="comment-avatar" style="width:32px;height:32px;font-size:0.875rem;">
                    <?= strtoupper(substr($u['name'] ?? 'T', 0, 1)) ?>
                  </div>
                  <div>
                    <div class="fw-semibold"><?= htmlspecialchars($u['name'] ?? 'Technicien') ?></div>
                  <?php if ($role === 'admin'): ?>
                  <?php endif; ?>

                    <?php if (!empty($u['phone'])): ?>
                      <small class="text-muted"><i class="fas fa-phone me-1"></i><?= htmlspecialchars($u['phone']) ?></small>
                    <?php endif; ?>
                  </div>
                  <?php if ($canAssignTechnician && !empty($u['user_id'])): ?>
                    <div class="ms-auto">
                      <button type="button"
                              class="btn btn-sm btn-outline-danger js-unassign-btn"
                              data-incident-id="<?= (int)$incident['id'] ?>"
                              data-user-id="<?= (int)$u['user_id'] ?>"
                              data-user-name="<?= htmlspecialchars($u['name'] ?? 'Technicien') ?>">
                        <i class="fas fa-user-minus me-1"></i>Désassigner
                      </button>
                    </div>
                  <?php endif; ?>
                </div>
              <?php endforeach; ?>
            </div>
          <?php else: ?>
            <div class="alert alert-secondary py-2 small mb-3">
              <i class="fas fa-user-slash me-1"></i>Aucun technicien assigné
            </div>
          <?php endif; ?>

          <?php if ($canAssignTechnician && (empty($assignedUsers) || count((array)$assignedUsers) === 0)): ?>
          <form method="post" action="<?= htmlspecialchars(route_url('/incidents/assign')) ?>" class="row g-2 align-items-end">
            <input type="hidden" name="incident_id" value="<?= (int)$incident['id'] ?>">
            <div class="col-12">
              <?php $assignedIds = array_map(fn($x) => (int)($x['user_id'] ?? 0), is_array($assignedUsers)?$assignedUsers:[]); ?>
              <div class="form-floating">
                <select class="form-select form-select-sm" name="user_id" id="assignTechSelect" required>
                  <option value="" selected disabled>— Sélectionner —</option>
                  <?php if (!empty($techniciens) && is_array($techniciens)): ?>
                    <?php foreach ($techniciens as $t): $tid=(int)($t['id'] ?? 0); if ($tid<=0 || in_array($tid,$assignedIds,true)) { continue; } ?>
                      <option value="<?= $tid ?>"><?= htmlspecialchars($t['name'] ?? 'Technicien') ?></option>
                    <?php endforeach; ?>
                  <?php endif; ?>
                </select>
                <label for="assignTechSelect">Assigner un technicien</label>
              </div>
            </div>
            <div class="col-12 d-grid">
              <button type="submit" class="btn btn-sm btn-primary"><i class="fas fa-user-plus me-1"></i> Assigner</button>
            </div>
          </form>
          <?php elseif ($canAssignTechnician): ?>
            <p class="small text-muted mb-0"><i class="fas fa-lock me-1"></i> Assignation indisponible (statut traité/clôturé).</p>
          <?php endif; ?>
        </div>
      </div>
    <?php endif; ?>
  </div>
</div>

<!-- Modals (inclure les mêmes que detail.php) -->
<!-- Modal aperçu fichier -->
<div class="modal fade" id="filePreviewModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-file me-2"></i> Aperçu</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <div class="modal-body p-0" id="filePreviewBody">
        <iframe id="filePreviewFrame" src="" class="w-100 border-0" style="height:70vh; background:#fff"></iframe>
      </div>
      <div class="modal-footer">
        <a id="fileDownloadLink" href="#" class="btn btn-primary" target="_blank"><i class="fas fa-download me-1"></i> Ouvrir</a>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fermer</button>
      </div>
    </div>
  </div>
</div>

<?php if ($role === 'admin' && $showAdminQuickReportUI): ?>
<!-- Modale: Création rapide d'un rapport (Admin) -->
<style>
  .modal-lg{max-width:900px}
  #adminReportModal .modal-body{max-height:70vh;overflow-y:auto;}
</style>
<?php
  $rTeamName = !empty($treatmentReport['team_name']) ? $treatmentReport['team_name'] : ($cu['name'] ?? 'Admin');
  $rTeamContact = !empty($treatmentReport['team_contact']) ? $treatmentReport['team_contact'] : ($cu['phone'] ?? ($cu['email'] ?? ''));
  $rType = $treatmentReport['type_of_incident'] ?? '';
  $rDetection = $treatmentReport['detection_mode'] ?? '';
  $rCutKm = $treatmentReport['cut_distance_km'] ?? '';
  $rGpsLat = $treatmentReport['gps_lat'] ?? '';
  $rGpsLng = $treatmentReport['gps_lng'] ?? '';
  $rFault = $treatmentReport['fault_nature'] ?? '';
  $rRepairType = $treatmentReport['repair_type'] ?? '';
  $rWorkComments = $treatmentReport['work_comments'] ?? '';

  $rTakeover = '';
  if (!empty($treatmentReport['takeover_at'])) {
    $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $treatmentReport['takeover_at']);
    if ($dt) $rTakeover = $dt->format('Y-m-d\TH:i');
  }
  $rStart = '';
  if (!empty($treatmentReport['intervention_start'])) {
    $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $treatmentReport['intervention_start']);
    if ($dt) $rStart = $dt->format('Y-m-d\TH:i');
  }
  $rEnd = '';
  if (!empty($treatmentReport['intervention_end'])) {
    $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $treatmentReport['intervention_end']);
    if ($dt) $rEnd = $dt->format('Y-m-d\TH:i');
  }

  $rImpacted = '';
  if (!empty($treatmentReport['impacted_equipment'])) {
    $arr = @json_decode($treatmentReport['impacted_equipment'], true);
    if (is_array($arr)) {
      $rImpacted = implode(', ', array_filter($arr));
    }
  }
  $ticketLabel = isset($incident['ticket_id']) && $incident['ticket_id']
    ? (string)$incident['ticket_id']
    : ('Incident #'.(int)($incident['id'] ?? 0));
?>
<div class="modal fade" id="adminReportModal" tabindex="-1" aria-labelledby="adminReportLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="adminReportLabel"><i class="fas fa-file-medical me-2"></i> Rapport de traitement — <?= htmlspecialchars($ticketLabel) ?></h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <form id="adminReportForm" method="post" action="<?= htmlspecialchars(route_url('/incidents/treatment/save')) ?>" enctype="multipart/form-data">
        <input type="hidden" name="incident_id" value="<?= (int)$incident['id'] ?>">
        <div class="modal-body">
          <?php if (!empty($treatmentReport)): ?>
            <div class="alert alert-info mb-3">
              <i class="fas fa-info-circle me-2"></i>
              Les champs sont pré-remplis avec les données validées du traitement.
              <strong>Seul l'ajout d'un rapport final (fichier) permet de clôturer l'incident.</strong>
            </div>
          <?php endif; ?>

          <div class="row g-3">
            <div class="col-12 col-md-6">
              <div class="form-floating">
                <input type="text" class="form-control" id="ar_team_name" name="team_name" value="<?= htmlspecialchars($rTeamName) ?>" placeholder=" " readonly>
                <label for="ar_team_name">Équipe / Auteur</label>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="form-floating">
                <input type="text" class="form-control" id="ar_team_contact" name="team_contact" value="<?= htmlspecialchars($rTeamContact) ?>" placeholder=" " readonly>
                <label for="ar_team_contact">Contact</label>
              </div>
            </div>

            <div class="col-12 col-md-4">
              <div class="form-floating">
                <input type="text" class="form-control" id="ar_type" name="type_of_incident" value="<?= htmlspecialchars($rType) ?>" placeholder=" " readonly>
                <label for="ar_type">Type d'incident</label>
              </div>
            </div>
            <div class="col-12 col-md-4">
              <div class="form-floating">
                <input type="text" class="form-control" id="ar_detection" name="detection_mode" value="<?= htmlspecialchars($rDetection) ?>" placeholder=" " readonly>
                <label for="ar_detection">Mode de détection</label>
              </div>
            </div>
            <div class="col-12 col-md-4">
              <div class="form-floating">
                <input type="number" step="0.01" class="form-control" id="ar_cut_km" name="cut_distance_km" value="<?= htmlspecialchars($rCutKm) ?>" placeholder=" " readonly>
                <label for="ar_cut_km">Distance de coupure (km)</label>
              </div>
            </div>

            <div class="col-12 col-md-6">
              <div class="form-floating">
                <input type="number" step="0.000001" class="form-control" id="ar_gps_lat" name="gps_lat" value="<?= htmlspecialchars($rGpsLat) ?>" placeholder=" " readonly>
                <label for="ar_gps_lat">GPS Latitude</label>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="form-floating">
                <input type="number" step="0.000001" class="form-control" id="ar_gps_lng" name="gps_lng" value="<?= htmlspecialchars($rGpsLng) ?>" placeholder=" " readonly>
                <label for="ar_gps_lng">GPS Longitude</label>
              </div>
            </div>

            <div class="col-12 col-md-4">
              <label class="form-label">Prise en charge</label>
              <div class="input-group">
                <span class="input-group-text"><i class="far fa-calendar"></i></span>
                <input type="datetime-local" class="form-control" name="takeover_at" value="<?= htmlspecialchars($rTakeover) ?>" readonly>
              </div>
            </div>
            <div class="col-12 col-md-4">
              <label class="form-label">Début intervention</label>
              <div class="input-group">
                <span class="input-group-text"><i class="far fa-calendar"></i></span>
                <input type="datetime-local" class="form-control" name="intervention_start" value="<?= htmlspecialchars($rStart) ?>" readonly>
              </div>
            </div>
            <div class="col-12 col-md-4">
              <label class="form-label">Fin intervention</label>
              <div class="input-group">
                <span class="input-group-text"><i class="far fa-calendar"></i></span>
                <input type="datetime-local" class="form-control" name="intervention_end" value="<?= htmlspecialchars($rEnd) ?>" readonly>
              </div>
            </div>

            <div class="col-12 col-md-6">
              <div class="form-floating">
                <input type="text" class="form-control" id="ar_repair_type" name="repair_type" value="<?= htmlspecialchars($rRepairType) ?>" placeholder=" " readonly>
                <label for="ar_repair_type">Type de réparation</label>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="form-floating">
                <input type="text" class="form-control" id="ar_fault" name="fault_nature" value="<?= htmlspecialchars($rFault) ?>" placeholder=" " readonly>
                <label for="ar_fault">Nature de la panne</label>
              </div>
            </div>

            <div class="col-12">
              <div class="form-floating">
                <input type="text" class="form-control" id="ar_impacted" value="<?= htmlspecialchars($rImpacted) ?>" placeholder="Routeur, PTO, Boîtier" readonly />
                <label for="ar_impacted">Équipements impactés</label>
              </div>
            </div>

            <div class="col-12">
              <div class="form-floating">
                <textarea class="form-control" id="ar_work_comments" name="work_comments" placeholder=" " style="height: 110px" readonly><?= htmlspecialchars($rWorkComments) ?></textarea>
                <label for="ar_work_comments">Observations / Travaux effectués</label>
              </div>
            </div>

            <hr class="my-4">

            <div class="col-12">
              <h6 class="text-primary mb-3"><i class="fas fa-file-upload me-2"></i>Clôture de l'incident</h6>
              <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <strong>Important :</strong> L'upload d'un rapport final (PDF, Word, etc.) permettra de clôturer définitivement cet incident.
              </div>
            </div>

            <div class="col-12">
              <label class="form-label fw-bold">Rapport final de clôture <span class="text-danger">*</span></label>
              <div class="input-group">
                <span class="input-group-text"><i class="fas fa-file-pdf"></i></span>
                <input type="file" class="form-control" name="closure_report" id="ar_closure_report" accept=".pdf,.doc,.docx" required>
              </div>
              <div class="form-text">Formats acceptés : PDF, Word. Requis pour clôturer l'incident.</div>
            </div>

            <div class="col-12">
              <div class="form-floating">
                <textarea class="form-control" id="ar_closure_notes" name="closure_notes" placeholder=" " rows="3"></textarea>
                <label for="ar_closure_notes">Notes de clôture (optionnel)</label>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
          <button type="submit" class="btn btn-success" id="ar_submit_btn">
            <i class="fas fa-check-circle me-1"></i> Clôturer l'incident
          </button>
        </div>
      </form>
    </div>
  </div>
  <script>
    (function(){
      const form = document.getElementById('adminReportForm');
      form && form.addEventListener('submit', function(ev){
        const txt = document.getElementById('ar_impacted');
        if (!txt) return;
        const raw = (txt.value || '').split(',');
        raw.map(s => s.trim()).filter(Boolean).forEach(val => {
          const inp = document.createElement('input');
          inp.type = 'hidden';
          inp.name = 'impacted_equipment[]';
          inp.value = val;
          form.appendChild(inp);
        });
      });
    })();
  </script>
</div>
<?php endif; ?>

<!-- Modal motif de pause -->
<div class="modal fade" id="pauseReasonModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-pause me-2"></i>Motif de mise en pause</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-2">
          <label for="pauseReasonInput" class="form-label">Motif</label>
          <textarea id="pauseReasonInput" class="form-control" rows="3" placeholder="Ex: attente matériel..."></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
        <button type="button" class="btn btn-warning" id="pauseReasonSubmit"><i class="fas fa-check me-1"></i> Valider</button>
      </div>
    </div>
  </div>
</div>

<?php if ($canFinalReport): ?>
<style>.modal-backdrop.show{backdrop-filter:blur(3px);background-color:rgba(0,0,0,0.25);} .modal-lg{max-width:720px;} .form-text{font-size:.85rem;} .form-floating>textarea.form-control{height:120px;}</style>
<div class="modal fade" id="finalReportModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-lg modal-dialog-centered"><div class="modal-content"><div class="modal-header"><h5 class="modal-title"><i class="fas fa-file-signature me-2"></i> Rapport final</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button></div><div class="modal-body"><form id="finalReportForm" method="post" action="<?= htmlspecialchars(route_url('/incidents/final-report/save')) ?>" enctype="multipart/form-data"><input type="hidden" name="incident_id" value="<?= (int)$incident['id'] ?>"><div class="row g-3">
  <div class="col-12 col-md-6">
    <label class="form-label">Date et heure de remontée</label>
    <div class="input-group">
      <span class="input-group-text"><i class="far fa-calendar"></i></span>
      <?php $valFR = (!empty($finalReport['restoration_at']) ? date('Y-m-d\\TH:i', strtotime($finalReport['restoration_at'])) : ''); ?>
      <input type="datetime-local" name="restoration_at" class="form-control" value="<?= htmlspecialchars($valFR) ?>" required>
    </div>
    <div class="form-text">Horodatage de rétablissement.</div>
  </div>
  <div class="col-12 col-md-6">
    <div class="form-floating">
      <input id="fr_tech" type="text" class="form-control" value="<?= htmlspecialchars($cu['name'] ?? 'Technicien') ?>" disabled placeholder=" ">
      <label for="fr_tech">Technicien</label>
    </div>
  </div>
  <div class="col-12 col-md-6">
    <div class="form-floating">
      <input id="fr_client_supervisor" type="text" name="client_supervisor" class="form-control" value="<?= htmlspecialchars($finalReport['client_supervisor'] ?? '') ?>" placeholder="Nom superviseur côté client">
      <label for="fr_client_supervisor">Superviseur Client</label>
    </div>
    <div class="form-text">Saisi manuellement.</div>
  </div>
  <div class="col-12">
    <div class="form-floating">
      <textarea id="fr_comments" name="comments" class="form-control" placeholder="Observations finales..."><?= htmlspecialchars($finalReport['comments'] ?? '') ?></textarea>
      <label for="fr_comments">Commentaire</label>
    </div>
  </div>
  <div class="col-12">
    <label class="form-label mb-1">Pièces jointes</label>
    <div class="input-group">
      <span class="input-group-text"><i class="fas fa-paperclip"></i></span>
      <input type="file" name="final_attachments[]" class="form-control" multiple>
    </div>
    <div class="form-text">Images, PDF...</div>
  </div>
</div></form><?php
  try { $pdoFR = \App\Core\Database::pdo(); $stFR = $pdoFR->prepare('SELECT a.path FROM incident_final_report_attachments a JOIN incident_final_reports fr ON fr.id=a.final_report_id WHERE fr.incident_id=? ORDER BY a.id ASC'); $stFR->execute([(int)$incident['id']]); $rowsFR=$stFR->fetchAll(); } catch (\Throwable $e) { $rowsFR=[]; }
  if (!empty($rowsFR)) { echo '<div class="mt-3"><label class="form-label">Pièces jointes existantes</label><div class="d-flex flex-wrap gap-2">'; foreach ($rowsFR as $r){ $p=$r['path']; $clean=ltrim($p,'/'); if(str_starts_with($clean,'storage/uploads/')) $clean=substr($clean,strlen('storage/uploads/')); if(!str_starts_with($clean,'incidents/')) $clean='incidents/'.$incident['id'].'/final/'.basename($clean); $url=upload_url($clean); echo '<a class="btn btn-sm btn-outline-secondary js-open-file" data-file-url="'.htmlspecialchars($url).'" href="'.htmlspecialchars($url).'"><i class="fas fa-paperclip me-1"></i> PJ</a>'; } echo '</div></div>'; }
?></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button><button type="submit" form="finalReportForm" class="btn btn-primary"><i class="fas fa-check me-1"></i> Enregistrer et clôturer</button></div></div></div></div>
<?php endif; ?>

<?php if ($canValidateFinalReport): ?>
<div class="modal fade" id="finalReportValidateModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-check-circle me-2"></i> Confirmer la validation de la clôture</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <div class="modal-body">
        <p>Voulez-vous vraiment valider la clôture de cet incident ?</p>
        <ul class="mb-2">
          <li>Le rapport final sera marqué comme validé.</li>
          <li>Les profils technicien, admin, agent et superviseur recevront une notification in-app.</li>
        </ul>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
        <form method="post" action="<?= htmlspecialchars(route_url('/incidents/final-report/validate')) ?>" class="m-0">
          <input type="hidden" name="incident_id" value="<?= (int)$incident['id'] ?>">
          <button type="submit" class="btn btn-success">
            <i class="fas fa-check-circle me-1"></i> Oui, valider la clôture
          </button>
        </form>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<!-- Modal confirmation désassignation -->
<div class="modal fade" id="unassignConfirmModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-user-minus me-2"></i>Confirmer la désassignation</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        Voulez-vous désassigner le technicien <strong id="unassignTechName">—</strong> ?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
        <button type="button" class="btn btn-danger" id="unassignConfirmBtn"><i class="fas fa-check me-1"></i> Oui, désassigner</button>
      </div>
    </div>
  </div>
  </div>

<!-- Formulaire caché pour POST désassignation -->
<form id="unassignHiddenForm" method="post" action="<?= htmlspecialchars(route_url('/incidents/unassign')) ?>" class="d-none">
  <input type="hidden" name="incident_id" id="unassignIncidentId" value="">
  <input type="hidden" name="user_id" id="unassignUserId" value="">
  <input type="hidden" name="_csrf" value="">
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // Active le bon onglet Bootstrap si un hash est présent
  (function(){
    const hash = window.location.hash;
    if (hash) {
      const tabTriggerEl = document.querySelector(`button[data-bs-target="${hash}"]`);
      if (tabTriggerEl) {
        try { if (window.bootstrap && bootstrap.Tab) { new bootstrap.Tab(tabTriggerEl).show(); } } catch(e) { }
      }
    }
    document.querySelectorAll('button[data-bs-toggle="tab"]').forEach(btn=>{
      btn.addEventListener('shown.bs.tab', e => {
        const target = e.target?.getAttribute('data-bs-target');
        if (target && history.replaceState) { history.replaceState(null, '', target); }
      });
    });
  })();

  // Gestion des actions d'intervention
  const btnStart = document.getElementById('btnInterventionStart');
  const btnPause = document.getElementById('btnInterventionPause');
  const btnResume = document.getElementById('btnInterventionResume');
  const incidentId = <?= (int)$incident['id'] ?>;
  const pauseReasonInput = document.getElementById('pauseReasonInput');
  const pauseReasonSubmitBtn = document.getElementById('pauseReasonSubmit');
  let pauseModal = null;
  const pauseModalEl = document.getElementById('pauseReasonModal');
  if (pauseModalEl && window.bootstrap && bootstrap.Modal) { pauseModal = new bootstrap.Modal(pauseModalEl); }

  // Modal de rapport final
  const finalReportModalEl = document.getElementById('finalReportModal');
  let finalReportModal = null;
  if (finalReportModalEl && window.bootstrap && bootstrap.Modal) {
    finalReportModal = new bootstrap.Modal(finalReportModalEl);
  }

  function waitForBootstrap(cb, timeoutMs){
    const max = typeof timeoutMs === 'number' ? timeoutMs : 4000;
    const start = Date.now();
    if (window.bootstrap) return void cb();
    const iv = setInterval(()=>{
      if (window.bootstrap || (Date.now()-start) > max) { clearInterval(iv); if (window.bootstrap) cb(); }
    }, 120);
  }

  // Gestions des boutons de clôture (rapport final)
  const finalReportTriggers = document.querySelectorAll('a[data-bs-target="#finalReportModal"]');
  if (finalReportTriggers.length && finalReportModalEl) {
    window.openFinalReportModal = function() {
      if (!finalReportModal && window.bootstrap && bootstrap.Modal) {
        finalReportModal = new bootstrap.Modal(finalReportModalEl);
      }
      if (finalReportModal) {
        finalReportModal.show();
      } else if (typeof waitForBootstrap === 'function') {
        waitForBootstrap(() => {
          if (!finalReportModal && window.bootstrap && bootstrap.Modal) {
            finalReportModal = new bootstrap.Modal(finalReportModalEl);
          }
          if (finalReportModal) finalReportModal.show();
        });
      }
    };

    finalReportTriggers.forEach(btn => {
      btn.addEventListener('click', function(e) {
        // Laisser Bootstrap gérer data-bs-*, mais forcer si besoin
        if (!finalReportModal) {
          e.preventDefault();
          window.openFinalReportModal();
        }
      });
    });
  }

  async function postIntervention(action, extraParams) {
    const urlMap = {
      start: '<?= htmlspecialchars(route_url('/incidents/intervention/start')) ?>',
      pause: '<?= htmlspecialchars(route_url('/incidents/intervention/pause')) ?>',
      resume: '<?= htmlspecialchars(route_url('/incidents/intervention/resume')) ?>'
    };
    const params = new URLSearchParams({ incident_id: String(incidentId), ajax: '1' });
    if (extraParams) {
      Object.entries(extraParams).forEach(([k, v]) => { if (v !== undefined && v !== null) params.append(k, v); });
    }
    try {
      const resp = await fetch(urlMap[action], {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest' },
        body: params.toString(),
        credentials: 'same-origin'
      });
      const data = await resp.json().catch(() => ({}));
      if (resp.ok && data && data.status === 'ok') {
        location.reload(); // Recharger pour simplifier
      } else {
        alert(data && data.message ? data.message : 'Action échouée');
      }
    } catch (e) {
      alert('Erreur lors de l\'action');
    }
  }

  if (btnStart) {
    btnStart.addEventListener('click', () => postIntervention('start'));
  }
  if (btnPause) {
    btnPause.addEventListener('click', () => {
      if (pauseReasonInput) pauseReasonInput.value = '';
      if (!pauseModal && pauseModalEl && window.bootstrap && bootstrap.Modal) {
        pauseModal = new bootstrap.Modal(pauseModalEl);
      }
      if (pauseModal) {
        pauseModal.show();
      } else {
        waitForBootstrap(() => {
          if (!pauseModal && pauseModalEl && window.bootstrap && bootstrap.Modal) {
            pauseModal = new bootstrap.Modal(pauseModalEl);
          }
          if (pauseModal) pauseModal.show();
        });
      }
    });
  }
  if (btnResume) {
    btnResume.addEventListener('click', () => postIntervention('resume'));
  }

  if (pauseReasonSubmitBtn) {
    pauseReasonSubmitBtn.addEventListener('click', () => {
      const val = pauseReasonInput ? String(pauseReasonInput.value).trim() : '';
      if (!val) { alert('Motif requis'); return; }
      postIntervention('pause', { reason: val }).then(() => { if (pauseModal) pauseModal.hide(); });
    });
  }

  // Désassignation via modal Bootstrap
  let unassignModal = null;
  const unassignModalEl = document.getElementById('unassignConfirmModal');
  const unassignBtn = document.getElementById('unassignConfirmBtn');
  const unassignTechName = document.getElementById('unassignTechName');
  const unassignForm = document.getElementById('unassignHiddenForm');
  const unassignIncidentInput = document.getElementById('unassignIncidentId');
  const unassignUserInput = document.getElementById('unassignUserId');
  if (unassignModalEl && window.bootstrap && bootstrap.Modal) { unassignModal = new bootstrap.Modal(unassignModalEl); }

  document.addEventListener('click', function(e){
    const btn = e.target.closest && e.target.closest('.js-unassign-btn');
    if (!btn) return;
    e.preventDefault();
    const uid = btn.getAttribute('data-user-id');
    const iid = btn.getAttribute('data-incident-id');
    const uname = btn.getAttribute('data-user-name') || 'Technicien';
    if (unassignTechName) unassignTechName.textContent = uname;
    if (unassignIncidentInput) unassignIncidentInput.value = iid || '';
    if (unassignUserInput) unassignUserInput.value = uid || '';
    if (unassignModal) {
      unassignModal.show();
    } else if (typeof waitForBootstrap === 'function') {
      waitForBootstrap(() => {
        if (!unassignModal && unassignModalEl && window.bootstrap && bootstrap.Modal) {
          unassignModal = new bootstrap.Modal(unassignModalEl);
        }
        if (unassignModal) unassignModal.show();
      });
    }
  });

  if (unassignBtn) {
    unassignBtn.addEventListener('click', function(){
      if (!unassignForm) return;
      unassignForm.submit();
    });
  }

  // Délégation : ouverture des fichiers en modal
  (function(){
    const modalEl = document.getElementById('filePreviewModal');
    const frame = document.getElementById('filePreviewFrame');
    const dl = document.getElementById('fileDownloadLink');
    let modal;
    if (modalEl && window.bootstrap && bootstrap.Modal) { modal = new bootstrap.Modal(modalEl); }
    document.addEventListener('click', function(e){
      const a = e.target.closest && e.target.closest('a.js-open-file');
      if (!a) return;
      e.preventDefault();
      const url = a.getAttribute('data-file-url') || a.getAttribute('href');
      if (!url || !frame) return;
      frame.src = url;
      if (dl) dl.href = url;
      modal && modal.show();
    });
  })();

  // Soumission AJAX des commentaires (optionnel, simplifié pour le redesign)
  const commentForm = document.querySelector('#pane-comments form[action*="/incidents/comment"]');
  if (commentForm) {
    const uploadBase = '<?= htmlspecialchars(rtrim(upload_url(""), "/")) ?>';
    commentForm.addEventListener('submit', async function(e) {
      e.preventDefault();
      const fd = new FormData(commentForm);
      fd.append('ajax', '1');
      const submitBtn = commentForm.querySelector('button[type="submit"]');
      if (submitBtn) { submitBtn.disabled = true; submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Publication...'; }
      try {
        const resp = await fetch(commentForm.action, {
          method: 'POST',
          body: fd,
          headers: { 'X-Requested-With': 'XMLHttpRequest' },
          credentials: 'same-origin'
        });
        const data = await resp.json().catch(() => ({}));
        if (resp.ok && data && data.status === 'ok') {
          location.reload(); // Recharger pour simplifier
        } else {
          alert(data && data.message ? data.message : 'Publication échouée');
        }
      } catch (err) {
        alert('Erreur de publication');
      } finally {
        if (submitBtn) { submitBtn.disabled = false; submitBtn.innerHTML = '<i class="fas fa-paper-plane me-1"></i>Publier'; }
      }
    });

    // Toggle Public/Interne
    (function(){
      const tabs = document.querySelectorAll('#commentsModeTabs [data-comments-mode]');
      if (!tabs || tabs.length === 0) return;
      const pub = document.getElementById('commentsBlockPublic');
      const intl = document.getElementById('commentsBlockInternal');
      const setMode = (mode) => {
        tabs.forEach(t => t.classList.toggle('active', t.getAttribute('data-comments-mode') === mode));
        if (pub) pub.style.display = (mode === 'public') ? '' : 'none';
        if (intl) intl.style.display = (mode === 'internal') ? '' : 'none';
      };
      tabs.forEach(t => t.addEventListener('click', () => setMode(t.getAttribute('data-comments-mode') || 'public')));
      setMode('public');
    })();

    // Réponses: bouton "Répondre" sur chaque commentaire
    const parentIdInput = document.getElementById('commentParentId');
    const replyBanner = document.getElementById('commentReplyBanner');
    const replyToSpan = document.getElementById('commentReplyTo');
    const cancelReplyBtn = document.getElementById('commentCancelReplyBtn');
    const textarea = commentForm.querySelector('textarea[name="comment"]');
    const internalCheck = document.getElementById('isInternalCheck');

    const setReplyTarget = (id, user, isInternal) => {
      if (parentIdInput) parentIdInput.value = id ? String(id) : '';
      if (replyToSpan) replyToSpan.textContent = user ? String(user) : '—';
      if (replyBanner) replyBanner.classList.toggle('d-none', !id);
      if (internalCheck && typeof isInternal !== 'undefined' && isInternal !== null && isInternal !== '') {
        internalCheck.checked = String(isInternal) === '1';
        internalCheck.disabled = !!id; // hérite du parent
      } else if (internalCheck && !id) {
        internalCheck.disabled = false;
      }
      if (textarea) { textarea.focus(); }
      try { commentForm.scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch(e) {}
    };

    document.addEventListener('click', function(e){
      const btn = e.target.closest && e.target.closest('.js-reply-comment');
      if (!btn) return;
      e.preventDefault();
      const id = btn.getAttribute('data-comment-id');
      const user = btn.getAttribute('data-comment-user') || 'Utilisateur';
      const isInt = btn.getAttribute('data-is-internal');
      setReplyTarget(id, user, isInt);
    });

    if (cancelReplyBtn) {
      cancelReplyBtn.addEventListener('click', function(){
        setReplyTarget('', '—', null);
      });
    }

    // Mentions @user: autocomplétion très légère
    const mentionUsers = <?= json_encode($mentionUsersSafe, JSON_UNESCAPED_UNICODE) ?>;
    const suggestEl = document.getElementById('mentionSuggest');
    const hideSuggest = () => { if (suggestEl) { suggestEl.style.display = 'none'; suggestEl.innerHTML = ''; } };
    const showSuggest = (items, onPick) => {
      if (!suggestEl) return;
      suggestEl.innerHTML = '';
      items.forEach(it => {
        const a = document.createElement('button');
        a.type = 'button';
        a.className = 'list-group-item list-group-item-action';
        a.innerHTML = '<div class="fw-semibold">@' + it.handle + '</div><div class="small text-muted">' + (it.label || it.handle) + '</div>';
        a.addEventListener('click', () => onPick(it));
        suggestEl.appendChild(a);
      });
      suggestEl.style.display = items.length ? 'block' : 'none';
    };

    const getMentionQuery = (val, pos) => {
      const left = val.slice(0, pos);
      // Mode @[...]
      const m2 = left.match(/(^|\s)@\[([^\]\r\n]{0,80})$/);
      if (m2) return { mode: 'bracket', prefix: m2[1] || '', q: m2[2] || '' };
      // Mode @username
      const m1 = left.match(/(^|\s)@([A-Za-z0-9._-]{0,40})$/);
      if (m1) return { mode: 'handle', prefix: m1[1] || '', q: m1[2] || '' };
      return null;
    };

    const insertMention = (handle, label) => {
      if (!textarea) return;
      const pos = textarea.selectionStart || 0;
      const val = textarea.value;
      const mq = getMentionQuery(val, pos);
      if (!mq) return;
      let left = val.slice(0, pos);
      if (mq.mode === 'bracket') {
        const lbl = String(label || handle || '').trim();
        left = left.replace(/(^|\s)@\[([^\]\r\n]{0,80})$/, '$1@[' + lbl + '] ');
      } else {
        left = left.replace(/(^|\s)@([A-Za-z0-9._-]{0,40})$/, '$1@' + String(handle || '').trim() + ' ');
      }
      const right = val.slice(pos);
      textarea.value = left + right;
      const newPos = left.length;
      textarea.setSelectionRange(newPos, newPos);
      textarea.focus();
      hideSuggest();
    };

    if (textarea && suggestEl && Array.isArray(mentionUsers) && mentionUsers.length) {
      textarea.addEventListener('input', () => {
        const pos = textarea.selectionStart || 0;
        const mq = getMentionQuery(textarea.value, pos);
        if (!mq) { hideSuggest(); return; }
        const q = String(mq.q || '').toLowerCase();
        const items = mentionUsers
          .filter(u => String(u.handle || '').toLowerCase().startsWith(q))
          .slice(0, 6);
        showSuggest(items, (it) => insertMention(it.handle, it.label));
      });
      textarea.addEventListener('blur', () => { setTimeout(hideSuggest, 150); });
      document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') hideSuggest();
      });
    }
  }
});
</script>
