add_shortcode('agenda_auto', function() {
    $dir = '/var/www/html/wp-content/uploads/';
    $files = glob($dir . "*.ics");
    if (!$files) return "Aucun fichier calendrier trouvé.";

    usort($files, function($a, $b) { return filemtime($b) - filemtime($a); });

    $ics_content = file_get_contents($files[0]);
    // On nettoie les caractères qui cassent le Javascript
    $ics_content_safe = base64_encode($ics_content);

    return '
    <script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.8/index.global.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@fullcalendar/icalendar@6.1.8/index.global.min.js"></script>
    
    <div id="calendar-auto" style="height: 700px; background: white; padding: 10px; border: 1px solid #ddd;"></div>
    
    <script>
      document.addEventListener("DOMContentLoaded", function() {
        var icsData = atob("' . $ics_content_safe . '");
        var calendarEl = document.getElementById("calendar-auto");
        var calendar = new FullCalendar.Calendar(calendarEl, {
          initialView: "dayGridMonth",
          locale: "fr",
          headerToolbar: { left: "prev,next today", center: "title", right: "dayGridMonth,listMonth" },
          events: {
            ics: icsData,
            format: "ics"
          },
          eventSourceSuccess: function() { console.log("ICS chargé avec succès"); },
          eventSourceFailure: function() { alert("Erreur de lecture des événements dans le fichier ICS"); }
        });
        calendar.render();
      });
    </script>';
});