{% extends 'backoffice/base.html' %}
{% load static %}

{% block title %}Activités - {{ project.title }} - ECOLUX Dashboard{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'css/modal-responsive.css' %}">
{% endblock %}

{% block content %}
<!-- TinyMCE Editor -->
<script src="https://cdn.tiny.cloud/1/2fssx32bpsx37bdxan8ya9hcmgo4qhqf2ezoncwafvcldzq2/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>

<style>
/* Design slim et moderne */
.ecolux-card {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    border: 1px solid #f0f0f0;
    transition: all 0.2s ease;
}

.ecolux-card:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.ecolux-primary {
    background: linear-gradient(135deg, #1e1810 0%, #2a221a 100%);
}

.ecolux-secondary {
    background: linear-gradient(135deg, #e6c252 0%, #f0d670 100%);
}

.has-text-ecolux-primary {
    color: #1e1810 !important;
}

.has-text-ecolux-secondary {
    color: #e6c252 !important;
}

.is-ecolux-primary {
    background: linear-gradient(135deg, #1e1810 0%, #2a221a 100%);
    color: white;
    border: none;
}

.is-ecolux-secondary {
    background: linear-gradient(135deg, #e6c252 0%, #f0d670 100%);
    color: #1e1810;
    border: none;
}

/* En-tête compact */
.project-header {
    background: linear-gradient(135deg, #f8f6f0 0%, #f5f2e8 100%);
    border-radius: 8px;
    padding: 1rem 1.25rem;
    margin-bottom: 1rem;
    border-left: 4px solid #e6c252;
}

/* Cartes d'activité ultra-slim */
.activity-card {
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 0.875rem 1rem;
    margin-bottom: 0.75rem;
    transition: all 0.2s ease;
    background: white;
    box-shadow: 0 1px 3px rgba(0,0,0,0.04);
}

.activity-card:hover {
    border-color: #e6c252;
    box-shadow: 0 4px 12px rgba(230, 194, 82, 0.12);
}

/* Icônes compactes */
.activity-icon {
    width: 32px;
    height: 32px;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 0.875rem;
    margin-right: 0.75rem;
    flex-shrink: 0;
}

.activity-facture { background: #10b981; }
.activity-note { background: #f59e0b; }
.activity-devis { background: #3b82f6; }
.activity-justificatif { background: #8b5cf6; }
.activity-design { background: #ec4899; }
.activity-construction { background: #ef4444; }

/* Badges compacts */
.status-badge {
    padding: 0.15rem 0.5rem;
    border-radius: 4px;
    font-size: 0.7rem;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
}

.status-completed { background: #dcfce7; color: #166534; }
.status-pending { background: #fef3c7; color: #92400e; }
.status-overdue { background: #fee2e2; color: #991b1b; }

.priority-high { border-left: 3px solid #dc2626; }
.priority-medium { border-left: 3px solid #f59e0b; }
.priority-low { border-left: 3px solid #3b82f6; }
.priority-urgent { border-left: 3px solid #dc2626; animation: pulse-border 2s infinite; }

@keyframes pulse-border {
    0%, 100% { border-left-color: #dc2626; }
    50% { border-left-color: #f87171; }
}

/* Boutons slim */
.simple-button {
    padding: 0.5rem 1rem;
    border-radius: 6px;
    font-weight: 500;
    transition: all 0.2s ease;
    border: none;
    cursor: pointer;
    font-size: 0.875rem;
}

.simple-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(30, 24, 16, 0.15);
}

.search-input {
    border: 1px solid #e5e7eb;
    border-radius: 6px;
    padding: 0.5rem 0.875rem;
    transition: all 0.2s ease;
    font-size: 0.875rem;
}

.search-input:focus {
    border-color: #e6c252;
    box-shadow: 0 0 0 3px rgba(230, 194, 82, 0.1);
    outline: none;
}

/* Onglets compacts */
.filter-tabs {
    border-bottom: 1px solid #e5e7eb;
    margin-bottom: 1rem;
    display: flex;
    gap: 0.5rem;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.filter-tab {
    padding: 0.5rem 1rem;
    border: none;
    background: none;
    color: #6b7280;
    border-bottom: 2px solid transparent;
    transition: all 0.2s ease;
    cursor: pointer;
    white-space: nowrap;
    font-size: 0.875rem;
}

.filter-tab.active {
    color: #e6c252;
    border-bottom-color: #e6c252;
    font-weight: 600;
}

.filter-tab:hover {
    color: #1e1810;
}

/* État vide */
.empty-state {
    text-align: center;
    padding: 3rem 1.5rem;
    color: #6b7280;
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: 0.75rem;
    color: #e6c252;
}

/* Sections pliables */
.collapsible-section {
    margin-top: 0.75rem;
    border-top: 1px solid #f3f4f6;
    padding-top: 0.75rem;
}

.collapsible-header {
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 0;
    color: #374151;
    font-weight: 500;
    font-size: 0.875rem;
    transition: color 0.2s;
}

.collapsible-header:hover {
    color: #1e1810;
}

.collapsible-icon {
    transition: transform 0.2s;
    font-size: 0.75rem;
}

.collapsible-icon.rotated {
    transform: rotate(90deg);
}

.collapsible-content {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.3s ease;
}

.collapsible-content.expanded {
    max-height: 2000px;
}

/* Tags inline compacts */
.inline-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 0.375rem;
    align-items: center;
}

/* Boutons d'action compacts */
.action-buttons {
    display: flex;
    gap: 0.25rem;
}

.btn-icon {
    width: 28px;
    height: 28px;
    padding: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    font-size: 0.75rem;
}

/* Optimisation mobile */
@media screen and (max-width: 768px) {
    .project-header {
        padding: 0.875rem 1rem;
    }
    
    .activity-card {
        padding: 0.75rem 0.875rem;
    }
    
    .filter-tab {
        padding: 0.4rem 0.75rem;
        font-size: 0.8rem;
    }
    
    .simple-button {
        padding: 0.4rem 0.875rem;
        font-size: 0.8rem;
    }
}

/* Mode liste dense */
.dense-mode .activity-card {
    padding: 0.625rem 0.875rem;
    margin-bottom: 0.5rem;
}

.dense-mode .activity-icon {
    width: 28px;
    height: 28px;
    font-size: 0.75rem;
}

/* Amélioration du scroll */
::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* Animation de chargement */
.loading-skeleton {
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: loading 1.5s infinite;
}

@keyframes loading {
    0% { background-position: 200% 0; }
    100% { background-position: -200% 0; }
}

/* TinyMCE personnalisation */
.tinymce-editor {
    visibility: hidden;
}

.tox-promotion {
    display: none !important;
}

.tox .tox-editor-header {
    border-bottom: 1px solid #e6c252 !important;
}

.tox .tox-toolbar {
    background: #f8f6f0 !important;
}

.tox .tox-tbtn {
    color: #1e1810 !important;
}

.tox .tox-tbtn:hover {
    background: #e6c252 !important;
    color: white !important;
}
</style>

<section class="section is-main-section" style="padding: 1rem;">
    <!-- En-tête compact -->
    <div class="project-header">
        <div class="level is-mobile mb-0">
            <div class="level-left">
                <div class="level-item">
                    <div>
                        <h1 class="title is-4 has-text-ecolux-primary mb-2" style="line-height: 1.2;">
                            <i class="fas fa-tasks mr-2"></i>{{ project.title }}
                        </h1>
                        <div class="inline-tags">
                            <span class="tag is-ecolux-secondary is-small">
                                <i class="fas fa-calendar mr-1"></i>{{ activities|length }} activité{{ activities|length|pluralize }}
                            </span>
                            <span class="tag is-info is-small">
                                <i class="fas fa-user mr-1"></i>{{ project.created_by.user.get_full_name|default:project.created_by.user.username }}
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="level-right">
                <div class="level-item">
                    <div class="buttons has-addons">
                        <a href="{% url 'app:dashboard_projects_list' %}" class="button is-light simple-button">
                            <i class="fas fa-arrow-left"></i>
                            <span class="is-hidden-mobile ml-1">Retour</span>
                        </a>
                        {% if user_type == 'DRH' or user_type == 'TECHNICIEN' or project.created_by.user == request.user %}
                        <button class="button is-ecolux-primary simple-button" onclick="openCreateModal()">
                            <i class="fas fa-plus"></i>
                            <span class="is-hidden-mobile ml-1">Nouvelle</span>
                        </button>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filtres et recherche compacts -->
    <div class="card ecolux-card mb-3">
        <div class="card-content" style="padding: 0.875rem;">
            <div class="columns is-mobile is-multiline mb-2" style="margin-bottom: 0.5rem !important;">
                <div class="column is-12-mobile is-8-tablet" style="padding-bottom: 0.5rem;">
                    <div class="field mb-0">
                        <div class="control has-icons-left">
                            <input class="input search-input is-small" type="text" id="searchInput" placeholder="Rechercher..." onkeyup="filterActivities()">
                            <span class="icon is-left is-small">
                                <i class="fas fa-search"></i>
                            </span>
                        </div>
                    </div>
                </div>
                <div class="column is-12-mobile is-4-tablet" style="padding-bottom: 0.5rem;">
                    <div class="select is-fullwidth is-small">
                        <select id="typeFilter" onchange="filterActivities()">
                            <option value="">Tous les types</option>
                            <option value="FACTURE">Factures</option>
                            <option value="NOTE">Notes</option>
                            <option value="DEVIS">Devis</option>
                            <option value="JUSTIFICATIF">Justificatifs</option>
                            <option value="DESIGN">Design</option>
                            <option value="CONSTRUCTION">Construction</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- Onglets compacts -->
            <div class="filter-tabs">
                <button class="filter-tab active" onclick="setStatusFilter('all')">
                    <i class="fas fa-list mr-1"></i><span class="is-hidden-mobile">Toutes </span>({{ activities|length }})
                </button>
                <button class="filter-tab" onclick="setStatusFilter('pending')">
                    <i class="fas fa-clock mr-1"></i><span class="is-hidden-mobile">En cours </span>({{ pending_activities }})
                </button>
                <button class="filter-tab" onclick="setStatusFilter('completed')">
                    <i class="fas fa-check mr-1"></i><span class="is-hidden-mobile">Terminées </span>({{ completed_activities }})
                </button>
                <button class="filter-tab" onclick="setStatusFilter('overdue')">
                    <i class="fas fa-exclamation-triangle mr-1"></i><span class="is-hidden-mobile">Retard </span>({{ overdue_activities }})
                </button>
            </div>
        </div>
    </div>

    <!-- Liste des activités (design compact et pliable) -->
    <div id="activitiesList">
        {% if activity_groups %}
            {% for group in activity_groups %}
            {% with activity=group.parent %}
            <div class="activity-card priority-{{ activity.priority|lower }}" 
                 data-type="{{ activity.activity_type }}" 
                 data-status="{% if activity.is_completed %}completed{% elif activity.is_overdue %}overdue{% else %}pending{% endif %}"
                 data-title="{{ activity.title|lower }}">
                
                <!-- En-tête compact -->
                <div class="level is-mobile mb-2">
                    <div class="level-left" style="min-width: 0; flex: 1;">
                        <div class="level-item" style="min-width: 0; flex: 1;">
                            <div class="media" style="min-width: 0; width: 100%;">
                                <div class="media-left">
                                    <div class="activity-icon activity-{{ activity.activity_type|lower }}">
                                        {% if activity.activity_type == 'FACTURE' %}
                                            <i class="fas fa-file-invoice"></i>
                                        {% elif activity.activity_type == 'NOTE' %}
                                            <i class="fas fa-sticky-note"></i>
                                        {% elif activity.activity_type == 'DEVIS' %}
                                            <i class="fas fa-calculator"></i>
                                        {% elif activity.activity_type == 'JUSTIFICATIF' %}
                                            <i class="fas fa-file-alt"></i>
                                        {% elif activity.activity_type == 'DESIGN' %}
                                            <i class="fas fa-palette"></i>
                                        {% elif activity.activity_type == 'CONSTRUCTION' %}
                                            <i class="fas fa-hard-hat"></i>
                                        {% else %}
                                            <i class="fas fa-paperclip"></i>
                                        {% endif %}
                                    </div>
                                </div>
                                <div class="media-content" style="min-width: 0;">
                                    <div class="content">
                                        <p class="mb-1" style="line-height: 1.3;">
                                            <strong class="has-text-ecolux-primary is-size-6">{{ activity.title }}</strong>
                                            <span class="tag is-small is-light ml-1" style="vertical-align: middle;">{{ activity.get_activity_type_display }}</span>
                                            {% if activity.priority == 'HIGH' %}
                                                <span class="tag is-small is-danger ml-1" style="vertical-align: middle;">�</span>
                                            {% elif activity.priority == 'URGENT' %}
                                                <span class="tag is-small is-danger ml-1" style="vertical-align: middle;">🚨</span>
                                            {% endif %}
                                        </p>
                                        
                                        <div class="inline-tags">
                                            {% if activity.is_completed %}
                                                <span class="status-badge status-completed">
                                                    <i class="fas fa-check-circle"></i>Terminé
                                                </span>
                                            {% elif activity.is_overdue %}
                                                <span class="status-badge status-overdue">
                                                    <i class="fas fa-exclamation-triangle"></i>Retard
                                                </span>
                                            {% else %}
                                                <span class="status-badge status-pending">
                                                    <i class="fas fa-clock"></i>En cours
                                                </span>
                                            {% endif %}
                                            
                                            {% if activity.due_date %}
                                            <span class="tag is-small is-light">
                                                <i class="fas fa-calendar mr-1"></i>{{ activity.due_date|date:"d/m/Y" }}
                                            </span>
                                            {% endif %}
                                            
                                            {% if activity.assigned_users.exists %}
                                                <span class="tag is-small is-info">
                                                    <i class="fas fa-user mr-1"></i>{{ activity.assigned_users.count }} assigné{{ activity.assigned_users.count|pluralize }}
                                                </span>
                                            {% elif activity.assigned_to %}
                                            <span class="tag is-small is-info">
                                                <i class="fas fa-user mr-1"></i>{{ activity.assigned_to.user.get_full_name|default:activity.assigned_to.user.username|truncatechars:15 }}
                                            </span>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="level-right">
                        <div class="level-item">
                            <div class="action-buttons">
                                <!-- Bouton détails -->
                                <button class="button btn-icon is-small is-light" onclick="toggleDetails({{ activity.id }})" title="Voir détails">
                                    <i class="fas fa-chevron-down" id="icon-{{ activity.id }}"></i>
                                </button>
                                <!-- Bouton sous-activités -->
                                {% if group.children %}
                                <button class="button btn-icon is-small is-light" onclick="toggleChildren({{ activity.id }})" title="Sous-activités ({{ group.children|length }})">
                                    <i class="fas fa-sitemap"></i>
                                </button>
                                {% endif %}
                                <!-- Modifier -->
                                {% if user_type == 'DRH' or activity.created_by.user == request.user or request.user.is_superuser %}
                                <button class="button btn-icon is-small is-info is-light" onclick="openEditActivity({{ activity.id }})">
                                    <i class="fas fa-edit"></i>
                                </button>
                                {% endif %}
                                <!-- Terminer/Rouvrir -->
                                {% if user_type == 'DRH' or activity.created_by.user == request.user %}
                                <button class="button btn-icon is-small {% if activity.is_completed %}is-warning{% else %}is-success{% endif %}" 
                                        onclick="toggleActivityStatus({{ activity.id }})"
                                        title="{% if activity.is_completed %}Rouvrir{% else %}Terminer{% endif %}">
                                    <i class="fas {% if activity.is_completed %}fa-redo{% else %}fa-check{% endif %}"></i>
                                </button>
                                {% endif %}
                                <!-- Supprimer -->
                                {% if user_type == 'DRH' or activity.created_by.user == request.user or request.user.is_superuser %}
                                <button class="button btn-icon is-small is-danger is-light" onclick="deleteActivity({{ activity.id }})">
                                    <i class="fas fa-trash"></i>
                                </button>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Section détails pliable -->
                <div class="collapsible-content" id="details-{{ activity.id }}">
                    <!-- Description -->
                    {% if activity.description %}
                    <div class="collapsible-section">
                        <div class="collapsible-header" onclick="toggleSection('desc-{{ activity.id }}')">
                            <i class="fas fa-chevron-right collapsible-icon" id="icon-desc-{{ activity.id }}"></i>
                            <i class="fas fa-align-left mr-1"></i>
                            <strong>Description</strong>
                        </div>
                        <div class="collapsible-content" id="desc-{{ activity.id }}">
                            <div class="box is-size-7" style="background: #f8f9fa; border-left: 3px solid #e6c252; padding: 0.75rem; margin-top: 0.5rem;">
                                {{ activity.description|safe }}
                            </div>
                        </div>
                    </div>
                    {% endif %}

                    <!-- Informations compactes -->
                    <div class="collapsible-section">
                        <div class="columns is-multiline is-mobile" style="font-size: 0.8rem;">
                            <div class="column is-half-mobile is-one-third-tablet">
                                <p class="mb-1"><strong><i class="fas fa-user-plus mr-1"></i>Créé par:</strong></p>
                                <p class="has-text-grey">{{ activity.created_by.user.get_full_name|default:activity.created_by.user.username }}</p>
                            </div>
                            <div class="column is-half-mobile is-one-third-tablet">
                                <p class="mb-1"><strong><i class="fas fa-clock mr-1"></i>Création:</strong></p>
                                <p class="has-text-grey">{{ activity.created_at|date:"d/m/Y H:i" }}</p>
                            </div>
                            {% if activity.assigned_users.exists %}
                            <div class="column is-full-mobile is-one-third-tablet">
                                <p class="mb-1"><strong><i class="fas fa-users mr-1"></i>Assignés:</strong></p>
                                <div class="inline-tags">
                                    {% for assigned_user in activity.assigned_users.all %}
                                    <span class="tag is-info is-light is-small">
                                        {{ assigned_user.user.get_full_name|default:assigned_user.user.username }}
                                    </span>
                                    {% endfor %}
                                </div>
                            </div>
                            {% endif %}
                            {% if activity.completed_at %}
                            <div class="column is-half-mobile is-one-third-tablet">
                                <p class="mb-1"><strong><i class="fas fa-check-double mr-1"></i>Terminé:</strong></p>
                                <p class="has-text-grey">{{ activity.completed_at|date:"d/m/Y H:i" }}</p>
                            </div>
                            {% endif %}
                        </div>
                    </div>

                    <!-- Fichiers joints (version compacte) -->
                    {% with activity.images.all as images %}
                    {% with activity.videos.all as videos %}
                    {% with activity.files.all as files %}
                    {% if images or videos or files %}
                    <div class="collapsible-section">
                        <div class="collapsible-header" onclick="toggleSection('files-{{ activity.id }}')">
                            <i class="fas fa-chevron-right collapsible-icon" id="icon-files-{{ activity.id }}"></i>
                            <i class="fas fa-paperclip mr-1"></i>
                            <strong>Fichiers ({{ images.count|add:videos.count|add:files.count }})</strong>
                        </div>
                        <div class="collapsible-content" id="files-{{ activity.id }}">
                            <!-- Images en miniature -->
                            {% if images %}
                            <div class="mt-2">
                                <p class="is-size-7 has-text-weight-semibold mb-2"><i class="fas fa-image mr-1"></i>Images ({{ images.count }})</p>
                                <div class="columns is-multiline is-mobile">
                                    {% for image in images|slice:":6" %}
                                    <div class="column is-4-mobile is-3-tablet is-2-desktop">
                                        <a href="{{ image.image.url }}" target="_blank" title="{{ image.title }}">
                                            <figure class="image is-square">
                                                <img src="{{ image.image.url }}" alt="{{ image.title }}" 
                                                     style="object-fit: cover; border-radius: 4px; border: 1px solid #e6c252;">
                                            </figure>
                                        </a>
                                    </div>
                                    {% endfor %}
                                    {% if images.count > 6 %}
                                    <div class="column is-4-mobile is-3-tablet is-2-desktop">
                                        <div class="box has-text-centered" style="height: 100%; display: flex; align-items: center; justify-content: center; background: #f8f9fa; padding: 0.5rem;">
                                            <p class="is-size-7">+{{ images.count|add:"-6" }}</p>
                                        </div>
                                    </div>
                                    {% endif %}
                                </div>
                            </div>
                            {% endif %}

                            <!-- Documents -->
                            {% if files %}
                            <div class="mt-2">
                                <p class="is-size-7 has-text-weight-semibold mb-2"><i class="fas fa-file-alt mr-1"></i>Documents ({{ files.count }})</p>
                                {% for file in files %}
                                <div class="box is-size-7" style="background: #f0f8ff; border: 1px solid #ddd; padding: 0.5rem; margin-bottom: 0.25rem;">
                                    <div class="level is-mobile mb-0">
                                        <div class="level-left" style="min-width: 0;">
                                            <div class="level-item" style="min-width: 0;">
                                                <span class="icon has-text-primary mr-2">
                                                    <i class="fas fa-file-download"></i>
                                                </span>
                                                <span style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{ file.title }}</span>
                                            </div>
                                        </div>
                                        <div class="level-right">
                                            <div class="level-item">
                                                <a href="{{ file.file.url }}" target="_blank" class="button is-small is-primary btn-icon">
                                                    <i class="fas fa-download"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    {% endif %}
                    {% endwith %}
                    {% endwith %}
                    {% endwith %}
                </div>

                <!-- Sous-activités (version compacte) -->
                {% if group.children %}
                <div id="children-{{ activity.id }}" style="display: none; margin-left: 1rem; margin-top: 0.75rem; padding-left: 0.75rem; border-left: 2px solid #e6c252;">
                    {% for child in group.children %}
                    <div class="activity-card priority-{{ child.priority|lower }}" 
                         data-type="{{ child.activity_type }}" 
                         data-status="{% if child.is_completed %}completed{% elif child.is_overdue %}overdue{% else %}pending{% endif %}"
                         data-title="{{ child.title|lower }}"
                         style="padding: 0.625rem 0.75rem;">
                        
                        <!-- En-tête de la sous-activité -->
                        <div class="level is-mobile mb-2">
                            <div class="level-left" style="min-width: 0; flex: 1;">
                                <div class="level-item" style="min-width: 0; flex: 1;">
                                    <div class="media" style="min-width: 0; width: 100%;">
                                        <div class="media-left">
                                            <div class="activity-icon activity-{{ child.activity_type|lower }}" style="width: 24px; height: 24px; font-size: 0.7rem;">
                                                <i class="fas fa-level-down-alt"></i>
                                            </div>
                                        </div>
                                        <div class="media-content" style="min-width: 0;">
                                            <p class="mb-1 is-size-7" style="line-height: 1.2;">
                                                <strong class="has-text-ecolux-primary">{{ child.title }}</strong>
                                                <span class="tag is-small is-light ml-1" style="vertical-align: middle; font-size: 0.65rem;">{{ child.get_activity_type_display }}</span>
                                                {% if child.priority == 'HIGH' %}
                                                    <span class="tag is-small is-danger ml-1" style="vertical-align: middle;">🔴</span>
                                                {% elif child.priority == 'URGENT' %}
                                                    <span class="tag is-small is-danger ml-1" style="vertical-align: middle;">🚨</span>
                                                {% endif %}
                                            </p>
                                            
                                            <div class="inline-tags">
                                                {% if child.is_completed %}
                                                    <span class="status-badge status-completed"><i class="fas fa-check-circle"></i>Terminé</span>
                                                {% elif child.is_overdue %}
                                                    <span class="status-badge status-overdue"><i class="fas fa-exclamation-triangle"></i>Retard</span>
                                                {% else %}
                                                    <span class="status-badge status-pending"><i class="fas fa-clock"></i>En cours</span>
                                                {% endif %}
                                                
                                                {% if child.due_date %}
                                                <span class="tag is-small is-light">
                                                    <i class="fas fa-calendar mr-1"></i>{{ child.due_date|date:"d/m/Y" }}
                                                </span>
                                                {% endif %}
                                                
                                                {% if child.assigned_users.exists %}
                                                    <span class="tag is-small is-info">
                                                        <i class="fas fa-user mr-1"></i>{{ child.assigned_users.count }} assigné{{ child.assigned_users.count|pluralize }}
                                                    </span>
                                                {% elif child.assigned_to %}
                                                <span class="tag is-small is-info">
                                                    <i class="fas fa-user mr-1"></i>{{ child.assigned_to.user.get_full_name|default:child.assigned_to.user.username|truncatechars:15 }}
                                                </span>
                                                {% endif %}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="level-right">
                                <div class="level-item">
                                    <div class="action-buttons">
                                        <!-- Bouton détails -->
                                        <button class="button btn-icon is-small is-light" onclick="toggleDetails({{ child.id }})" title="Voir détails">
                                            <i class="fas fa-chevron-down" id="icon-{{ child.id }}"></i>
                                        </button>
                                        <!-- Modifier -->
                                        {% if user_type == 'DRH' or child.created_by.user == request.user or request.user.is_superuser %}
                                        <button class="button btn-icon is-small is-info is-light" onclick="openEditActivity({{ child.id }})">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        {% endif %}
                                        <!-- Terminer/Rouvrir -->
                                        {% if user_type == 'DRH' or child.created_by.user == request.user %}
                                        <button class="button btn-icon is-small {% if child.is_completed %}is-warning{% else %}is-success{% endif %}" onclick="toggleActivityStatus({{ child.id }})" title="{% if child.is_completed %}Rouvrir{% else %}Terminer{% endif %}">
                                            <i class="fas {% if child.is_completed %}fa-redo{% else %}fa-check{% endif %}"></i>
                                        </button>
                                        {% endif %}
                                        <!-- Supprimer -->
                                        {% if user_type == 'DRH' or child.created_by.user == request.user or request.user.is_superuser %}
                                        <button class="button btn-icon is-small is-danger is-light" onclick="deleteActivity({{ child.id }})">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Section détails pliable de la sous-activité -->
                        <div class="collapsible-content" id="details-{{ child.id }}">
                            <!-- Description -->
                            {% if child.description %}
                            <div class="collapsible-section">
                                <div class="collapsible-header" onclick="toggleSection('desc-{{ child.id }}')">
                                    <i class="fas fa-chevron-right collapsible-icon" id="icon-desc-{{ child.id }}"></i>
                                    <i class="fas fa-align-left mr-1"></i>
                                    <strong>Description</strong>
                                </div>
                                <div class="collapsible-content" id="desc-{{ child.id }}">
                                    <div class="box is-size-7" style="background: #f8f9fa; border-left: 3px solid #e6c252; padding: 0.75rem; margin-top: 0.5rem;">
                                        {{ child.description|safe }}
                                    </div>
                                </div>
                            </div>
                            {% endif %}

                            <!-- Informations compactes -->
                            <div class="collapsible-section">
                                <div class="columns is-multiline is-mobile" style="font-size: 0.75rem;">
                                    <div class="column is-half-mobile is-one-third-tablet">
                                        <p class="mb-1"><strong><i class="fas fa-user-plus mr-1"></i>Créé par:</strong></p>
                                        <p class="has-text-grey">{{ child.created_by.user.get_full_name|default:child.created_by.user.username }}</p>
                                    </div>
                                    <div class="column is-half-mobile is-one-third-tablet">
                                        <p class="mb-1"><strong><i class="fas fa-clock mr-1"></i>Création:</strong></p>
                                        <p class="has-text-grey">{{ child.created_at|date:"d/m/Y H:i" }}</p>
                                    </div>
                                    {% if child.assigned_users.exists %}
                                    <div class="column is-full-mobile is-one-third-tablet">
                                        <p class="mb-1"><strong><i class="fas fa-users mr-1"></i>Assignés:</strong></p>
                                        <div class="inline-tags">
                                            {% for assigned_user in child.assigned_users.all %}
                                            <span class="tag is-info is-light is-small">
                                                {{ assigned_user.user.get_full_name|default:assigned_user.user.username }}
                                            </span>
                                            {% endfor %}
                                        </div>
                                    </div>
                                    {% endif %}
                                    {% if child.completed_at %}
                                    <div class="column is-half-mobile is-one-third-tablet">
                                        <p class="mb-1"><strong><i class="fas fa-check-double mr-1"></i>Terminé:</strong></p>
                                        <p class="has-text-grey">{{ child.completed_at|date:"d/m/Y H:i" }}</p>
                                    </div>
                                    {% endif %}
                                </div>
                            </div>

                            <!-- Fichiers joints (version compacte) -->
                            {% with child.images.all as images %}
                            {% with child.videos.all as videos %}
                            {% with child.files.all as files %}
                            {% if images or videos or files %}
                            <div class="collapsible-section">
                                <div class="collapsible-header" onclick="toggleSection('files-{{ child.id }}')">
                                    <i class="fas fa-chevron-right collapsible-icon" id="icon-files-{{ child.id }}"></i>
                                    <i class="fas fa-paperclip mr-1"></i>
                                    <strong>Fichiers ({{ images.count|add:videos.count|add:files.count }})</strong>
                                </div>
                                <div class="collapsible-content" id="files-{{ child.id }}">
                                    <!-- Images en miniature -->
                                    {% if images %}
                                    <div class="mt-2">
                                        <p class="is-size-7 has-text-weight-semibold mb-2"><i class="fas fa-image mr-1"></i>Images ({{ images.count }})</p>
                                        <div class="columns is-multiline is-mobile">
                                            {% for image in images|slice:":6" %}
                                            <div class="column is-4-mobile is-3-tablet is-2-desktop">
                                                <a href="{{ image.image.url }}" target="_blank" title="{{ image.title }}">
                                                    <figure class="image is-square">
                                                        <img src="{{ image.image.url }}" alt="{{ image.title }}" 
                                                             style="object-fit: cover; border-radius: 4px; border: 1px solid #e6c252;">
                                                    </figure>
                                                </a>
                                            </div>
                                            {% endfor %}
                                            {% if images.count > 6 %}
                                            <div class="column is-4-mobile is-3-tablet is-2-desktop">
                                                <div class="box has-text-centered" style="height: 100%; display: flex; align-items: center; justify-content: center; background: #f8f9fa; padding: 0.5rem;">
                                                    <p class="is-size-7">+{{ images.count|add:"-6" }}</p>
                                                </div>
                                            </div>
                                            {% endif %}
                                        </div>
                                    </div>
                                    {% endif %}

                                    <!-- Documents -->
                                    {% if files %}
                                    <div class="mt-2">
                                        <p class="is-size-7 has-text-weight-semibold mb-2"><i class="fas fa-file-alt mr-1"></i>Documents ({{ files.count }})</p>
                                        {% for file in files %}
                                        <div class="box is-size-7" style="background: #f0f8ff; border: 1px solid #ddd; padding: 0.5rem; margin-bottom: 0.25rem;">
                                            <div class="level is-mobile mb-0">
                                                <div class="level-left" style="min-width: 0;">
                                                    <div class="level-item" style="min-width: 0;">
                                                        <span class="icon has-text-primary mr-2">
                                                            <i class="fas fa-file-download"></i>
                                                        </span>
                                                        <span style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{ file.title }}</span>
                                                    </div>
                                                </div>
                                                <div class="level-right">
                                                    <div class="level-item">
                                                        <a href="{{ file.file.url }}" target="_blank" class="button is-small is-primary btn-icon">
                                                            <i class="fas fa-download"></i>
                                                        </a>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        {% endfor %}
                                    </div>
                                    {% endif %}
                                </div>
                            </div>
                            {% endif %}
                            {% endwith %}
                            {% endwith %}
                            {% endwith %}
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% endif %}

            </div>
            {% endwith %}
            {% endfor %}
        {% else %}
            <div class="empty-state">
                <i class="fas fa-inbox"></i>
                <h3 class="title is-4">Aucune activité</h3>
                <p class="subtitle">Ce projet n'a pas encore d'activités.</p>
                {% if user_type == 'DRH' or user_type == 'TECHNICIEN' or project.created_by.user == request.user %}
                <button class="button is-ecolux-primary simple-button mt-3" onclick="openCreateModal()">
                    <i class="fas fa-plus mr-2"></i>
                    Créer la première activité
                </button>
                {% endif %}
            </div>
        {% endif %}
    </div>
</section>

<!-- Modal de création d'activité -->
<div class="modal" id="createActivityModal">
    <div class="modal-background" onclick="closeCreateModal()"></div>
    <div class="modal-card" style="width: 95%; max-width: 800px; margin: auto;">
        <header class="modal-card-head ecolux-primary">
            <p class="modal-card-title has-text-white">
                <i class="fas fa-plus mr-2"></i>
                Nouvelle activité
            </p>
            <button class="delete" aria-label="close" onclick="closeCreateModal()"></button>
        </header>
        
        <section class="modal-card-body" style="max-height: 80vh; overflow-y: auto;">
            <form id="createActivityForm" method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                <input type="hidden" name="project_id" value="{{ project.id }}">
                
                <div class="field">
                    <label class="label has-text-ecolux-primary">Titre *</label>
                    <div class="control">
                        <input class="input" type="text" name="title" placeholder="Titre de l'activité" required>
                    </div>
                </div>

                <div class="columns is-mobile">
                    <div class="column is-half-mobile is-half-tablet">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Type *</label>
                            <div class="control">
                                <div class="select is-fullwidth">
                                    <select name="activity_type" required>
                                        <option value="">Choisir un type</option>
                                        {% for activity_type, display_name in allowed_activity_types %}
                                            <option value="{{ activity_type }}">{{ display_name }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="column is-half-mobile is-half-tablet">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Priorité</label>
                            <div class="control">
                                <div class="select is-fullwidth">
                                    <select name="priority">
                                        <option value="LOW">🟢 Basse</option>
                                        <option value="MEDIUM" selected>🟡 Moyenne</option>
                                        <option value="HIGH">🔴 Haute</option>
                                        <option value="URGENT">🚨 Urgent</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="field">
                    <label class="label has-text-ecolux-primary">Description</label>
                    <div class="control">
                        <textarea class="textarea tinymce-editor" name="description" rows="4" placeholder="Description de l'activité"></textarea>
                    </div>
                    <p class="help">Utilisez l'éditeur pour formater votre texte (gras, italique, listes, etc.)</p>
                </div>

                <!-- Facturation, parent, budget et activation -->
                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Type de facturation</label>
                            <div class="control">
                                <div class="select is-fullwidth">
                                    <select name="billing_type">
                                        <option value="NONE" selected>Non facturable</option>
                                        <option value="MILESTONE">Par jalon</option>
                                        <option value="FIXED">Forfait</option>
                                        <option value="TIME">Temps passé</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Activité parente</label>
                            <div class="control">
                                <div class="select is-fullwidth">
                                    <select name="parent" id="activity_parent_select">
                                        <option value="">Aucune</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Budget activité (FCFA)</label>
                            <div class="control">
                                <input class="input" type="number" name="budget_amount" placeholder="Montant prévu">
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field" style="margin-top: 2rem;">
                            <label class="checkbox">
                                <input type="checkbox" name="is_active" checked>
                                Activité activée
                            </label>
                        </div>
                    </div>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Date d'échéance</label>
                            <div class="control">
                                <input class="input" type="date" name="due_date">
                            </div>
                        </div>
                    </div>
                    <div class="column is-full-mobile is-full-tablet is-two-thirds-desktop">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">
                                <i class="fas fa-users mr-1"></i>Assigner à (multiple)
                            </label>
                            <div class="control">
                                <div class="select is-multiple is-fullwidth">
                                    <select name="assigned_to" multiple size="6" style="min-height: 140px;">
                                        {% regroup all_users by type as users_by_type %}
                                        {% for type_group in users_by_type %}
                                            <optgroup label="{% if type_group.grouper == 'ADMIN' %}🛠️ Administrateurs{% elif type_group.grouper == 'DRH' %}👑 DRH{% elif type_group.grouper == 'CLIENT' %}👔 Clients{% elif type_group.grouper == 'TECHNICIEN' %}🔧 Techniciens{% else %}👤 {{ type_group.grouper }}{% endif %}">
                                                {% for user in type_group.list %}
                                                    <option value="{{ user.id }}">
                                                        {{ user.user.get_full_name|default:user.user.username }}
                                                        ({{ user.get_type_display }})
                                                        {% if user.id == project.created_by.id %} - Créateur{% endif %}
                                                        {% if user.id == project.client.id %} - Client du projet{% endif %}
                                                        {% if user in available_technicians %} - Assigné au projet{% endif %}
                                                    </option>
                                                {% endfor %}
                                            </optgroup>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>
                            <p class="help is-size-7">
                                <i class="fas fa-info-circle mr-1"></i>
                                <span class="is-hidden-mobile"><strong>Ctrl+Clic</strong> pour sélectionner plusieurs personnes. <strong>Shift+Clic</strong> pour sélectionner une plage.</span>
                                <span class="is-hidden-tablet">Appuyez et maintenez pour sélectionner plusieurs personnes.</span>
                            </p>
                        </div>
                    </div>
                </div>

                <div class="field">
                    <label class="label has-text-ecolux-primary">Fichiers</label>
                    
                    <!-- Fichiers existants (visible uniquement en mode édition) -->
                    <div id="existingFiles" style="display: none; margin-bottom: 1rem;">
                        <p class="has-text-weight-semibold mb-2" style="font-size: 0.875rem;">
                            <i class="fas fa-paperclip mr-1"></i>Fichiers actuels:
                        </p>
                        <div id="existingFilesList" class="box" style="background: #f8f9fa; padding: 0.75rem;">
                            <!-- Les fichiers seront ajoutés ici dynamiquement -->
                        </div>
                    </div>
                    
                    <!-- Champ pour ajouter de nouveaux fichiers -->
                    <div class="control">
                        <div class="file has-name is-fullwidth">
                            <label class="file-label">
                                <input class="file-input" type="file" name="activity_files" multiple accept="image/*,video/*,.pdf,.doc,.docx">
                                <span class="file-cta is-ecolux-secondary">
                                    <span class="file-icon">
                                        <i class="fas fa-upload"></i>
                                    </span>
                                    <span class="file-label" id="fileUploadLabel">Choisir des fichiers</span>
                                </span>
                                <span class="file-name">Aucun fichier choisi</span>
                            </label>
                        </div>
                    </div>
                    <p class="help">Images, vidéos, PDF, documents Word acceptés</p>
                </div>
            </form>
        </section>
        
        <footer class="modal-card-foot">
            <button class="button is-ecolux-primary" onclick="submitActivityForm()">
                <i class="fas fa-save mr-2"></i>
                mettre à jour l'activité
            </button>
            <button class="button" onclick="closeCreateModal()">Annuler</button>
        </footer>
    </div>
</div>

<script>
let currentStatusFilter = 'all';
let editingActivityId = null;
let filesToDelete = {
    images: [],
    files: [],
    videos: []
};

// Initialisation de TinyMCE pour l'éditeur de description
function initTinyMCE() {
    if (typeof tinymce === 'undefined') {
        console.error('TinyMCE n\'est pas encore chargé');
        return;
    }
    
    if (tinymce.get('description-editor')) {
        tinymce.get('description-editor').remove();
    }
    
    tinymce.init({
        selector: '.tinymce-editor',
        height: 300,
        language: 'fr_FR',
        plugins: [
            'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
            'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
            'insertdatetime', 'media', 'table', 'help', 'wordcount', 'emoticons'
        ],
        toolbar: 'undo redo | blocks | bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | removeformat | code | help',
        menubar: false,
        branding: false,
        promotion: false,
        content_style: 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; font-size: 14px; }',
        setup: function (editor) {
            editor.on('change', function () {
                editor.save();
            });
        },
        images_upload_handler: function (blobInfo, success, failure) {
            // Vous pouvez implémenter l'upload d'images ici si nécessaire
            failure('Upload d\'image non configuré');
        }
    });
}

// Détruire l'instance TinyMCE
function destroyTinyMCE() {
    if (typeof tinymce !== 'undefined' && tinymce.editors && Object.keys(tinymce.editors).length > 0) {
        tinymce.remove('.tinymce-editor');
    }
}

// Basculer les détails d'une activité (nouveau)
function toggleDetails(activityId) {
    const details = document.getElementById(`details-${activityId}`);
    const icon = document.getElementById(`icon-${activityId}`);
    
    if (details.classList.contains('expanded')) {
        details.classList.remove('expanded');
        icon.classList.remove('fa-chevron-up');
        icon.classList.add('fa-chevron-down');
    } else {
        details.classList.add('expanded');
        icon.classList.remove('fa-chevron-down');
        icon.classList.add('fa-chevron-up');
    }
}

// Basculer une section pliable (nouveau)
function toggleSection(sectionId) {
    const section = document.getElementById(sectionId);
    const icon = document.getElementById(`icon-${sectionId}`);
    
    if (section.classList.contains('expanded')) {
        section.classList.remove('expanded');
        icon.classList.remove('rotated');
    } else {
        section.classList.add('expanded');
        icon.classList.add('rotated');
    }
}

// Basculer les sous-activités
function toggleChildren(activityId) {
    const el = document.getElementById(`children-${activityId}`);
    if (!el) return;
    el.style.display = (el.style.display === 'none' || el.style.display === '') ? 'block' : 'none';
}

// Gestion du modal
function openCreateModal() {
    const modal = document.getElementById('createActivityModal');
    modal.classList.add('is-active');
    document.body.style.overflow = 'hidden';
    
    // Charger les activités parentes
    populateParentActivities();
    
    // Initialiser TinyMCE après que le modal soit visible
    setTimeout(() => {
        initTinyMCE();
        // Focus sur le premier champ (desktop uniquement)
        if (window.innerWidth > 768) {
            const firstInput = modal.querySelector('input[name="title"]');
            if (firstInput) firstInput.focus();
        }
    }, 200);
}

function closeCreateModal() {
    // Détruire l'instance TinyMCE avant de fermer le modal
    destroyTinyMCE();
    
    document.getElementById('createActivityModal').classList.remove('is-active');
    document.getElementById('createActivityForm').reset();
    document.body.style.overflow = '';
    editingActivityId = null;
    
    // Réinitialiser la liste des fichiers à supprimer
    filesToDelete = {
        images: [],
        files: [],
        videos: []
    };
    
    // Réinitialiser l'affichage des fichiers
    const existingFilesDiv = document.getElementById('existingFiles');
    const existingFilesList = document.getElementById('existingFilesList');
    const fileUploadLabel = document.getElementById('fileUploadLabel');
    
    if (existingFilesDiv) existingFilesDiv.style.display = 'none';
    if (existingFilesList) existingFilesList.innerHTML = '';
    if (fileUploadLabel) fileUploadLabel.textContent = 'Choisir des fichiers';
    
    const fileName = document.querySelector('.file-name');
    if (fileName) {
        fileName.textContent = 'Aucun fichier choisi';
    }
}

// Charger les activités pour le sélecteur parent
function populateParentActivities() {
    const select = document.getElementById('activity_parent_select');
    if (!select) return;
    select.innerHTML = '<option value="">Aucune</option>';
    
    fetch(`/dashboard/projects/{{ project.id }}/activities/options/`)
        .then(res => res.json())
        .then(data => {
            if (data.success && Array.isArray(data.activities)) {
                data.activities.forEach(act => {
                    const opt = document.createElement('option');
                    opt.value = act.id;
                    opt.textContent = act.title;
                    select.appendChild(opt);
                });
            }
        })
        .catch(err => console.error('Erreur chargement activités:', err));
}

// Afficher les fichiers existants d'une activité
function displayExistingFiles(activity) {
    const existingFilesDiv = document.getElementById('existingFiles');
    const existingFilesList = document.getElementById('existingFilesList');
    const fileUploadLabel = document.getElementById('fileUploadLabel');
    
    if (!existingFilesDiv || !existingFilesList) return;
    
    // Vider la liste
    existingFilesList.innerHTML = '';
    
    const hasFiles = (activity.images && activity.images.length > 0) || 
                     (activity.files && activity.files.length > 0) ||
                     (activity.videos && activity.videos.length > 0);
    
    if (hasFiles) {
        existingFilesDiv.style.display = 'block';
        fileUploadLabel.textContent = 'Ajouter d\'autres fichiers';
        
        let filesHTML = '';
        
        // Images
        if (activity.images && activity.images.length > 0) {
            filesHTML += '<div class="mb-2"><strong style="font-size: 0.8rem;"><i class="fas fa-image mr-1"></i>Images:</strong></div>';
            activity.images.forEach(img => {
                filesHTML += `
                    <div class="mb-2" id="image-${img.id}" style="display: flex; align-items: center; gap: 0.5rem; padding: 0.5rem; background: white; border-radius: 4px; border: 1px solid #e5e7eb;">
                        <img src="${img.url}" style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;">
                        <span style="flex: 1; font-size: 0.8rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${img.name || 'Image'}</span>
                        <a href="${img.url}" target="_blank" class="button is-small is-info is-light" title="Voir">
                            <i class="fas fa-eye"></i>
                        </a>
                        <button type="button" class="button is-small is-danger is-light" title="Supprimer" onclick="markFileForDeletion('image', ${img.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                `;
            });
        }
        
        // Documents
        if (activity.files && activity.files.length > 0) {
            filesHTML += '<div class="mb-2 mt-3"><strong style="font-size: 0.8rem;"><i class="fas fa-file-alt mr-1"></i>Documents:</strong></div>';
            activity.files.forEach(file => {
                const icon = file.name.endsWith('.pdf') ? 'fa-file-pdf' : 
                            file.name.endsWith('.doc') || file.name.endsWith('.docx') ? 'fa-file-word' : 
                            'fa-file';
                filesHTML += `
                    <div class="mb-2" id="file-${file.id}" style="display: flex; align-items: center; gap: 0.5rem; padding: 0.5rem; background: white; border-radius: 4px; border: 1px solid #e5e7eb;">
                        <i class="fas ${icon}" style="font-size: 1.5rem; color: #6b7280; width: 40px; text-align: center;"></i>
                        <span style="flex: 1; font-size: 0.8rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${file.name}</span>
                        <a href="${file.url}" target="_blank" class="button is-small is-info is-light" title="Télécharger">
                            <i class="fas fa-download"></i>
                        </a>
                        <button type="button" class="button is-small is-danger is-light" title="Supprimer" onclick="markFileForDeletion('file', ${file.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                `;
            });
        }
        
        // Vidéos
        if (activity.videos && activity.videos.length > 0) {
            filesHTML += '<div class="mb-2 mt-3"><strong style="font-size: 0.8rem;"><i class="fas fa-video mr-1"></i>Vidéos:</strong></div>';
            activity.videos.forEach(video => {
                filesHTML += `
                    <div class="mb-2" id="video-${video.id}" style="display: flex; align-items: center; gap: 0.5rem; padding: 0.5rem; background: white; border-radius: 4px; border: 1px solid #e5e7eb;">
                        <i class="fas fa-video" style="font-size: 1.5rem; color: #6b7280; width: 40px; text-align: center;"></i>
                        <span style="flex: 1; font-size: 0.8rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${video.name || 'Vidéo'}</span>
                        <a href="${video.url}" target="_blank" class="button is-small is-info is-light" title="Voir">
                            <i class="fas fa-eye"></i>
                        </a>
                        <button type="button" class="button is-small is-danger is-light" title="Supprimer" onclick="markFileForDeletion('video', ${video.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                `;
            });
        }
        
        existingFilesList.innerHTML = filesHTML;
    } else {
        existingFilesDiv.style.display = 'none';
        fileUploadLabel.textContent = 'Choisir des fichiers';
    }
}

// Marquer un fichier pour suppression
function markFileForDeletion(fileType, fileId) {
    console.log('markFileForDeletion appelée:', fileType, fileId);
    
    if (!confirm('Voulez-vous vraiment supprimer ce fichier ?')) {
        return;
    }
    
    // Ajouter l'ID à la liste des fichiers à supprimer
    if (fileType === 'image') {
        filesToDelete.images.push(fileId);
    } else if (fileType === 'file') {
        filesToDelete.files.push(fileId);
    } else if (fileType === 'video') {
        filesToDelete.videos.push(fileId);
    }
    
    console.log('Liste mise à jour filesToDelete:', filesToDelete);
    
    // Masquer visuellement le fichier (avec effet de fade-out)
    const element = document.getElementById(`${fileType}-${fileId}`);
    if (element) {
        element.style.opacity = '0.5';
        element.style.textDecoration = 'line-through';
        element.style.backgroundColor = '#fee2e2';
        
        // Désactiver le bouton de suppression
        const deleteBtn = element.querySelector('button[onclick*="markFileForDeletion"]');
        if (deleteBtn) {
            deleteBtn.disabled = true;
            deleteBtn.innerHTML = '<i class="fas fa-check"></i>';
            deleteBtn.classList.remove('is-danger');
            deleteBtn.classList.add('is-success');
        }
    }
}

// Ouvrir l'édition d'une activité
function openEditActivity(activityId) {
    document.getElementById('createActivityModal').classList.add('is-active');
    document.body.style.overflow = 'hidden';
    editingActivityId = activityId;
    
    const form = document.getElementById('createActivityForm');
    form.reset();
    
    // Détruire l'instance TinyMCE existante
    destroyTinyMCE();
    
    populateParentActivities();

    fetch(`{% url 'app:get_activity_data' 0 %}`.replace('0', activityId))
        .then(r => r.json())
        .then(data => {
            if (!data.success) { 
                alert(data.message || 'Erreur chargement activité'); 
                return; 
            }
            const a = data.activity;
            form.querySelector('[name=title]').value = a.title || '';
            
            // Charger la description dans le textarea AVANT d'initialiser TinyMCE
            const descriptionTextarea = form.querySelector('[name=description]');
            if (descriptionTextarea) {
                descriptionTextarea.value = a.description || '';
            }
            
            if (a.activity_type) form.querySelector('[name=activity_type]').value = a.activity_type;
            if (a.priority) form.querySelector('[name=priority]').value = a.priority;
            if (a.due_date) form.querySelector('[name=due_date]').value = a.due_date;
            if (a.billing_type) form.querySelector('[name=billing_type]').value = a.billing_type;
            if (a.budget_amount) form.querySelector('[name=budget_amount]').value = a.budget_amount;
            form.querySelector('[name=is_active]').checked = !!a.is_active;

            // Afficher les fichiers existants
            displayExistingFiles(a);

            // Initialiser TinyMCE - il va automatiquement récupérer le contenu du textarea
            setTimeout(() => {
                initTinyMCE();
            }, 200);

            setTimeout(() => {
                if (a.parent_id) {
                    const parentSelect = document.getElementById('activity_parent_select');
                    if (parentSelect) parentSelect.value = String(a.parent_id);
                }
            }, 200);

            if (Array.isArray(a.assigned_user_ids)) {
                const sel = form.querySelector('select[name="assigned_to"]');
                if (sel) {
                    Array.from(sel.options).forEach(opt => {
                        opt.selected = a.assigned_user_ids.includes(parseInt(opt.value));
                    });
                }
            }
        })
        .catch(e => console.error(e));
}

// Supprimer une activité
function deleteActivity(activityId) {
    if (!confirm('Supprimer cette activité ?')) return;
    
    fetch(`{% url 'app:delete_dashboard_activity' 0 %}`.replace('0', activityId), {
        method: 'POST',
        headers: { 'X-CSRFToken': '{{ csrf_token }}' }
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) { 
            location.reload(); 
        } else { 
            alert(data.message || 'Suppression refusée'); 
        }
    })
    .catch(e => { 
        console.error(e); 
        alert('Erreur de suppression'); 
    });
}

// Changement de statut d'activité
function toggleActivityStatus(activityId) {
    if (!confirm('Changer le statut de cette activité ?')) return;
    
    fetch(`{% url 'app:toggle_activity_status' 0 %}`.replace('0', activityId), {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}',
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'completed=true'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Erreur: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Erreur:', error);
        alert('Une erreur est survenue');
    });
}

// Filtrage des activités
function filterActivities() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    const typeFilter = document.getElementById('typeFilter').value;
    const activities = document.querySelectorAll('.activity-card[data-title]');
    
    let visibleCount = 0;
    activities.forEach(activity => {
        const title = activity.dataset.title;
        const type = activity.dataset.type;
        const status = activity.dataset.status;
        
        let showActivity = true;
        
        if (searchTerm && !title.includes(searchTerm)) {
            showActivity = false;
        }
        
        if (typeFilter && type !== typeFilter) {
            showActivity = false;
        }
        
        if (currentStatusFilter !== 'all' && status !== currentStatusFilter) {
            showActivity = false;
        }
        
        activity.style.display = showActivity ? 'block' : 'none';
        if (showActivity) visibleCount++;
    });
    
    // Afficher un message si aucun résultat
    const list = document.getElementById('activitiesList');
    let noResults = list.querySelector('.no-results-message');
    
    if (visibleCount === 0 && !noResults) {
        noResults = document.createElement('div');
        noResults.className = 'empty-state no-results-message';
        noResults.innerHTML = '<i class="fas fa-search"></i><h3 class="title is-5">Aucun résultat</h3><p>Essayez de modifier vos critères de recherche.</p>';
        list.appendChild(noResults);
    } else if (visibleCount > 0 && noResults) {
        noResults.remove();
    }
}

// Changement de filtre de statut
function setStatusFilter(status) {
    currentStatusFilter = status;
    
    document.querySelectorAll('.filter-tab').forEach(tab => {
        tab.classList.remove('active');
    });
    event.target.classList.add('active');
    
    filterActivities();
}

// Initialisation au chargement
document.addEventListener('DOMContentLoaded', function() {
    // Gestion du nom de fichier
    const fileInput = document.querySelector('.file-input');
    const fileName = document.querySelector('.file-name');
    
    if (fileInput) {
        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                if (this.files.length === 1) {
                    const name = this.files[0].name;
                    fileName.textContent = name.length > 30 ? name.substring(0, 27) + '...' : name;
                } else {
                    fileName.textContent = `${this.files.length} fichiers`;
                }
            } else {
                fileName.textContent = 'Aucun fichier choisi';
            }
        });
    }
    
    // Amélioration tactile sur mobile
    if (window.innerWidth <= 768) {
        const multiSelect = document.querySelector('select[multiple]');
        if (multiSelect) {
            multiSelect.addEventListener('touchstart', function() {
                this.setAttribute('size', Math.min(this.options.length, 8));
            });
        }
        
        // Gérer le bouton retour Android
        window.addEventListener('popstate', function() {
            const modal = document.querySelector('.modal.is-active');
            if (modal) {
                closeCreateModal();
            }
        });
    }
    
    // Prévenir la double soumission
    const createForm = document.getElementById('createActivityForm');
    if (createForm) {
        let isSubmitting = false;
        const submitButton = document.querySelector('button[onclick*="submitActivityForm"]');
        
        window.submitActivityForm = function() {
            if (isSubmitting) return;
            isSubmitting = true;
            
            if (submitButton) {
                submitButton.disabled = true;
                const originalHTML = submitButton.innerHTML;
                submitButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>En cours...';
                
                // S'assurer que le contenu de TinyMCE est sauvegardé
                if (typeof tinymce !== 'undefined' && tinymce.editors && Object.keys(tinymce.editors).length > 0) {
                    Object.values(tinymce.editors).forEach(editor => {
                        editor.save();
                    });
                }
                
                const form = document.getElementById('createActivityForm');
                const formData = new FormData(form);
                
                // Ajouter les IDs des fichiers à supprimer
                if (editingActivityId && (filesToDelete.images.length > 0 || filesToDelete.files.length > 0 || filesToDelete.videos.length > 0)) {
                    console.log('Fichiers à supprimer:', filesToDelete);
                    formData.append('delete_images', JSON.stringify(filesToDelete.images));
                    formData.append('delete_files', JSON.stringify(filesToDelete.files));
                    formData.append('delete_videos', JSON.stringify(filesToDelete.videos));
                }
                
                const url = editingActivityId 
                    ? `{% url 'app:update_dashboard_activity' 0 %}`.replace('0', editingActivityId)
                    : `{% url 'app:create_dashboard_activity' %}`;
                
                console.log('URL:', url);
                console.log('Mode édition:', editingActivityId);
                
                fetch(url, {
                    method: 'POST',
                    body: formData,
                    headers: { 'X-CSRFToken': '{{ csrf_token }}' }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('Erreur: ' + (data.message || 'Une erreur est survenue'));
                        isSubmitting = false;
                        submitButton.disabled = false;
                        submitButton.innerHTML = originalHTML;
                    }
                })
                .catch(error => {
                    console.error('Erreur:', error);
                    alert('Une erreur est survenue');
                    isSubmitting = false;
                    submitButton.disabled = false;
                    submitButton.innerHTML = originalHTML;
                });
            }
        };
    }
    
    // Raccourcis clavier
    document.addEventListener('keydown', function(e) {
        // ESC pour fermer le modal
        if (e.key === 'Escape') {
            const modal = document.querySelector('.modal.is-active');
            if (modal) {
                closeCreateModal();
            }
        }
        
        // Ctrl+F pour focus sur la recherche
        if (e.ctrlKey && e.key === 'f') {
            e.preventDefault();
            document.getElementById('searchInput').focus();
        }
    });
});
</script>
{% endblock %}
