import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import type { User, EvaluationRecord, HistoryEntry, FieldChange } from './types';
import { FIELD_LABELS } from './types';
import HistoryTimeline from './Historytimeline';
import jsPDF from 'jspdf';

interface HistoriquePageProps {
    records: EvaluationRecord[];
    onNewEntry: () => void;
    user: User;
    onLogout: () => void;
    onUpdateRecord: (record: EvaluationRecord) => void;
    impersonatedUser?: User | null;
}

type StatusFilter = 'tous' | 'OUI' | 'NON' | 'PARTIEL';
type SortColumn = 'nom' | 'campus' | 'promo' | 'formation' | 'date' | 'autoEval' | 'tuteurEval' | 'commentaireRRE' | 'commentaireFormateur' | 'dateAction' | 'dateActionRRE';
type SortDirection = 'asc' | 'desc';

// ✅ FONCTIONS DATES CORRIGÉES - PLUS DE DÉCALAGE
function formatDateParis(dateString: string | null): string {
    if (!dateString) return '-';

    // Si c'est une date sans heure (YYYY-MM-DD), la parser directement
    if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
        const [year, month, day] = dateString.split('-');
        return `${day}/${month}/${year}`;
    }

    // Sinon utiliser Date avec timezone
    const date = new Date(dateString);
    return date.toLocaleDateString('fr-FR', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        timeZone: 'Europe/Paris'
    });
}

function formatDateTimeParis(dateString: string | null): string {
    if (!dateString) return '-';

    const date = new Date(dateString);
    return date.toLocaleString('fr-FR', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        timeZone: 'Europe/Paris'
    });
}

// ═══════════════════════════════════════════════════════
// STYLES CSS INTÉGRÉS
// ═══════════════════════════════════════════════════════
const styles = `
/* Reset global */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html {
    font-size: 16px;
}

@media (max-width: 1600px) {
    html { font-size: 15px; }
}

@media (max-width: 1400px) {
    html { font-size: 14px; }
}

@media (max-width: 1200px) {
    html { font-size: 13px; }
}

@media (max-width: 992px) {
    html { font-size: 12px; }
}

body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', sans-serif;
    min-height: 100vh;
    overflow-x: hidden;
}

.page-container {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    max-width: 100vw;
    overflow-x: hidden;
}

/* NAVBAR */
.navbar {
    background: white;
    padding: 0.75rem 1.5rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    position: sticky;
    top: 0;
    z-index: 100;
    gap: 1rem;
    flex-wrap: nowrap;
}

.nav-left {
    display: flex;
    align-items: center;
    gap: 1rem;
    flex-shrink: 0;
}

.nav-logo {
    font-size: 1.5rem;
}

.nav-info {
    display: flex;
    flex-direction: column;
    gap: 0.2rem;
}

.nav-title {
    font-weight: 700;
    font-size: 1.1rem;
    color: #1e293b;
    white-space: nowrap;
}

.nav-subtitle {
    display: flex;
    align-items: center;
    gap: 0.4rem;
    font-size: 0.8rem;
    color: #64748b;
}

.role-badge {
    background: #0ea5e9;
    color: white;
    padding: 0.2rem 0.6rem;
    border-radius: 9999px;
    font-size: 0.7rem;
    font-weight: 600;
}

.role-badge-super {
    background: #f59e0b;
    color: white;
}

.role-badge-lecteur {
    background: #64748b;
    color: white;
}

.form-select:disabled,
.form-input:disabled,
.form-textarea:disabled {
    background: #f1f5f9;
    cursor: not-allowed;
    opacity: 0.7;
    color: #64748b;
}


.nav-right {
    display: flex;
    align-items: center;
    gap: 1rem;
    flex-shrink: 0;
}

.user-name {
    font-weight: 600;
    color: #1e293b;
    font-size: 0.9rem;
    white-space: nowrap;
}

.logout-button {
    background: #ef4444;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 12px;
    cursor: pointer;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 0.4rem;
    transition: all 0.3s ease;
    font-size: 0.85rem;
    white-space: nowrap;
}

.logout-button:hover {
    background: #dc2626;
    transform: translateY(-2px);
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

/* MAIN CONTENT */
.main-content {
    flex: 1;
    padding: 1.25rem;
    max-width: 100%;
    margin: 0 auto;
    width: 100%;
}

.content-header {
    margin-bottom: 1.5rem;
}

.content-header h1 {
    font-size: 1.75rem;
    font-weight: 700;
    color: black;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-section {
    background: white;
    padding: 1.25rem;
    border-radius: 12px;
    margin-bottom: 1.25rem;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.search-wrapper {
    position: relative;
    max-width: 100%;
}

.search-icon {
    position: absolute;
    left: 0.9rem;
    top: 50%;
    transform: translateY(-50%);
    font-size: 1.1rem;
    color: #64748b;
}

.search-input {
    width: 100%;
    padding: 0.7rem 2.5rem;
    border: 2px solid #f1f5f9;
    border-radius: 12px;
    font-size: 0.9rem;
    transition: all 0.3s ease;
}

.search-input:focus {
    outline: none;
    border-color: #0ea5e9;
    box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.1);
}

.search-clear {
    position: absolute;
    right: 0.9rem;
    top: 50%;
    transform: translateY(-50%);
    background: #f1f5f9;
    border: none;
    width: 1.8rem;
    height: 1.8rem;
    border-radius: 50%;
    cursor: pointer;
    font-size: 1.2rem;
    color: #64748b;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
}

.search-clear:hover {
    background: #ef4444;
    color: white;
}

.filters-container {
    background: white;
    padding: 1.25rem;
    border-radius: 12px;
    margin-bottom: 1.25rem;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.filters-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 0.9rem;
    margin-bottom: 1rem;
}

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 0.4rem;
}

.filter-label {
    font-weight: 600;
    color: #1e293b;
    font-size: 0.8rem;
    display: flex;
    align-items: center;
    gap: 0.4rem;
}

.filter-icon {
    font-size: 0.9rem;
}

.filter-select {
    padding: 0.55rem 0.75rem;
    border: 2px solid #f1f5f9;
    border-radius: 12px;
    font-size: 0.85rem;
    background: white;
    cursor: pointer;
    transition: all 0.3s ease;
}

.filter-select:focus {
    outline: none;
    border-color: #0ea5e9;
}

.filter-select:disabled {
    background: #f1f5f9;
    cursor: not-allowed;
    opacity: 0.6;
}

.filter-hint {
    color: #64748b;
    font-size: 0.7rem;
    font-style: italic;
}

.reset-filters-button {
    background: #64748b;
    color: white;
    border: none;
    padding: 0.55rem 1rem;
    border-radius: 12px;
    cursor: pointer;
    font-weight: 600;
    transition: all 0.3s ease;
    width: 100%;
    font-size: 0.85rem;
}

.reset-filters-button:hover {
    background: #1e293b;
}

.table-container {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    overflow: auto;
    max-width: 100%;
}

.data-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 1000px;
}

.data-table thead {
    background: #0ea5e9;
    color: white;
    position: sticky;
    top: 0;
    z-index: 10;
}

.data-table th {
    padding: 0.75rem 0.6rem;
    text-align: left;
    font-weight: 600;
    font-size: 0.8rem;
    white-space: nowrap;
}

.data-table th.sortable {
    cursor: pointer;
    user-select: none;
    transition: all 0.3s ease;
}

.data-table th.sortable:hover {
    background: #0284c7;
}

.sort-icon {
    margin-left: 0.3rem;
    opacity: 0.5;
    font-size: 0.75rem;
}

.sort-icon.active {
    opacity: 1;
}

.data-table td {
    padding: 0.75rem 0.6rem;
    border-bottom: 1px solid #f1f5f9;
    font-size: 0.8rem;
}

.table-row {
    transition: all 0.3s ease;
}

.table-row:hover {
    background: #f1f5f9;
}

.text-center {
    text-align: center;
}

.student-cell {
    min-width: 160px;
}

.student-info {
    display: flex;
    flex-direction: column;
    gap: 0.2rem;
}

.student-name {
    color: #1e293b;
    font-weight: 600;
    font-size: 0.85rem;
}

.student-id {
    color: #64748b;
    font-size: 0.7rem;
}

.promo-text {
    color: #1e293b;
    font-weight: 500;
}

.status-badge {
    display: inline-block;
    padding: 0.3rem 0.6rem;
    border-radius: 9999px;
    font-size: 0.7rem;
    font-weight: 600;
    text-align: center;
}

.status-success {
    background: #dcfce7;
    color: #166534;
}

.status-progress {
    background: #fef3c7;
    color: #92400e;
}

.status-pending {
    background: #fee2e2;
    color: #991b1b;
}

.date-cell {
    min-width: 100px;
}

.date-text {
    color: #1e293b;
    font-weight: 500;
    font-size: 0.8rem;
}

.no-date {
    color: #64748b;
}

.commentaire-formateur-cell,
.commentaire-rre-cell {
    max-width: 250px;
}

.commentaire-content,
.commentaire-rre-content {
    display: flex;
    align-items: center;
    gap: 0.4rem;
}

.commentaire-icon {
    font-size: 0.9rem;
    flex-shrink: 0;
}

.commentaire-text {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: 0.8rem;
}

.no-comment {
    color: #64748b;
    text-align: center;
}

.history-count {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: #0ea5e9;
    color: white;
    width: 1.8rem;
    height: 1.8rem;
    border-radius: 50%;
    font-weight: 600;
    font-size: 0.8rem;
}

.actions-cell {
    min-width: 100px;
}

.action-buttons {
    display: flex;
    gap: 0.4rem;
    justify-content: center;
}

.action-btn {
    padding: 0.4rem;
    border: none;
    border-radius: 12px;
    cursor: pointer;
    font-size: 1.1rem;
    transition: all 0.3s ease;
    background: #f1f5f9;
}

.action-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.action-view:hover {
    background: #0ea5e9;
}

.action-export:hover {
    background: #22c55e;
}

.loading-state {
    text-align: center;
    padding: 3rem 1.5rem;
}

.spinner {
    width: 2.5rem;
    height: 2.5rem;
    border: 3px solid #f1f5f9;
    border-top-color: #0ea5e9;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 0 auto 1rem;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.empty-state {
    text-align: center;
    padding: 3rem 1.5rem;
    color: #64748b;
}

.empty-icon {
    font-size: 3rem;
    margin-bottom: 1rem;
}

.modal-header {
    padding: 1.2rem 1.5rem;
    background: linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%);
    color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 20px 20px 0 0;
}

.modal-header h2 {
    font-size: 1.3rem;
    font-weight: 700;
}

.modal-close {
    background: rgba(255, 255, 255, 0.2);
    border: none;
    color: white;
    font-size: 1.8rem;
    width: 2.2rem;
    height: 2.2rem;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.modal-close:hover {
    background: rgba(255, 255, 255, 0.3);
    transform: rotate(90deg);
}

.modal-student-info {
    padding: 1.2rem 1.5rem;
    background: #f1f5f9;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 0.9rem;
    border-bottom: 2px solid #e2e8f0;
}

.info-row {
    display: flex;
    flex-direction: column;
    gap: 0.2rem;
}

.info-label {
    font-size: 0.7rem;
    font-weight: 600;
    color: #64748b;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.info-value {
    font-size: 0.9rem;
    font-weight: 600;
    color: #1e293b;
}

.column-section-title {
    font-size: 1.15rem;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 1.2rem;
    display: flex;
    align-items: center;
    gap: 0.6rem;
    padding-bottom: 0.6rem;
    border-bottom: 2px solid #f1f5f9;
}

.column-section-title span:first-child {
    font-size: 1.3rem;
}

.history-badge {
    background: #0ea5e9;
    color: white;
    padding: 0.2rem 0.6rem;
    border-radius: 9999px;
    font-size: 0.8rem;
    font-weight: 600;
}

.no-history-message {
    text-align: center;
    padding: 2.5rem 1rem;
    color: #64748b;
}

.no-history-icon {
    font-size: 3.5rem;
    margin-bottom: 1rem;
}

.current-status {
    background: white;
    padding: 1.2rem;
    border-radius: 12px;
    margin-bottom: 1.2rem;
    border: 2px solid #f1f5f9;
}

.current-status h3 {
    font-size: 1rem;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 0.9rem;
}

.status-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
    gap: 0.9rem;
}

.status-item {
    display: flex;
    flex-direction: column;
    gap: 0.4rem;
}

.status-item-label {
    font-size: 0.7rem;
    font-weight: 600;
    color: #64748b;
    text-transform: uppercase;
}

.status-item-value {
    font-size: 0.8rem;
    font-weight: 600;
    color: #1e293b;
}

.action-form {
    background: white;
    padding: 1.2rem;
    border-radius: 12px;
    border: 2px solid #f1f5f9;
}

.form-grid-2col {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 0.9rem;
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: 0.4rem;
}

.form-group-full {
    grid-column: 1 / -1;
}

.form-label {
    font-weight: 600;
    color: #1e293b;
    font-size: 0.8rem;
    display: flex;
    align-items: center;
    gap: 0.4rem;
}

.label-icon {
    font-size: 0.9rem;
}

.required-star {
    color: #ef4444;
    margin-left: 0.2rem;
}

.form-select,
.form-input {
    padding: 0.65rem;
    border: 2px solid #f1f5f9;
    border-radius: 12px;
    font-size: 0.8rem;
    transition: all 0.3s ease;
}

.form-select:focus,
.form-input:focus {
    outline: none;
    border-color: #0ea5e9;
    box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.1);
}

.form-textarea {
    padding: 0.65rem;
    border: 2px solid #f1f5f9;
    border-radius: 12px;
    font-size: 0.8rem;
    font-family: inherit;
    resize: vertical;
    transition: all 0.3s ease;
    min-height: 80px;
}

.form-textarea:focus {
    outline: none;
    border-color: #0ea5e9;
    box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.1);
}

.form-textarea-highlight {
    border-color: #f59e0b;
    background: #fffbeb;
}

.rre-readonly-info {
    background: #f1f5f9;
    padding: 0.9rem;
    border-radius: 12px;
    margin-bottom: 1.2rem;
    border-left: 4px solid #0ea5e9;
}

.rre-readonly-info h4 {
    font-size: 0.9rem;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 0.6rem;
}

.rre-readonly-info p {
    font-size: 0.8rem;
    color: #1e293b;
    margin-bottom: 0.4rem;
}

.modal-footer {
    padding: 1.2rem 1.5rem;
    background: #f1f5f9;
    display: flex;
    justify-content: flex-end;
    gap: 0.9rem;
    border-radius: 0 0 20px 20px;
    flex-wrap: wrap;
}

.secondary-button {
    background: #64748b;
    color: white;
    border: none;
    padding: 0.65rem 1.2rem;
    border-radius: 12px;
    cursor: pointer;
    font-weight: 600;
    transition: all 0.3s ease;
    font-size: 0.85rem;
}

.secondary-button:hover {
    background: #1e293b;
    transform: translateY(-2px);
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.btn-add-action {
    background: #22c55e;
    color: white;
    border: none;
    padding: 0.65rem 1.2rem;
    border-radius: 12px;
    cursor: pointer;
    font-weight: 600;
    transition: all 0.3s ease;
    font-size: 0.85rem;
}

.btn-add-action:hover:not(:disabled) {
    background: #16a34a;
    transform: translateY(-2px);
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.btn-add-action:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.table-container::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

.table-container::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb {
    background: #0ea5e9;
    border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb:hover {
    background: #0284c7;
}

.table-container::-webkit-scrollbar-corner {
    background: #f1f5f9;
}

@media (max-width: 768px) {
    html { font-size: 14px; }
    
    .navbar {
        flex-direction: column;
        align-items: flex-start;
        padding: 0.9rem;
    }
    
    .nav-right {
        width: 100%;
        justify-content: space-between;
    }
    
    .filters-grid {
        grid-template-columns: 1fr;
    }
    
    .data-table {
        min-width: 800px;
    }
}
`;

