import './bootstrap';
import Alpine from 'alpinejs';
import Swiper from 'swiper/bundle'; // Use bundle to get all modules
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';

window.Alpine = Alpine;
window.Swiper = Swiper;
Alpine.start();

// Enhanced Global Toast Notification
window.showToast = function(message, type = 'info') {
    // Remove any existing notifications to prevent stacking
    document.querySelectorAll('.toast-notification').forEach(n => n.remove());

    const notification = document.createElement('div');
    notification.className = 'toast-notification fixed top-5 right-5 w-full max-w-sm bg-white shadow-2xl rounded-xl p-4 border-l-4 z-[1000]';

    const icons = { success: 'fa-check-circle', error: 'fa-exclamation-circle', info: 'fa-info-circle', warning: 'fa-exclamation-triangle' };
    const borderColors = { success: 'border-green-500', error: 'border-red-500', info: 'border-blue-500', warning: 'border-yellow-500' };
    const textColors = { success: 'text-green-500', error: 'text-red-500', info: 'text-blue-500', warning: 'text-yellow-500' };

    notification.classList.add(borderColors[type] || borderColors.info);

    notification.innerHTML = `
        <div class="flex items-start gap-4">
            <i class="fas ${icons[type] || icons.info} ${textColors[type] || textColors.info} text-2xl mt-1"></i>
            <div class="flex-1">
                <p class="font-bold text-gray-800">${type.charAt(0).toUpperCase() + type.slice(1)}</p>
                <p class="text-sm text-gray-600">${message}</p>
            </div>
            <button class="v-alert-close text-gray-400 hover:text-gray-600" onclick="this.closest('.toast-notification').remove()">&times;</button>
        </div>
        <div class="absolute bottom-0 left-0 h-1 bg-gray-200 rounded-bl-lg">
            <div class="h-1 ${borderColors[type] ? borderColors[type].replace('border', 'bg') : 'bg-blue-500'} rounded-bl-lg" style="width: 100%; animation: progress 4s linear forwards;"></div>
        </div>
    `;

    document.body.appendChild(notification);
    // Define keyframes if they don't exist
    if (!document.styleSheets[0].cssRules.namedItem('toast-in')) {
        document.styleSheets[0].insertRule('@keyframes toast-in { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }', document.styleSheets[0].cssRules.length);
        document.styleSheets[0].insertRule('@keyframes toast-out { from { transform: translateX(0); opacity: 1; } to { transform: translateX(100%); opacity: 0; } }', document.styleSheets[0].cssRules.length);
        document.styleSheets[0].insertRule('@keyframes progress { from { width: 100%; } to { width: 0%; } }', document.styleSheets[0].cssRules.length);
    }
    notification.style.animation = 'toast-in 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards';

    const close = () => {
        notification.style.animation = 'toast-out 0.5s ease-in forwards';
        notification.addEventListener('animationend', () => notification.remove(), { once: true });
    };

    setTimeout(close, 4000);
};

// Initialize Swiper sliders on DOMContentLoaded
document.addEventListener('DOMContentLoaded', function() {
    // Swiper for the home page content slider
    if (document.querySelector('.mySwiper')) {
        new Swiper(".mySwiper", {
            loop: true,
            autoplay: {
                delay: 3000,
                disableOnInteraction: false,
            },
            pagination: {
                el: ".swiper-pagination",
                clickable: true,
            },
            navigation: {
                nextEl: ".swiper-button-next",
                prevEl: ".swiper-button-prev",
            },
        });
    }
});

// Custom Carousel for the main hero section
document.addEventListener('DOMContentLoaded', function () {
    const track = document.getElementById('carousel-track');
    const slides = document.querySelectorAll('.carousel-slide');
    const dots = document.querySelectorAll('.carousel-dot');
    const prevBtn = document.getElementById('prev-btn');
    const nextBtn = document.getElementById('next-btn');

    if (!track || !prevBtn || !nextBtn || slides.length === 0) return;

    let currentIndex = 0;
    const totalSlides = slides.length;
    let autoSlideInterval;

    // Update carousel position and active dot
    function updateCarousel() {
        const translateX = -currentIndex * 100;
        track.style.transform = `translate3d(${translateX}%, 0px, 0px)`;

        // Update active dot
        dots.forEach((dot, index) => {
            if (index === currentIndex) {
                dot.classList.add('active');
            } else {
                dot.classList.remove('active');
            }
        });
    }

    // Auto slide every 5 seconds
    function startAutoSlide() {
        autoSlideInterval = setInterval(function () {
            currentIndex = (currentIndex + 1) % totalSlides;
            updateCarousel();
        }, 5000);
    }

    function resetAutoSlide() {
        clearInterval(autoSlideInterval);
        startAutoSlide();
    }

    // Next button event
    nextBtn.addEventListener('click', function () {
        resetAutoSlide();
        currentIndex = (currentIndex + 1) % totalSlides;
        updateCarousel();
    });

    // Previous button event
    prevBtn.addEventListener('click', function () {
        resetAutoSlide();
        currentIndex = (currentIndex - 1 + totalSlides) % totalSlides;
        updateCarousel();
    });

    // Dot navigation events
    dots.forEach((dot, index) => {
        dot.addEventListener('click', function () {
            resetAutoSlide();
            currentIndex = index;
            updateCarousel();
        });
    });

    // Initialize
    updateCarousel();
    startAutoSlide();
});
