import './app.scss';
import * as Turbo from "@hotwired/turbo";
import * as Sentry from "@sentry/browser";
import AOS from 'aos';
import 'aos/dist/aos.css';

// --- INITIALISATION SENTRY ---
// On initialise Sentry immédiatement sans attendre le DOM pour capturer les erreurs précoces
Sentry.init({
    dsn: "https://803814be6540031b1c37bf92ba9c0f79@sentry.esy-web.dev/24",
    tunnel: "/sentry-tunnel",
    integrations: [
        Sentry.browserTracingIntegration(),
        Sentry.replayIntegration()
    ],
    tracesSampleRate: 1.0,
    replaysSessionSampleRate: 0.1,
    replaysOnErrorSampleRate: 1.0
});

/**
 * Initialisation globale des composants UI
 * Appelée à chaque navigation Turbo
 */
const initApp = () => {
    // Flash Messages Auto-hide
    document.querySelectorAll('.flash-message').forEach(flash => {
        setTimeout(() => {
            flash.classList.add('opacity-0', 'translate-y-2');
            setTimeout(() => flash.remove(), 500);
        }, 5000);
    });

    // Initialize AOS
    AOS.init({
        duration: 800,
        once: true,
        // offset: 120, // Optional: offset (in px) from the original trigger point
        // easing: 'ease', // Optional: default easing for AOS animations
    });
    
    // Exemple : Init d'un bouton de retour en haut de page
    // initBackToTop();
};

// --- TURBO HOOKS ---

// 'turbo:load' s'exécute au chargement initial ET à chaque navigation
document.addEventListener('turbo:load', () => {
    initApp();
});

// Gestion des confirmations de suppression ou d'actions sensibles via Turbo
document.addEventListener("turbo:click", (event) => {
    const confirmationMsg = event.target.closest("[data-turbo-confirm]")?.getAttribute("data-turbo-confirm");
    if (confirmationMsg && !confirm(confirmationMsg)) {
        event.preventDefault();
    }
});

// Capture des erreurs de rendu Turbo dans Sentry
document.addEventListener("turbo:render", () => {
    Sentry.addBreadcrumb({
        category: "turbo",
        message: "Page rendered: " + window.location.pathname,
        level: "info",
    });
});