// ═══════════════════════════════════════════════════════
// UTILITAIRES
// ═══════════════════════════════════════════════════════
const fixWeirdPdfEncoding = (text: string): string => {
    if (!text) return text;
    let result = text;
    result = result.replace(/Ø>Ýê/g, '');
    return result;
};

const sanitizeTextForPDF = (value: any): string => {
    if (value === null || value === undefined) return 'N/A';
    let result = String(value);
    result = result.normalize('NFC');
    result = result.replace(/[\u200B-\u200D\uFEFF]/g, '');
    result = fixWeirdPdfEncoding(result);
    return result;
};

const formatDateForInput = (dateString: string | null | undefined): string => {
    if (!dateString) return '';
    try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return '';
        return date.toISOString().split('T')[0];
    } catch {
        return '';
    }
};

// ═══════════════════════════════════════════════════════
// TRANSFORMATION HISTORIQUE
// ═══════════════════════════════════════════════════════
const transformHistoryData = (apiData: any[]): HistoryEntry[] => {
    if (!apiData || !Array.isArray(apiData)) {
        return [];
    }

    return apiData.map((item, index) => {
        const changes: FieldChange[] = [];

        if (item.auto_evaluation_new !== null && item.auto_evaluation_new !== undefined) {
            changes.push({
                field: 'autoEvaluation' as keyof EvaluationRecord,
                fieldLabel: 'Auto-évaluation',
                oldValue: item.auto_evaluation_old || '(vide)',
                newValue: item.auto_evaluation_new
            });
        }

        if (item.evaluation_tuteur_new !== null && item.evaluation_tuteur_new !== undefined) {
            changes.push({
                field: 'evaluationTuteur' as keyof EvaluationRecord,
                fieldLabel: 'Évaluation tuteur',
                oldValue: item.evaluation_tuteur_old || '(vide)',
                newValue: item.evaluation_tuteur_new
            });
        }

        if (item.date_action_new !== null && item.date_action_new !== undefined) {
            changes.push({
                field: 'dateAction' as keyof EvaluationRecord,
                fieldLabel: 'Date action formateur',
                oldValue: item.date_action_old || '(vide)',
                newValue: item.date_action_new
            });
        }

        if (item.date_action_rre_new !== null && item.date_action_rre_new !== undefined) {
            changes.push({
                field: 'dateActionRRE' as keyof EvaluationRecord,
                fieldLabel: 'Date action RRE',
                oldValue: item.date_action_rre_old || '(vide)',
                newValue: item.date_action_rre_new
            });
        }

        if (item.commentaire_formateur_new !== null && item.commentaire_formateur_new !== undefined) {
            changes.push({
                field: 'commentaireFormateur' as keyof EvaluationRecord,
                fieldLabel: 'Commentaire formateur',
                oldValue: item.commentaire_formateur_old || '(vide)',
                newValue: item.commentaire_formateur_new
            });
        }

        if (item.commentaire_rre_new !== null && item.commentaire_rre_new !== undefined) {
            changes.push({
                field: 'commentaireRRE' as keyof EvaluationRecord,
                fieldLabel: 'Commentaire RRE',
                oldValue: item.commentaire_rre_old || '(vide)',
                newValue: item.commentaire_rre_new
            });
        }

        if (item.commentaire_new !== null && item.commentaire_new !== undefined) {
            changes.push({
                field: 'commentaire' as keyof EvaluationRecord,
                fieldLabel: 'Commentaire',
                oldValue: item.commentaire_old || '(vide)',
                newValue: item.commentaire_new
            });
        }

        const actionType = item.action_type?.toUpperCase();
        const action: 'creation' | 'Nouvelle Action' =
            actionType === 'CREATION' ? 'creation' : 'Nouvelle Action';

        return {
            id: String(item.id || `history-${index}`),
            timestamp: item.created_at || new Date().toISOString(),
            userId: item.author_email || '',
            userName: item.author_name || 'Inconnu',
            userRole: (item.author_role?.toLowerCase() === 'rre' ? 'rre' : 'formateur') as 'formateur' | 'rre',
            action,
            reason: item.action_description || 'Modification',
            changes,
            autoEvaluation: item.auto_evaluation_new,
            evaluationTuteur: item.evaluation_tuteur_new,
            dateAction: item.date_action_new,
            dateActionRRE: item.date_action_rre_new,
            commentaireFormateur: item.commentaire_formateur_new,
            commentaireRRE: item.commentaire_rre_new
        };
    });
};

// ═══════════════════════════════════════════════════════
// COMPOSANT PRINCIPAL
// ═══════════════════════════════════════════════════════
const HistoriquePage: React.FC<HistoriquePageProps> = ({
    records: initialRecords,
    onNewEntry,
    user,
    onLogout,
    onUpdateRecord,
    impersonatedUser
}) => {
    const [filter, setFilter] = useState<string>('');
    const [statusFilter, setStatusFilter] = useState<StatusFilter>('tous');
    const [campusFilter, setCampusFilter] = useState<string>('tous');
    const [promoFilter, setPromoFilter] = useState<string>('tous');
    const [studentFilter, setStudentFilter] = useState<string>('tous');
    const [selectedRecord, setSelectedRecord] = useState<EvaluationRecord | null>(null);
    const [isDetailModalOpen, setIsDetailModalOpen] = useState<boolean>(false);
    const [sortColumn, setSortColumn] = useState<SortColumn>('date');
    const [sortDirection, setSortDirection] = useState<SortDirection>('desc');

    const [campusList, setCampusList] = useState<string[]>(['tous']);
    const [promoList, setPromoList] = useState<string[]>(['tous']);
    const [studentsList, setStudentsList] = useState<{ id: string; name: string }[]>([]);
    const [records, setRecords] = useState<EvaluationRecord[]>(initialRecords);
    const [isLoading, setIsLoading] = useState<boolean>(true);
    const [isSaving, setIsSaving] = useState<boolean>(false);

    const [editAutoEval, setEditAutoEval] = useState<string>('NON');
    const [editTuteurEval, setEditTuteurEval] = useState<string>('NON');
    const [editCommentaire, setEditCommentaire] = useState<string>('');
    const [editDateAction, setEditDateAction] = useState<string>('');
    const [editDateActionRRE, setEditDateActionRRE] = useState<string>('');
    const [editCommentaireFormateur, setEditCommentaireFormateur] = useState<string>('');
    const [editDateEvalTuteur, setEditDateEvalTuteur] = useState<string>('');
    const [editCommentaireRRE, setEditCommentaireRRE] = useState<string>('');

    // ✅ Vérifier si l'utilisateur peut modifier (pas lecteur)
    const effectiveRole = impersonatedUser?.role || user.role;
    const canModify = effectiveRole !== 'lecteur';

    const getRequestHeaders = useCallback((): Record<string, string> => {
        const headers: Record<string, string> = {
            'X-User-Role': user.role,
            'X-User-Email': user.email || '',
            'X-User-Campus': user.campus || ''
        };

        if (user.role === 'super' && impersonatedUser) {
            headers['X-Impersonated-Email'] = impersonatedUser.email || '';
            headers['X-Impersonated-Role'] = impersonatedUser.role;
            headers['X-Impersonated-Campus'] = impersonatedUser.campus || '';
        }

        return headers;
    }, [user.role, user.email, user.campus, impersonatedUser]);

    useEffect(() => {
        const styleElement = document.createElement('style');
        styleElement.innerHTML = styles;
        document.head.appendChild(styleElement);

        return () => {
            document.head.removeChild(styleElement);
        };
    }, []);
    useEffect(() => {
        const effectiveRole = impersonatedUser?.role || user.role;
        const effectiveCampus = impersonatedUser?.campus || user.campus;

        // 🔥 CORRECTION : Super-user et RRE ont leur campus fixé
        if (user.role === 'super' && !impersonatedUser && effectiveCampus) {
            setCampusFilter(effectiveCampus);
        } else if (effectiveRole === 'rre' && effectiveCampus) {
            setCampusFilter(effectiveCampus);
        } else if (user.role === 'super' && !impersonatedUser && !effectiveCampus) {
            // Si super-user sans campus défini, "tous"
            setCampusFilter('tous');
        } else {
            setCampusFilter('tous');
        }
    }, [user.role, user.campus, impersonatedUser]);
    const loadData = useCallback(async () => {
        setIsLoading(true);
        try {
            const headers = getRequestHeaders();

            const evalRes = await fetch('/api/evaluations', { headers });
            if (evalRes.ok) {
                const response = await evalRes.json();

                // ✅ CORRECTION : gérer les deux formats de réponse
                let recordsData = [];

                if (response.data && Array.isArray(response.data)) {
                    // Format avec wrapper { data: [...] }
                    recordsData = response.data;
                } else if (Array.isArray(response)) {
                    // Format direct [...]
                    recordsData = response;
                } else {
                    console.warn('⚠️ Format de réponse inattendu:', response);
                    recordsData = [];
                }

                setRecords(recordsData);
                console.log('✅ Records chargés:', recordsData.length);
            } else {
                console.error('❌ Erreur fetch evaluations:', evalRes.status);
                setRecords([]);
            }

            const effectiveRole = impersonatedUser?.role || user.role;
            const effectiveCampus = impersonatedUser?.campus || user.campus;

            const campusRes = await fetch('/api/campus-list', { headers });
            if (campusRes.ok) {
                const campuses = await campusRes.json();

                // 🔥 SUPER-USER SANS USURPATION : SON campus uniquement
                if (user.role === 'super' && !impersonatedUser) {
                    if (effectiveCampus && campuses.length > 0) {
                        setCampusList(campuses);
                        setCampusFilter(campuses[0]);
                    } else {
                        setCampusList(['tous', ...campuses]);
                    }
                } else if (effectiveRole === 'rre') {
                    setCampusList(campuses.length > 0 ? campuses : [effectiveCampus]);
                    if (campuses.length > 0) {
                        setCampusFilter(campuses[0]);
                    }
                } else {
                    setCampusList(['tous', ...(campuses.length > 0 ? campuses : [effectiveCampus])]);
                }
            } else {
                if (user.role === 'super' && !impersonatedUser) {
                    if (effectiveCampus) {
                        setCampusList([effectiveCampus]);
                        setCampusFilter(effectiveCampus);
                    } else {
                        setCampusList(['tous']);
                    }
                } else if (effectiveRole === 'rre') {
                    setCampusList([effectiveCampus || '']);
                    if (effectiveCampus) {
                        setCampusFilter(effectiveCampus);
                    }
                } else {
                    setCampusList(['tous', effectiveCampus || '']);
                }
            }
        } catch (error) {
            console.error('❌ Erreur chargement données:', error);
            setRecords([]);
            const effectiveRole = impersonatedUser?.role || user.role;
            const effectiveCampus = impersonatedUser?.campus || user.campus;
            if (user.role === 'super' && !impersonatedUser) {
                if (effectiveCampus) {
                    setCampusList([effectiveCampus]);
                    setCampusFilter(effectiveCampus);
                } else {
                    setCampusList(['tous']);
                }
            } else if (effectiveRole === 'rre') {
                setCampusList([effectiveCampus || '']);
                if (effectiveCampus) {
                    setCampusFilter(effectiveCampus);
                }
            } else {
                setCampusList(['tous', effectiveCampus || '']);
            }
        } finally {
            setIsLoading(false);
        }
    }, [getRequestHeaders, user.role, user.campus, impersonatedUser]);
    useEffect(() => {
        loadData();
    }, [loadData]);

    useEffect(() => {
        const loadFilteredData = async () => {
            if (campusFilter === 'tous') {
                setPromoList(['tous']);
                setStudentsList([]);
                setStudentFilter('tous');
                return;
            }

            try {
                const headers = getRequestHeaders();

                const promoRes = await fetch(
                    `/api/promo-list?campus=${encodeURIComponent(campusFilter)}`,
                    { headers }
                );
                if (promoRes.ok) {
                    const promos = await promoRes.json();
                    setPromoList(['Tous', ...promos]);
                }

                let studentUrl = `/api/student-list?campus=${encodeURIComponent(campusFilter)}`;
                if (promoFilter !== 'Tous') {
                    studentUrl += `&promo=${encodeURIComponent(promoFilter)}`;
                }

                const studentRes = await fetch(studentUrl, { headers });
                if (studentRes.ok) {
                    const students = await studentRes.json();
                    setStudentsList(students);
                }

            } catch (error) {
                console.error('❌ Erreur chargement filtres:', error);
            }
        };

        loadFilteredData();
    }, [campusFilter, promoFilter, getRequestHeaders]);

    const preFilteredRecords = useMemo(() => {
        if (!Array.isArray(records)) {
            return [];
        }

        const filtered = records.filter((r: EvaluationRecord) => {
            const matchesText =
                r.nom.toLowerCase().includes(filter.toLowerCase()) ||
                r.prenom.toLowerCase().includes(filter.toLowerCase()) ||
                `${r.nom} ${r.prenom}`.toLowerCase().includes(filter.toLowerCase()) ||
                r.formation.toLowerCase().includes(filter.toLowerCase()) ||
                (r.nomDip && r.nomDip.toLowerCase().includes(filter.toLowerCase())) ||
                (r.commentaireRRE && r.commentaireRRE.toLowerCase().includes(filter.toLowerCase())) ||
                (r.commentaireFormateur && r.commentaireFormateur.toLowerCase().includes(filter.toLowerCase()));

            const matchesCampus = campusFilter === 'tous' || r.campusPromo === campusFilter || r.campus === campusFilter;
            const matchesPromo = promoFilter === 'tous' || r.nomDip === promoFilter || r.formation === promoFilter;
            const matchesStudent = studentFilter === 'tous' || r.id === studentFilter;

            return matchesText && matchesCampus && matchesPromo && matchesStudent;
        });

        return filtered;
    }, [records, filter, campusFilter, promoFilter, studentFilter]);

    const dynamicStatusCounts = useMemo(() => {
        const oui = preFilteredRecords.filter(r =>
            r.autoEvaluation === 'OUI' && r.evaluationTuteur === 'OUI'
        ).length;

        const partiel = preFilteredRecords.filter(r =>
            r.autoEvaluation === 'PARTIEL' || r.evaluationTuteur === 'PARTIEL'
        ).length;

        const non = preFilteredRecords.filter(r => {
            const autoEvalNotOui = r.autoEvaluation !== 'OUI';
            const tuteurNotOui = r.evaluationTuteur !== 'OUI';
            const hasNonOrEmpty =
                r.autoEvaluation === 'NON' || !r.autoEvaluation ||
                r.evaluationTuteur === 'NON' || !r.evaluationTuteur;

            return autoEvalNotOui && tuteurNotOui && hasNonOrEmpty &&
                r.autoEvaluation !== 'PARTIEL' && r.evaluationTuteur !== 'PARTIEL';
        }).length;

        return {
            tous: preFilteredRecords.length,
            OUI: oui,
            PARTIEL: partiel,
            NON: non
        };
    }, [preFilteredRecords]);

    const filteredRecords = useMemo(() => {
        let filtered = preFilteredRecords.filter((r: EvaluationRecord) => {
            if (statusFilter === 'tous') return true;

            if (statusFilter === 'OUI') {
                return r.autoEvaluation === 'OUI' && r.evaluationTuteur === 'OUI';
            }

            if (statusFilter === 'PARTIEL') {
                return r.autoEvaluation === 'PARTIEL' || r.evaluationTuteur === 'PARTIEL';
            }

            if (statusFilter === 'NON') {
                const autoEvalNotOui = r.autoEvaluation !== 'OUI';
                const tuteurNotOui = r.evaluationTuteur !== 'OUI';
                const hasNonOrEmpty =
                    r.autoEvaluation === 'NON' || !r.autoEvaluation ||
                    r.evaluationTuteur === 'NON' || !r.evaluationTuteur;

                return autoEvalNotOui && tuteurNotOui && hasNonOrEmpty;
            }

            return true;
        });

        filtered.sort((a, b) => {
            let comparison = 0;

            switch (sortColumn) {
                case 'nom':
                    const fullNameA = `${a.nom} ${a.prenom}`.toLowerCase();
                    const fullNameB = `${b.nom} ${b.prenom}`.toLowerCase();
                    comparison = fullNameA.localeCompare(fullNameB);
                    break;
                case 'campus':
                    comparison = (a.campusPromo || a.campus || '').localeCompare(b.campusPromo || b.campus || '');
                    break;
                case 'promo':
                    comparison = (a.nomDip || a.formation || '').localeCompare(b.nomDip || b.formation || '');
                    break;
                case 'formation':
                    comparison = (a.formation || '').localeCompare(b.formation || '');
                    break;
                case 'date':
                    comparison = (a.lastUpdate || '').localeCompare(b.lastUpdate || '');
                    break;
                case 'autoEval':
                    const autoEvalOrder: { [key: string]: number } = { 'OUI': 1, 'PARTIEL': 2, 'NON': 3 };
                    comparison = (autoEvalOrder[a.autoEvaluation] || 999) - (autoEvalOrder[b.autoEvaluation] || 999);
                    break;
                case 'tuteurEval':
                    const tuteurEvalOrder: { [key: string]: number } = { 'OUI': 1, 'PARTIEL': 2, 'NON': 3 };
                    comparison = (tuteurEvalOrder[a.evaluationTuteur] || 999) - (tuteurEvalOrder[b.evaluationTuteur] || 999);
                    break;
                case 'dateAction':
                    comparison = (a.dateAction || '').localeCompare(b.dateAction || '');
                    break;
                case 'dateActionRRE':
                    comparison = ((a as any).dateActionRRE || '').localeCompare((b as any).dateActionRRE || '');
                    break;
                case 'commentaireFormateur':
                    comparison = (a.commentaireFormateur ? 1 : 0) - (b.commentaireFormateur ? 1 : 0);
                    break;
                case 'commentaireRRE':
                    comparison = (a.commentaireRRE ? 1 : 0) - (b.commentaireRRE ? 1 : 0);
                    break;
                default:
                    comparison = 0;
            }

            return sortDirection === 'asc' ? comparison : -comparison;
        });

        return filtered;
    }, [preFilteredRecords, statusFilter, sortColumn, sortDirection]);

    const handleSort = (column: SortColumn) => {
        if (sortColumn === column) {
            setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
        } else {
            setSortColumn(column);
            setSortDirection('asc');
        }
    };

    const handleViewHistory = async (record: EvaluationRecord) => {
        setSelectedRecord(record);
        setEditAutoEval(record.autoEvaluation || 'NON');
        setEditTuteurEval(record.evaluationTuteur || 'NON');
        setEditCommentaire('');

        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const todayLocal = `${year}-${month}-${day}`;

        setEditDateAction(todayLocal);
        setEditDateActionRRE(todayLocal);
        setEditDateEvalTuteur(todayLocal);

        setEditCommentaireFormateur('');
        setEditCommentaireRRE('');

        try {
            const historyRes = await fetch(`/api/history/${record.id}`);
            if (historyRes.ok) {
                const historyData = await historyRes.json();
                const transformedHistory = transformHistoryData(historyData);

                const recordWithHistory: EvaluationRecord = {
                    ...record,
                    history: transformedHistory
                };

                setSelectedRecord(recordWithHistory);
                setRecords(prev =>
                    prev.map(r => r.id === record.id ? recordWithHistory : r)
                );
            }
        } catch (error) {
            console.error('❌ Erreur chargement historique:', error);
        }

        setIsDetailModalOpen(true);
    };

    const handleAddAction = async () => {
        if (!selectedRecord) return;

        setIsSaving(true);
        try {
            const updates: any = {};
            let hasChanges = false;

            const effectiveRole = impersonatedUser?.role || user.role;
            const canEditFormateur = effectiveRole === 'formateur' || user.role === 'super';
            const canEditRRE = effectiveRole === 'rre' || user.role === 'super';

            if (canEditFormateur) {
                updates.autoEvaluation = editAutoEval;
                updates.evaluationTuteur = editTuteurEval;
                hasChanges = true;

                if (editDateAction) {
                    updates.dateAction = editDateAction;
                }

                if (editCommentaireFormateur.trim()) {
                    updates.commentaireFormateur = editCommentaireFormateur;
                }

                if (editDateEvalTuteur) {
                    updates.dateEvalTuteur = editDateEvalTuteur;
                }

                if (editCommentaire.trim()) {
                    updates.commentaire = editCommentaire;
                }
            }

            if (canEditRRE) {
                if (editDateActionRRE) {
                    updates.dateActionRRE = editDateActionRRE;
                    hasChanges = true;
                }

                if (editCommentaireRRE.trim()) {
                    updates.commentaireRRE = editCommentaireRRE;
                    hasChanges = true;
                }
            }

            if (!hasChanges) {
                alert('⚠️ Aucune action à enregistrer');
                setIsSaving(false);
                return;
            }

            const response = await fetch(`/api/evaluations/${selectedRecord.id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    ...getRequestHeaders()
                },
                body: JSON.stringify({
                    updates,
                    author: {
                        email: impersonatedUser?.email || user.email,
                        name: impersonatedUser?.nomComplet || user.nomComplet,
                        role: impersonatedUser?.role || user.role,
                        campus: impersonatedUser?.campus || user.campus
                    }
                })
            });

            if (response.ok) {
                await loadData();

                const historyRes = await fetch(`/api/history/${selectedRecord.id}`);
                if (historyRes.ok) {
                    const historyData = await historyRes.json();
                    const transformedHistory = transformHistoryData(historyData);

                    const updatedRecord = records.find(r => r.id === selectedRecord.id);
                    if (updatedRecord) {
                        const recordWithUpdatedHistory = {
                            ...updatedRecord,
                            history: transformedHistory
                        };

                        setSelectedRecord(recordWithUpdatedHistory);
                    }
                }

                const today = new Date();
                const year = today.getFullYear();
                const month = String(today.getMonth() + 1).padStart(2, '0');
                const day = String(today.getDate()).padStart(2, '0');
                const todayLocal = `${year}-${month}-${day}`;

                setEditCommentaire('');
                setEditDateAction(todayLocal);
                setEditDateActionRRE(todayLocal);
                setEditCommentaireFormateur('');
                setEditDateEvalTuteur(todayLocal);
                setEditCommentaireRRE('');
            } else {
                const errorData = await response.json();
                alert('❌ Erreur lors de l\'enregistrement: ' + (errorData.error || 'Erreur inconnue'));
            }
        } catch (error) {
            alert('❌ Erreur lors de l\'enregistrement');
        } finally {
            setIsSaving(false);
        }
    };

    const generatePdfForRecord = (record: EvaluationRecord) => {
        const doc = new jsPDF();

        doc.setFont('helvetica', 'bold');
        doc.setFontSize(18);
        doc.text('Dossier d\'évaluation', 105, 20, { align: 'center' });

        doc.setFontSize(12);
        doc.setFont('helvetica', 'normal');
        let y = 40;

        doc.text(`Apprenant: ${sanitizeTextForPDF(record.prenom)} ${sanitizeTextForPDF(record.nom)}`, 20, y);
        y += 8;
        doc.text(`ID: ${sanitizeTextForPDF(record.id)}`, 20, y);
        y += 8;
        doc.text(`Formation: ${sanitizeTextForPDF(record.formation)}`, 20, y);
        y += 8;
        doc.text(`Campus: ${sanitizeTextForPDF(record.campusPromo || record.campus)}`, 20, y);
        y += 8;
        doc.text(`Promotion: ${sanitizeTextForPDF(record.nomDip)}`, 20, y);
        y += 15;

        doc.setLineWidth(0.5);
        doc.line(20, y, 190, y);
        y += 10;

        doc.setFont('helvetica', 'bold');
        doc.setFontSize(14);
        doc.text('Statut actuel', 20, y);
        y += 10;

        doc.setFont('helvetica', 'normal');
        doc.setFontSize(11);
        doc.text(`Auto-évaluation: ${sanitizeTextForPDF(record.autoEvaluation)}`, 20, y);
        y += 7;
        doc.text(`Évaluation tuteur: ${sanitizeTextForPDF(record.evaluationTuteur)}`, 20, y);
        y += 7;

        // ✅ DATES PDF CORRIGÉES
        if (record.dateAction) {
            doc.text(`Date action formateur: ${formatDateParis(record.dateAction)}`, 20, y);
            y += 7;
        }

        if (record.dateActionRRE) {
            doc.text(`Date action RRE: ${formatDateParis(record.dateActionRRE)}`, 20, y);
            y += 7;
        }

        y += 8;

        if (record.commentaireFormateur) {
            doc.setFont('helvetica', 'bold');
            doc.text('Commentaire Formateur:', 20, y);
            y += 7;
            doc.setFont('helvetica', 'normal');
            const formateurLines = doc.splitTextToSize(sanitizeTextForPDF(record.commentaireFormateur), 170);
            doc.text(formateurLines, 20, y);
            y += formateurLines.length * 7 + 5;
        }

        if (record.commentaireRRE) {
            if (y > 250) {
                doc.addPage();
                y = 20;
            }
            doc.setFont('helvetica', 'bold');
            doc.text('Commentaire RRE:', 20, y);
            y += 7;
            doc.setFont('helvetica', 'normal');
            const rreLines = doc.splitTextToSize(sanitizeTextForPDF(record.commentaireRRE), 170);
            doc.text(rreLines, 20, y);
            y += rreLines.length * 7 + 5;
        }

        if (record.commentaire) {
            if (y > 250) {
                doc.addPage();
                y = 20;
            }
            doc.setFont('helvetica', 'bold');
            doc.text('Commentaire général:', 20, y);
            y += 7;
            doc.setFont('helvetica', 'normal');
            const generalLines = doc.splitTextToSize(sanitizeTextForPDF(record.commentaire), 170);
            doc.text(generalLines, 20, y);
            y += generalLines.length * 7 + 10;
        }

        if (record.history && record.history.length > 0) {
            if (y > 220) {
                doc.addPage();
                y = 20;
            }

            doc.setLineWidth(0.5);
            doc.line(20, y, 190, y);
            y += 10;

            doc.setFont('helvetica', 'bold');
            doc.setFontSize(14);
            doc.text('Historique des actions', 20, y);
            y += 10;

            doc.setFont('helvetica', 'normal');
            doc.setFontSize(10);

            record.history.forEach((entry, index) => {
                if (y > 270) {
                    doc.addPage();
                    y = 20;
                }

                // ✅ HISTORIQUE PDF CORRIGÉ
                const date = formatDateTimeParis(entry.timestamp);

                doc.setFont('helvetica', 'bold');
                doc.text(`${index + 1}. ${date} - ${sanitizeTextForPDF(entry.userName)} (${entry.userRole.toUpperCase()})`, 20, y);
                y += 6;

                doc.setFont('helvetica', 'normal');
                doc.text(`Action: ${sanitizeTextForPDF(entry.reason)}`, 25, y);
                y += 6;

                if (entry.changes && entry.changes.length > 0) {
                    entry.changes.forEach(change => {
                        if (y > 275) {
                            doc.addPage();
                            y = 20;
                        }
                        doc.text(`${sanitizeTextForPDF(change.fieldLabel)}: "${sanitizeTextForPDF(change.oldValue)}" → "${sanitizeTextForPDF(change.newValue)}"`, 30, y);
                        y += 5;
                    });
                }

                y += 4;
            });
        }

        const pageCount = doc.getNumberOfPages();
        for (let i = 1; i <= pageCount; i++) {
            doc.setPage(i);
            doc.setFontSize(9);
            doc.setFont('helvetica', 'normal');
            doc.text(
                `Généré le ${new Date().toLocaleDateString('fr-FR')} à ${new Date().toLocaleTimeString('fr-FR')} - Page ${i}/${pageCount}`,
                105,
                285,
                { align: 'center' }
            );
        }

        const fileName = `evaluation_${sanitizeTextForPDF(record.nom)}_${sanitizeTextForPDF(record.prenom)}_${new Date().toISOString().split('T')[0]}.pdf`;
        doc.save(fileName);
    };

    const handleExportPDF = async (record: EvaluationRecord) => {
        if (!record.history || record.history.length === 0) {
            try {
                const historyRes = await fetch(`/api/history/${record.id}`);
                if (historyRes.ok) {
                    const historyData = await historyRes.json();
                    const transformedHistory = transformHistoryData(historyData);
                    const recordWithHistory: EvaluationRecord = {
                        ...record,
                        history: transformedHistory
                    };
                    setRecords(prev =>
                        prev.map(r => r.id === record.id ? recordWithHistory : r)
                    );
                    setSelectedRecord(prev =>
                        prev && prev.id === record.id ? recordWithHistory : prev
                    );
                    generatePdfForRecord(recordWithHistory);
                    return;
                }
            } catch (error) {
                console.error('❌ Erreur chargement historique avant export PDF:', error);
            }
        }
        generatePdfForRecord(record);
    };

    const handleResetFilters = () => {
        setFilter('');
        setStatusFilter('tous');
        const effectiveRole = impersonatedUser?.role || user.role;
        if (effectiveRole === 'formateur') {
            setCampusFilter('tous');
        }
        setPromoFilter('tous');
        setStudentFilter('tous');
    };

    const SortIcon = ({ column }: { column: SortColumn }) => {
        if (sortColumn !== column) return <span className="sort-icon">⇅</span>;
        return <span className="sort-icon active">{sortDirection === 'asc' ? '↑' : '↓'}</span>;
    };

    const truncateText = (text: string | undefined | null, maxLength: number = 50): string => {
        if (!text) return '-';
        if (text.length <= maxLength) return text;
        return text.substring(0, maxLength) + '...';
    };


    const effectiveCampus = impersonatedUser?.campus || user.campus;
    const displayName = impersonatedUser ? `${user.nomComplet} → ${impersonatedUser.nomComplet}` : user.nomComplet;

    return (
        <div className="page-container">
            <nav className="navbar">
                <div className="nav-left">
                    <div className="nav-logo">📊</div>
                    <div className="nav-info">
                        <span className="nav-title">Suivi Évaluations</span>
                        <span className="nav-subtitle">
                            {user.role === 'super' && <span className="role-badge role-badge-super">🔐 SUPER{impersonatedUser && ' [USURPÉ]'}</span>}
                            {user.role === 'rre' && <span className="role-badge">RRE{impersonatedUser && ' [USURPÉ]'}</span>}
                            {user.role === 'formateur' && <span className="role-badge">FORMATEUR{impersonatedUser && ' [USURPÉ]'}</span>}
                            {user.role === 'lecteur' && <span className="role-badge role-badge-lecteur">👁️ LECTEUR</span>}
                            {effectiveCampus && effectiveCampus}
                        </span>
                    </div>
                </div>
                <div className="nav-right">
                    <span className="user-name">{displayName}</span>
                    <button onClick={onLogout} className="logout-button">
                        <span>🚪</span> Déconnexion
                    </button>
                </div>
            </nav>

            <main className="main-content">
                <div className="content-header">
                    <h1>📋 Historique</h1>
                </div>

                <div className="search-section">
                    <div className="search-wrapper">
                        <span className="search-icon">🔍</span>
                        <input
                            type="text"
                            placeholder="Rechercher..."
                            value={filter}
                            onChange={(e) => setFilter(e.target.value)}
                            className="search-input"
                        />
                        {filter && (
                            <button className="search-clear" onClick={() => setFilter('')} title="Effacer">
                                ×
                            </button>
                        )}
                    </div>
                </div>

                <div className="filters-container">
                    <div className="filters-grid">
                        <div className="filter-group">
                            <label className="filter-label">
                                <span className="filter-icon">🏫</span> Campus
                            </label>
                            <select
                                value={campusFilter}
                                onChange={(e) => {
                                    setCampusFilter(e.target.value);
                                    setPromoFilter('tous');
                                    setStudentFilter('tous');
                                }}
                                className="filter-select"
                                disabled={
                                    (effectiveRole === 'rre' && user.role !== 'super') ||
                                    (user.role === 'super' && !impersonatedUser)  // ✅ AJOUT : désactiver pour super sans usurpation
                                }
                            >
                                {campusList.map(campus => (
                                    <option key={campus} value={campus}>{campus}</option>
                                ))}
                            </select>

                        </div>
                        <div className="filter-group">
                            <label className="filter-label">
                                <span className="filter-icon">🎓</span> Promotion
                            </label>
                            <select
                                value={promoFilter}
                                onChange={(e) => {
                                    setPromoFilter(e.target.value);
                                    setStudentFilter('tous');
                                }}
                                className="filter-select"
                                disabled={campusFilter === 'tous'}
                            >
                                {promoList.map(promo => (
                                    <option key={promo} value={promo}>{promo}</option>
                                ))}
                            </select>
                        </div>

                        <div className="filter-group">
                            <label className="filter-label">
                                <span className="filter-icon">👤</span> Étudiant
                            </label>
                            <select
                                value={studentFilter}
                                onChange={(e) => setStudentFilter(e.target.value)}
                                className="filter-select"
                                disabled={campusFilter === 'tous'}
                            >
                                {campusFilter === 'tous' ? (
                                    <option value="tous">Sélectionnez un campus d'abord</option>
                                ) : studentsList.length === 0 ? (
                                    <option value="tous">Aucun étudiant trouvé</option>
                                ) : (
                                    <>
                                        <option value="tous">Tous ({studentsList.length})</option>
                                        {studentsList.map(student => (
                                            <option key={student.id} value={student.id}>{student.name}</option>
                                        ))}
                                    </>
                                )}
                            </select>
                        </div>

                        <div className="filter-group">
                            <label className="filter-label">
                                <span className="filter-icon">📊</span> Statut
                            </label>
                            <select
                                value={statusFilter}
                                onChange={(e) => setStatusFilter(e.target.value as StatusFilter)}
                                className="filter-select"
                            >
                                <option value="tous">📊 Tous ({dynamicStatusCounts.tous})</option>
                                <option value="OUI">✅ OUI ({dynamicStatusCounts.OUI})</option>
                                <option value="PARTIEL">⚠️ PARTIEL ({dynamicStatusCounts.PARTIEL})</option>
                                <option value="NON">❌ NON ({dynamicStatusCounts.NON})</option>
                            </select>
                        </div>
                    </div>

                    {(filter || statusFilter !== 'tous' || (effectiveRole === 'formateur' && campusFilter !== 'tous') || promoFilter !== 'tous' || studentFilter !== 'tous') && (
                        <button onClick={handleResetFilters} className="reset-filters-button">
                            Réinitialiser les filtres
                        </button>
                    )}
                </div>

                <div className="table-container">
                    {isLoading ? (
                        <div className="loading-state">
                            <div className="spinner"></div>
                            <p>Chargement des données...</p>
                        </div>
                    ) : (
                        <table className="data-table">
                            <thead>
                                <tr>
                                    <th onClick={() => handleSort('nom')} className="sortable">
                                        Apprenant <SortIcon column="nom" />
                                    </th>
                                    <th onClick={() => handleSort('promo')} className="sortable">
                                        Promotion <SortIcon column="promo" />
                                    </th>
                                    <th onClick={() => handleSort('autoEval')} className="sortable">
                                        Auto-éval. <SortIcon column="autoEval" />
                                    </th>
                                    <th onClick={() => handleSort('tuteurEval')} className="sortable">
                                        Tuteur <SortIcon column="tuteurEval" />
                                    </th>
                                    <th onClick={() => handleSort('dateAction')} className="sortable text-center">
                                        Date Action Formateur <SortIcon column="dateAction" />
                                    </th>
                                    <th onClick={() => handleSort('dateActionRRE')} className="sortable text-center">
                                        Date Action RRE <SortIcon column="dateActionRRE" />
                                    </th>
                                    <th onClick={() => handleSort('commentaireFormateur')} className="sortable">
                                        Commentaire Formateur <SortIcon column="commentaireFormateur" />
                                    </th>
                                    <th onClick={() => handleSort('commentaireRRE')} className="sortable">
                                        Commentaire RRE <SortIcon column="commentaireRRE" />
                                    </th>
                                    <th className="text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {filteredRecords.length === 0 ? (
                                    <tr>
                                        <td colSpan={9} className="empty-state">
                                            <div className="empty-icon">📭</div>
                                            <p>Aucun enregistrement trouvé</p>
                                            <small>Essayez de modifier vos critères de recherche</small>
                                        </td>
                                    </tr>
                                ) : (
                                    filteredRecords.map((record: any) => (
                                        <tr key={record.id} className="table-row">
                                            <td className="student-cell">
                                                <div className="student-info">
                                                    <strong className="student-name">{record.nom} {record.prenom}</strong>
                                                    <small className="student-id">ID: {record.id}</small>
                                                </div>
                                            </td>
                                            <td>
                                                <span className="promo-text">{record.nomDip || '-'}</span>
                                            </td>
                                            <td>
                                                <span className={`status-badge ${record.autoEvaluation === 'OUI' ? 'status-success' : record.autoEvaluation === 'PARTIEL' ? 'status-progress' : 'status-pending'}`}>
                                                    {record.autoEvaluation}
                                                </span>
                                            </td>
                                            <td>
                                                <span className={`status-badge ${record.evaluationTuteur === 'OUI' ? 'status-success' : record.evaluationTuteur === 'PARTIEL' ? 'status-progress' : 'status-pending'}`}>
                                                    {record.evaluationTuteur}
                                                </span>
                                            </td>
                                            <td className="text-center date-cell">
                                                {record.dateAction ? (
                                                    <span className="date-text">
                                                        {formatDateParis(record.dateAction)}
                                                    </span>
                                                ) : (
                                                    <span className="no-date">-</span>
                                                )}
                                            </td>
                                            <td className="text-center date-cell">
                                                {/* ✅ CORRECTION LIGNE 1089 */}
                                                {record.dateActionRRE ? (
                                                    <span className="date-text">
                                                        {formatDateParis(record.dateActionRRE)}
                                                    </span>
                                                ) : (
                                                    <span className="no-date">-</span>
                                                )}
                                            </td>
                                            <td className="commentaire-formateur-cell">
                                                {record.commentaireFormateur ? (
                                                    <div className="commentaire-content" title={record.commentaireFormateur}>
                                                        <span className="commentaire-icon">💬</span>
                                                        <span className="commentaire-text">{truncateText(record.commentaireFormateur, 40)}</span>
                                                    </div>
                                                ) : (
                                                    <span className="no-comment">-</span>
                                                )}
                                            </td>
                                            <td className="commentaire-rre-cell">
                                                {record.commentaireRRE ? (
                                                    <div className="commentaire-rre-content" title={record.commentaireRRE}>
                                                        <span className="commentaire-icon">📝</span>
                                                        <span className="commentaire-text">{truncateText(record.commentaireRRE, 40)}</span>
                                                    </div>
                                                ) : (
                                                    <span className="no-comment">-</span>
                                                )}
                                            </td>
                                            <td className="actions-cell">
                                                <div className="action-buttons">
                                                    <button
                                                        onClick={() => handleViewHistory(record)}
                                                        className="action-btn action-view"
                                                        title="Voir l'historique"
                                                    >
                                                        👁️
                                                    </button>
                                                    <button
                                                        onClick={() => handleExportPDF(record)}
                                                        className="action-btn action-export"
                                                        title="Exporter en PDF"
                                                    >
                                                        📄
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    ))
                                )}
                            </tbody>
                        </table>
                    )}
                </div>
            </main>

            {isDetailModalOpen && selectedRecord && createPortal(
                <div
                    style={{
                        position: 'fixed',
                        top: 0,
                        left: 0,
                        right: 0,
                        bottom: 0,
                        background: 'rgba(0, 0, 0, 0.65)',
                        backdropFilter: 'blur(8px)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        zIndex: 1000,
                        padding: '1rem'
                    }}
                    onClick={() => setIsDetailModalOpen(false)}
                >
                    <div
                        style={{
                            background: 'white',
                            borderRadius: '20px',
                            width: '95%',
                            maxWidth: '1600px',
                            maxHeight: '90vh',
                            display: 'flex',
                            flexDirection: 'column',
                            boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.3)',
                            overflow: 'hidden'
                        }}
                        onClick={(e) => e.stopPropagation()}
                    >
                        <div className="modal-header">
                            <h2>
                                📝 Détails de l'évaluation
                                {user.role === 'super' && impersonatedUser && ' 🎭 [MODE USURPATION]'}
                                {user.role === 'super' && !impersonatedUser && ' 🔐 [MODE SUPER]'}
                            </h2>
                            <button className="modal-close" onClick={() => setIsDetailModalOpen(false)}>×</button>
                        </div>

                        <div className="modal-student-info">
                            <div className="info-row">
                                <span className="info-label">APPRENANT:</span>
                                <span className="info-value">{selectedRecord.nom} {selectedRecord.prenom}</span>
                            </div>
                            <div className="info-row">
                                <span className="info-label">FORMATION:</span>
                                <span className="info-value">{selectedRecord.formation}</span>
                            </div>
                            <div className="info-row">
                                <span className="info-label">CAMPUS:</span>
                                <span className="info-value">{selectedRecord.campusPromo || selectedRecord.campus}</span>
                            </div>
                        </div>

                        {/* 🔒 Bandeau lecteur en mode lecture seule */}
                        {!canModify && (
                            <div style={{
                                padding: '1rem 1.5rem',
                                background: '#fef3c7',
                                borderBottom: '2px solid #f59e0b',
                                display: 'flex',
                                alignItems: 'center',
                                gap: '0.75rem'
                            }}>
                                <span style={{ fontSize: '1.5rem' }}>🔒</span>
                                <div>
                                    <p style={{ color: '#92400e', fontWeight: 600, marginBottom: '0.25rem' }}>
                                        Mode Lecture Seule
                                    </p>
                                    <p style={{ color: '#78350f', fontSize: '0.85rem' }}>
                                        Vous consultez ce dossier en lecture seule. Les modifications ne sont pas autorisées.
                                    </p>
                                </div>
                            </div>
                        )}

                        <div
                            style={{
                                flex: 1,
                                overflow: 'hidden',
                                display: 'flex',
                                flexDirection: 'column',
                                minHeight: 0
                            }}
                        >
                            {/* SECTION NOUVELLE SAISIE EN HAUT */}
                            {canModify ? (
                                <div
                                    style={{
                                        padding: '1.5rem',
                                        background: '#f8fafc',
                                        borderBottom: '2px solid #e2e8f0',
                                        maxHeight: '45%',
                                        overflowY: 'auto'
                                    }}
                                >
                                    <h3 className="column-section-title">
                                        <span>✏️</span>
                                        Nouvelle saisie
                                        {user.role === 'super' && impersonatedUser && (
                                            <span style={{ color: '#f59e0b', fontSize: '0.85rem' }}>🎭 Mode Usurpation: {impersonatedUser.nomComplet}</span>
                                        )}
                                        {user.role === 'super' && !impersonatedUser && (
                                            <span style={{ color: '#f59e0b', fontSize: '0.85rem' }}>🔐 Mode SUPER</span>
                                        )}
                                    </h3>



                                    <form className="action-form">
                                        {/* SECTION FORMATEUR */}
                                        {(effectiveRole === 'formateur' || user.role === 'super') && (
                                            <>
                                                <div style={{
                                                    background: '#e0f2fe',
                                                    padding: '0.75rem',
                                                    borderRadius: '8px',
                                                    marginBottom: '1rem',
                                                    borderLeft: '4px solid #0ea5e9'
                                                }}>
                                                    <h4 style={{ fontSize: '0.9rem', fontWeight: 700, color: '#0369a1', marginBottom: '0.5rem' }}>
                                                        📝 Section Formateur
                                                    </h4>
                                                </div>

                                                <div className="form-grid-2col">
                                                    <div className="form-group">
                                                        <label className="form-label">
                                                            <span className="label-icon">✅</span> Auto-évaluation
                                                        </label>
                                                        <select
                                                            value={editAutoEval}
                                                            onChange={(e) => setEditAutoEval(e.target.value)}
                                                            className="form-select"
                                                            disabled={!canModify}
                                                        >
                                                            <option value="NON">NON</option>
                                                            <option value="PARTIEL">PARTIEL</option>
                                                            <option value="OUI">OUI</option>
                                                        </select>
                                                    </div>

                                                    <div className="form-group">
                                                        <label className="form-label">
                                                            <span className="label-icon">✅</span> Evaluation Tuteur
                                                        </label>
                                                        <select
                                                            value={editTuteurEval}
                                                            onChange={(e) => setEditTuteurEval(e.target.value)}
                                                            className="form-select"
                                                            disabled={!canModify}
                                                        >
                                                            <option value="NON">NON</option>
                                                            <option value="PARTIEL">PARTIEL</option>
                                                            <option value="OUI">OUI</option>
                                                        </select>
                                                    </div>

                                                    {/* Date Action Formateur et Commentaire Formateur côte à côte */}
                                                    <div className="form-group">
                                                        <label className="form-label">
                                                            <span className="label-icon">📅</span> Date Action Formateur
                                                        </label>
                                                        <input
                                                            type="date"
                                                            value={editDateAction}
                                                            onChange={(e) => setEditDateAction(e.target.value)}
                                                            className="form-input"
                                                            disabled={!canModify}
                                                        />
                                                    </div>

                                                    <div className="form-group">
                                                        <label className="form-label">
                                                            <span className="label-icon">💬</span> Commentaire Formateur
                                                        </label>
                                                        <textarea
                                                            value={editCommentaireFormateur}
                                                            onChange={(e) => setEditCommentaireFormateur(e.target.value)}
                                                            className="form-textarea"
                                                            rows={2}
                                                            placeholder="Ajoutez votre commentaire..."
                                                            disabled={!canModify}
                                                        />
                                                    </div>
                                                </div>
                                            </>
                                        )}

                                        {/* SÉPARATEUR pour super */}
                                        {user.role === 'super' && (
                                            <div style={{
                                                height: '2px',
                                                background: 'linear-gradient(90deg, transparent, #f59e0b, transparent)',
                                                margin: '1rem 0',
                                                position: 'relative'
                                            }}>
                                                <span style={{
                                                    position: 'absolute',
                                                    top: '50%',
                                                    left: '50%',
                                                    transform: 'translate(-50%, -50%)',
                                                    background: '#fff',
                                                    padding: '0.25rem 0.75rem',
                                                    fontSize: '0.75rem',
                                                    fontWeight: 700,
                                                    color: '#f59e0b',
                                                    borderRadius: '12px',
                                                    border: '2px solid #f59e0b'
                                                }}>
                                                    {impersonatedUser ? '🎭 USURPATION ACTIVE' : '🔐 MODE SUPER'}
                                                </span>
                                            </div>
                                        )}

                                        {/* SECTION RRE */}
                                        {(effectiveRole === 'rre' || user.role === 'super') && (
                                            <>
                                                <div style={{
                                                    background: '#fef3c7',
                                                    padding: '0.75rem',
                                                    borderRadius: '8px',
                                                    marginBottom: '1rem',
                                                    borderLeft: '4px solid #f59e0b'
                                                }}>
                                                    <h4 style={{ fontSize: '0.9rem', fontWeight: 700, color: '#92400e', marginBottom: '0.5rem' }}>
                                                        📋 Section RRE
                                                    </h4>
                                                </div>

                                                {selectedRecord.commentaireFormateur && effectiveRole === 'rre' && (
                                                    <div className="rre-readonly-info">
                                                        <h4>📋 État actuel Formateur</h4>
                                                        {selectedRecord.dateAction && (
                                                            <p><strong>Date Action:</strong> {new Date(selectedRecord.dateAction).toLocaleDateString('fr-FR')}</p>
                                                        )}
                                                        <p><strong>Commentaire:</strong> {selectedRecord.commentaireFormateur}</p>
                                                    </div>
                                                )}

                                                <div className="form-grid-2col">
                                                    {/* Date Action RRE et Commentaire RRE côte à côte */}
                                                    <div className="form-group">
                                                        <label className="form-label">
                                                            <span className="label-icon">📅</span> Date Action RRE
                                                        </label>
                                                        <input
                                                            type="date"
                                                            value={editDateActionRRE}
                                                            onChange={(e) => setEditDateActionRRE(e.target.value)}
                                                            className="form-input"
                                                            disabled={!canModify}
                                                        />
                                                    </div>

                                                    <div className="form-group">
                                                        <label className="form-label">
                                                            <span className="label-icon">💬</span> Commentaire RRE
                                                            {user.role !== 'super' && <span className="required-star">*</span>}
                                                        </label>
                                                        <textarea
                                                            value={editCommentaireRRE}
                                                            onChange={(e) => setEditCommentaireRRE(e.target.value)}
                                                            className="form-textarea form-textarea-highlight"
                                                            rows={2}
                                                            placeholder="Commentaire RRE..."
                                                            disabled={!canModify}
                                                        />
                                                    </div>
                                                </div>
                                            </>
                                        )}
                                    </form>
                                </div>
                            ) : (
                                <div
                                    style={{
                                        padding: '1.5rem',
                                        background: '#f8fafc',
                                        borderBottom: '2px solid #e2e8f0',
                                        textAlign: 'center'
                                    }}
                                >
                                    <h3 className="column-section-title" style={{ justifyContent: 'center' }}>
                                        <span>👁️</span>
                                        Mode Lecture Seule
                                    </h3>
                                    <div style={{
                                        background: '#fef3c7',
                                        padding: '1.5rem',
                                        borderRadius: '12px',
                                        borderLeft: '4px solid #f59e0b',
                                        marginTop: '1rem'
                                    }}>
                                        <p style={{ color: '#92400e', fontWeight: 600, marginBottom: '0.5rem', fontSize: '1rem' }}>
                                            ℹ️ Accès en lecture seule
                                        </p>
                                        <p style={{ color: '#78350f', fontSize: '0.9rem', lineHeight: '1.5' }}>
                                            Vous pouvez consulter les évaluations et exporter les données,
                                            mais vous ne pouvez pas effectuer de modifications.
                                        </p>
                                    </div>
                                </div>
                            )}

                            {/* SECTION HISTORIQUE EN BAS - TABLEAU */}
                            {/* SECTION HISTORIQUE EN BAS - TABLEAU */}
                            <div
                                style={{
                                    flex: 1,
                                    padding: '1.5rem',
                                    overflowY: 'auto',
                                    overflowX: 'auto',
                                    background: 'white',
                                    display: 'flex',
                                    flexDirection: 'column',
                                    minHeight: '300px'  // ✅ Hauteur minimale
                                }}
                            >
                                <h3 className="column-section-title" style={{ marginBottom: '1rem', flexShrink: 0 }}>
                                    <span>📜</span>
                                    Historique
                                    {selectedRecord.history && selectedRecord.history.length > 0 && (
                                        <span className="history-badge">{selectedRecord.history.length}</span>
                                    )}
                                </h3>

                                {selectedRecord.history && selectedRecord.history.length > 0 ? (
                                    <div
                                        className="table-container"
                                        style={{
                                            flex: 1,
                                            borderRadius: '12px',
                                            overflowY: 'auto',  // ✅ Scroll vertical
                                            overflowX: 'auto',  // ✅ Scroll horizontal
                                            maxHeight: '400px', // ✅ Hauteur max pour forcer le scroll
                                            minHeight: '200px'
                                        }}
                                    >
                                        <table className="data-table">
                                            <thead>
                                                <tr>
                                                    <th style={{ minWidth: '120px', position: 'sticky', top: 0, zIndex: 10 }}>Date</th>
                                                    <th style={{ minWidth: '100px', textAlign: 'center', position: 'sticky', top: 0, zIndex: 10 }}>Auto-éval</th>
                                                    <th style={{ minWidth: '100px', textAlign: 'center', position: 'sticky', top: 0, zIndex: 10 }}>Éval. Tuteur</th>
                                                    <th style={{ minWidth: '140px', textAlign: 'center', position: 'sticky', top: 0, zIndex: 10 }}>Date Action Formateur</th>
                                                    <th style={{ minWidth: '140px', textAlign: 'center', position: 'sticky', top: 0, zIndex: 10 }}>Date Action RRE</th>
                                                    <th style={{ minWidth: '220px', position: 'sticky', top: 0, zIndex: 10 }}>Commentaire Formateur</th>
                                                    <th style={{ minWidth: '220px', position: 'sticky', top: 0, zIndex: 10 }}>Commentaire RRE</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {selectedRecord.history.map((entry: any, index: number) => {
                                                    const autoEvalChange = entry.changes?.find((c: any) => c.field === 'autoEvaluation');
                                                    const tuteurEvalChange = entry.changes?.find((c: any) => c.field === 'evaluationTuteur');
                                                    const dateActionChange = entry.changes?.find((c: any) => c.field === 'dateAction');
                                                    const dateActionRREChange = entry.changes?.find((c: any) => c.field === 'dateActionRRE');
                                                    const commentaireFormateurChange = entry.changes?.find((c: any) => c.field === 'commentaireFormateur');
                                                    const commentaireRREChange = entry.changes?.find((c: any) => c.field === 'commentaireRRE');

                                                    return (
                                                        <tr key={entry.id || index} className="table-row">
                                                            <td>
                                                                <div style={{ fontSize: '0.8rem' }}>
                                                                    <div style={{ fontWeight: 600, color: '#1e293b' }}>
                                                                        {new Date(entry.timestamp).toLocaleDateString('fr-FR')}
                                                                    </div>

                                                                </div>
                                                            </td>
                                                            <td className="text-center">
                                                                {autoEvalChange ? (
                                                                    <span className={`status-badge ${autoEvalChange.newValue === 'OUI' ? 'status-success' : autoEvalChange.newValue === 'PARTIEL' ? 'status-progress' : 'status-pending'}`}>
                                                                        {autoEvalChange.newValue}
                                                                    </span>
                                                                ) : (
                                                                    <span style={{ color: '#94a3b8' }}>-</span>
                                                                )}
                                                            </td>
                                                            <td className="text-center">
                                                                {tuteurEvalChange ? (
                                                                    <span className={`status-badge ${tuteurEvalChange.newValue === 'OUI' ? 'status-success' : tuteurEvalChange.newValue === 'PARTIEL' ? 'status-progress' : 'status-pending'}`}>
                                                                        {tuteurEvalChange.newValue}
                                                                    </span>
                                                                ) : (
                                                                    <span style={{ color: '#94a3b8' }}>-</span>
                                                                )}
                                                            </td>
                                                            <td className="text-center">
                                                                {dateActionChange ? (
                                                                    <span className="date-text" style={{ fontSize: '0.8rem' }}>
                                                                        {dateActionChange.newValue !== '(vide)'
                                                                            ? new Date(dateActionChange.newValue).toLocaleDateString('fr-FR')
                                                                            : '-'
                                                                        }
                                                                    </span>
                                                                ) : (
                                                                    <span style={{ color: '#94a3b8' }}>-</span>
                                                                )}
                                                            </td>
                                                            <td className="text-center">
                                                                {dateActionRREChange ? (
                                                                    <span className="date-text" style={{ fontSize: '0.8rem' }}>
                                                                        {dateActionRREChange.newValue !== '(vide)'
                                                                            ? new Date(dateActionRREChange.newValue).toLocaleDateString('fr-FR')
                                                                            : '-'
                                                                        }
                                                                    </span>
                                                                ) : (
                                                                    <span style={{ color: '#94a3b8' }}>-</span>
                                                                )}
                                                            </td>
                                                            <td>
                                                                {commentaireFormateurChange ? (
                                                                    <div className="commentaire-content" title={commentaireFormateurChange.newValue}>
                                                                        <span className="commentaire-icon">💬</span>
                                                                        <span className="commentaire-text" style={{ fontSize: '0.8rem' }}>
                                                                            {truncateText(commentaireFormateurChange.newValue, 60)}
                                                                        </span>
                                                                    </div>
                                                                ) : (
                                                                    <span style={{ color: '#94a3b8', textAlign: 'center', display: 'block' }}>-</span>
                                                                )}
                                                            </td>
                                                            <td>
                                                                {commentaireRREChange ? (
                                                                    <div className="commentaire-rre-content" title={commentaireRREChange.newValue}>
                                                                        <span className="commentaire-icon">📝</span>
                                                                        <span className="commentaire-text" style={{ fontSize: '0.8rem' }}>
                                                                            {truncateText(commentaireRREChange.newValue, 60)}
                                                                        </span>
                                                                    </div>
                                                                ) : (
                                                                    <span style={{ color: '#94a3b8', textAlign: 'center', display: 'block' }}>-</span>
                                                                )}
                                                            </td>
                                                        </tr>
                                                    );
                                                })}
                                            </tbody>
                                        </table>
                                    </div>
                                ) : (
                                    <div className="no-history-message">
                                        <div className="no-history-icon">📭</div>
                                        <p>Aucun historique disponible</p>
                                    </div>
                                )}
                            </div>
                        </div>

                        <div className="modal-footer">
                            <button onClick={() => handleExportPDF(selectedRecord)} className="secondary-button">
                                📄 Exporter PDF
                            </button>
                            <button
                                onClick={handleAddAction}
                                className="btn-add-action"
                                disabled={isSaving || !canModify}
                            >
                                {isSaving ? '⏳ Enregistrement...' : !canModify ? '🔒 Lecture seule' : '✅ Ajouter l\'action'}
                            </button>
                        </div>
                    </div>
                </div>,
                document.body
            )}
        </div>
    );
};

export default HistoriquePage;