<?php
require_once('../../config.php');
require_once($CFG->libdir . '/filelib.php');
require_once(__DIR__ . '/lib.php');

$slidername = optional_param('slider', 'default', PARAM_TEXT);

// Permitir iframe de qualquer origem
header('X-Frame-Options: ALLOWALL');
header('Content-Type: text/html; charset=utf-8');
header('Access-Control-Allow-Origin: *');

// Carregar imagens do slider
$images = local_slider_get_slider_images($slidername);

?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Slider: <?php echo ucfirst($slidername); ?></title>
    
    <!-- Bootstrap e Font Awesome do Moodle -->
    <link rel="stylesheet" href="<?php echo $CFG->wwwroot; ?>/theme/bootstrap/style/bootstrap.css">
    <link rel="stylesheet" href="<?php echo $CFG->wwwroot; ?>/theme/fontawesome/fontawesome.css">
    
    <!-- CSS do Slider Original (MESMO DO INDEX) -->
    <link rel="stylesheet" href="<?php echo $CFG->wwwroot; ?>/local/slider/styles.css">
    
    <style>
        /* RESET para iframe - RESPONSIVO */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            margin: 0;
            padding: 0;
            background: transparent;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            overflow: hidden;
            width: 100%;
            height: 100%;
            min-height: 300px; /* Altura mínima menor para mobile */
        }
        
        /* Container principal - RESPONSIVO */
        .local-slider-container {
            width: 100%;
            height: 100%;
            padding: 10px; /* Padding menor para mobile */
            margin: 0;
            position: relative;
        }
        
        /* Container do slider - RESPONSIVO COMO NO INDEX */
        .slider-container {
            width: 100%;
            height: 100%;
            max-width: 100%;
            margin: 0 auto;
            position: relative;
            overflow: hidden;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            background: #f8f9fa;
            min-height: 300px; /* Menor para mobile */
        }
        
        /* Ajustes específicos para iframe - RESPONSIVO */
        .slider-wrapper {
            height: 100%;
            width: 100%;
        }
        
        .slider-image {
            max-height: 100%;
            max-width: 100%;
            width: auto;
            height: auto;
            object-fit: contain;
            display: block;
            margin: 0 auto;
        }
        
        /* CONTROLES SEMPRE VISÍVEIS NO IFRAME (mas responsivos) */
        .slider-controls, .vertical-controls {
            opacity: 1 !important;
            visibility: visible !important;
            display: flex !important;
        }
        
        .slider-dots, .slide-counter {
            opacity: 1 !important;
            visibility: visible !important;
            display: block !important;
        }
        
        /* Lightbox RESPONSIVO */
        .lightbox {
            display: none;
            position: fixed;
            z-index: 9999;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.95);
            overflow: auto;
        }
        
        .lightbox-content {
            position: relative;
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        
        .close-lightbox {
            position: absolute;
            top: 15px; /* Menor para mobile */
            right: 20px; /* Menor para mobile */
            color: #fff;
            font-size: 35px; /* Menor para mobile */
            font-weight: bold;
            cursor: pointer;
            z-index: 10000;
            background: rgba(0,0,0,0.5);
            width: 45px; /* Menor para mobile */
            height: 45px; /* Menor para mobile */
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            line-height: 1;
        }
        
        .lightbox-image-container {
            width: 95%;
            height: 85%;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: auto;
        }
        
        .lightbox-image {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
            transition: transform 0.3s ease;
        }
        
        .lightbox-controls {
            position: absolute;
            bottom: 15px; /* Menor para mobile */
            left: 0;
            width: 100%;
            text-align: center;
            padding: 10px; /* Menor para mobile */
            background: rgba(0,0,0,0.7);
            display: flex;
            justify-content: center;
            gap: 8px; /* Menor para mobile */
            flex-wrap: wrap;
        }
        
        .lightbox-counter {
            color: white;
            font-size: 14px; /* Menor para mobile */
            padding: 8px 16px; /* Menor para mobile */
            background: rgba(0,0,0,0.5);
            border-radius: 20px;
            margin-bottom: 8px; /* Menor para mobile */
        }
        
        /* BOTÃO PLAY/PAUSE CENTRAL - RESPONSIVO */
        .play-pause-container {
            position: absolute;
            bottom: 15px; /* Menor para mobile */
            left: 50%;
            transform: translateX(-50%);
            z-index: 100;
        }
        
        .play-pause-btn {
            width: 50px; /* Menor para mobile */
            height: 50px; /* Menor para mobile */
            border-radius: 50%;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto;
        }
        
        .autoplay-status {
            color: white;
            font-size: 11px; /* Menor para mobile */
            margin-top: 6px; /* Menor para mobile */
            text-align: center;
            text-shadow: 0 1px 2px rgba(0,0,0,0.5);
        }
        
        /* MENSAGEM DE ERRO */
        .embed-message {
            text-align: center;
            padding: 30px; /* Menor para mobile */
            color: #666;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100%;
        }
        
        /* BOTÕES DE MODO - RESPONSIVOS */
        .view-toggle {
            text-align: center;
            margin-bottom: 10px; /* Menor para mobile */
            padding: 0 5px;
        }
        
        .view-toggle .btn {
            min-width: 80px; /* Menor para mobile */
            font-size: 14px; /* Menor para mobile */
            padding: 6px 12px; /* Menor para mobile */
        }
        
        /* RESPONSIVIDADE ESPECÍFICA PARA IFRAME */
        @media (max-width: 768px) {
            body {
                min-height: 250px;
            }
            
            .local-slider-container {
                padding: 5px;
            }
            
            .slider-container {
                min-height: 250px;
                border-radius: 8px;
            }
            
            .slider-controls button, .vertical-controls button {
                width: 40px;
                height: 40px;
                font-size: 16px;
            }
            
            .play-pause-btn {
                width: 45px;
                height: 45px;
            }
            
            .lightbox-controls button {
                padding: 6px 10px;
                font-size: 14px;
                min-width: 40px;
            }
            
            .close-lightbox {
                top: 10px;
                right: 15px;
                font-size: 30px;
                width: 40px;
                height: 40px;
            }
            
            .lightbox-image-container {
                width: 98%;
                height: 75%;
            }
            
            .dot {
                width: 10px;
                height: 10px;
                margin: 0 5px;
            }
            
            .slide-counter {
                bottom: 10px;
                right: 10px;
                font-size: 12px;
                padding: 3px 10px;
            }
            
            .view-toggle .btn {
                min-width: 70px;
                font-size: 13px;
                padding: 5px 10px;
            }
        }
        
        @media (max-width: 480px) {
            body {
                min-height: 200px;
            }
            
            .slider-container {
                min-height: 200px;
                border-radius: 6px;
            }
            
            .slider-controls button, .vertical-controls button {
                width: 35px;
                height: 35px;
                font-size: 14px;
            }
            
            .play-pause-btn {
                width: 40px;
                height: 40px;
            }
            
            .autoplay-status {
                font-size: 10px;
            }
            
            .close-lightbox {
                top: 8px;
                right: 10px;
                font-size: 28px;
                width: 35px;
                height: 35px;
            }
            
            .lightbox-controls button {
                padding: 5px 8px;
                font-size: 12px;
                min-width: 35px;
            }
            
            .view-toggle .btn {
                min-width: 65px;
                font-size: 12px;
                padding: 4px 8px;
            }
        }
        
        @media (min-width: 769px) and (max-width: 1024px) {
            .slider-container {
                min-height: 350px;
            }
            
            .view-toggle .btn {
                min-width: 90px;
                font-size: 15px;
            }
        }
        
        @media (min-width: 1025px) {
            .slider-container {
                min-height: 400px;
            }
            
            .view-toggle .btn {
                min-width: 100px;
                font-size: 16px;
            }
        }
        
        /* Ajuste automático de altura */
        .auto-height {
            height: auto !important;
        }
    </style>
</head>
<body>
    <?php if (empty($images)): ?>
        <div class="embed-message">
            <i class="fa fa-images"></i>
            <h3>Slider não disponível</h3>
            <p>O slider "<?php echo ucfirst($slidername); ?>" está vazio ou não foi encontrado.</p>
        </div>
    <?php else: ?>
        <!-- SLIDER RESPONSIVO -->
        <div class="local-slider-container">
            
            <!-- BOTÕES DE MODO (GALERIA/SLIDER) - RESPONSIVOS -->
            <div class="view-toggle">
                <div class="btn-group" role="group">
                    <button type="button" class="btn btn-primary" onclick="setView('slider')">
                        <i class="fa fa-sliders-h"></i> Slider
                    </button>
                    <button type="button" class="btn btn-outline-primary" onclick="setView('gallery')">
                        <i class="fa fa-th-large"></i> Galeria
                    </button>
                </div>
            </div>
            
            <!-- MODO SLIDER (VISÍVEL POR PADRÃO) -->
            <div id="slider-view">
                <div class="slider-container" id="main-slider-container">
                    <div class="slider-wrapper" id="slider-wrapper">
                        
                        <?php foreach ($images as $index => $image): ?>
                            <?php $active = $index === 0 ? ' active' : ''; ?>
                            <div class="slide<?php echo $active; ?>" data-slide="<?php echo $index; ?>">
                                <div class="slide-content">
                                    <img src="<?php echo s($image['url']); ?>" 
                                         alt="<?php echo s($image['name']); ?>" 
                                         class="slider-image" 
                                         onclick="openLightbox(<?php echo $index; ?>)" 
                                         style="cursor: zoom-in;"
                                         loading="lazy">
                                </div>
                            </div>
                        <?php endforeach; ?>
                        
                        <?php if (count($images) > 1): ?>
                            <!-- CONTROLES RESPONSIVOS -->
                            <div class="slider-controls" id="horizontal-controls">
                                <button class="btn btn-dark prev-btn" onclick="prevSlide()" title="Anterior (←)">
                                    <i class="fa fa-chevron-left"></i>
                                </button>
                                <button class="btn btn-dark next-btn" onclick="nextSlide()" title="Próximo (→)">
                                    <i class="fa fa-chevron-right"></i>
                                </button>
                            </div>
                            
                            <div class="vertical-controls" id="vertical-controls">
                                <button class="btn btn-dark up-btn" onclick="prevSlide()" title="Anterior (↑)">
                                    <i class="fa fa-chevron-up"></i>
                                </button>
                                <button class="btn btn-dark down-btn" onclick="nextSlide()" title="Próximo (↓)">
                                    <i class="fa fa-chevron-down"></i>
                                </button>
                            </div>
                            
                            <!-- NAVEGAÇÃO RESPONSIVA -->
                            <div class="slider-dots" id="slider-dots">
                                <?php foreach ($images as $index => $image): ?>
                                    <?php $active = $index === 0 ? ' active' : ''; ?>
                                    <span class="dot<?php echo $active; ?>" 
                                          data-slide="<?php echo $index; ?>" 
                                          onclick="goToSlide(<?php echo $index; ?>)" 
                                          title="Slide <?php echo ($index + 1); ?>"></span>
                                <?php endforeach; ?>
                            </div>
                            
                            <!-- CONTADOR RESPONSIVO -->
                            <div class="slide-counter" id="slide-counter">
                                <span id="current-slide">1</span> / <span id="total-slides"><?php echo count($images); ?></span>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- BOTÃO PLAY/PAUSE RESPONSIVO -->
                <?php if (count($images) > 1): ?>
                    <div class="play-pause-container text-center">
                        <div class="d-flex flex-column align-items-center">
                            <button class="btn btn-outline-primary play-pause-btn" onclick="toggleAutoSlide()" id="play-pause-btn">
                                <i class="fa fa-play fa-lg"></i>
                            </button>
                            <small class="autoplay-status" id="mode-status">Clique para iniciar slides automáticos</small>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- MODO GALERIA RESPONSIVA -->
            <div id="gallery-view" style="display: none;">
                <div class="gallery-container">
                    <div class="row">
                        <?php foreach ($images as $index => $image): ?>
                            <div class="col-md-4 col-sm-6 col-12 mb-3"> <!-- Adicionado col-12 para mobile -->
                                <div class="card h-100">
                                    <div class="card-body text-center p-2 d-flex align-items-center justify-content-center" style="min-height: 150px;">
                                        <img src="<?php echo s($image['url']); ?>" 
                                             alt="<?php echo s($image['name']); ?>" 
                                             class="gallery-image" 
                                             onclick="openLightbox(<?php echo $index; ?>)" 
                                             style="cursor: zoom-in;"
                                             loading="lazy">
                                    </div>
                                    <div class="card-footer py-2">
                                        <small class="text-muted text-truncate d-block"><?php echo s($image['name']); ?></small>
                                        <small class="text-muted"><?php echo $image['width']; ?>×<?php echo $image['height']; ?></small>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- LIGHTBOX RESPONSIVO -->
        <div id="lightbox" class="lightbox">
            <div class="lightbox-content">
                <span class="close-lightbox" onclick="closeLightbox()">&times;</span>
                <div class="lightbox-image-container" id="lightbox-image-container">
                    <img id="lightbox-img" src="" class="lightbox-image">
                </div>
                <div class="lightbox-controls">
                    <?php if (count($images) > 1): ?>
                        <div class="lightbox-counter" id="lightbox-counter"></div>
                    <?php endif; ?>
                    <div class="lightbox-tools">
                        <button onclick="lightboxZoomIn()" class="btn btn-light" title="Aumentar Zoom (+ ou =)">
                            <i class="fa fa-search-plus"></i>
                        </button>
                        <button onclick="lightboxZoomOut()" class="btn btn-light" title="Diminuir Zoom (-)">
                            <i class="fa fa-search-minus"></i>
                        </button>
                        <button onclick="lightboxRotate()" class="btn btn-light" title="Rotacionar 90° (R)">
                            <i class="fa fa-redo"></i>
                        </button>
                        <button onclick="closeLightbox()" class="btn btn-light" title="Fechar (ESC)">
                            <i class="fa fa-times"></i> Fechar
                        </button>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <?php if (!empty($images)): ?>
    <script>
        // ================================================
        // JAVASCRIPT RESPONSIVO
        // ================================================
        
        // Variáveis globais
        let currentSlide = 0;
        let slideInterval = null;
        let isPlaying = false;
        let currentDirection = "horizontal";
        let touchStartX = 0;
        let touchStartY = 0;
        let touchEndX = 0;
        let touchEndY = 0;
        const swipeThreshold = 50;
        let controlsTimeout = null;
        let isMouseOverSlider = false;
        const images = <?php echo json_encode($images); ?>;
        
        // Variáveis para o lightbox
        let currentZoom = 1;
        let currentRotation = 0;
        let currentImageIndex = 0;
        let lightboxTouchStartX = 0;
        let lightboxTouchStartY = 0;
        let lightboxTouchStartTime = 0;
        
        // Elementos DOM
        let horizontalControls, verticalControls, sliderDots, slideCounter, playPauseBtn, modeStatus;
        
        // Inicialização quando DOM carrega
        document.addEventListener("DOMContentLoaded", function() {
            // Obter elementos
            horizontalControls = document.getElementById("horizontal-controls");
            verticalControls = document.getElementById("vertical-controls");
            sliderDots = document.getElementById("slider-dots");
            slideCounter = document.getElementById("slide-counter");
            playPauseBtn = document.getElementById("play-pause-btn");
            modeStatus = document.getElementById("mode-status");
            const sliderContainer = document.getElementById("main-slider-container");
            
            // Inicializar slider
            initSlider();
            
            // Configurar eventos de mouse
            if (sliderContainer) {
                sliderContainer.addEventListener("mouseenter", function() {
                    isMouseOverSlider = true;
                });
                
                sliderContainer.addEventListener("mousemove", function() {
                    if (!isMouseOverSlider) {
                        isMouseOverSlider = true;
                    }
                });
                
                sliderContainer.addEventListener("mouseleave", function() {
                    isMouseOverSlider = false;
                });
                
                // Configurar eventos de touch
                setupTouchEvents(sliderContainer);
            }
            
            // Configurar eventos de touch para o lightbox
            setupLightboxTouchEvents();
            
            // Ajustar altura do iframe dinamicamente
            adjustIframeHeight();
            
            // Redimensionar quando a janela muda de tamanho
            window.addEventListener('resize', function() {
                adjustIframeHeight();
            });
            
            // Iniciar autoplay após 2 segundos
            setTimeout(() => {
                startAutoSlide();
            }, 2000);
        });
        
        // Ajustar altura do iframe dinamicamente
        function adjustIframeHeight() {
            const container = document.querySelector('.local-slider-container');
            if (container && window.parent) {
                // Obter altura real do conteúdo
                const height = container.scrollHeight;
                
                // Determinar altura mínima baseada no dispositivo
                let minHeight = 300; // default para desktop
                if (window.innerWidth <= 480) {
                    minHeight = 200; // mobile muito pequeno
                } else if (window.innerWidth <= 768) {
                    minHeight = 250; // tablet/mobile
                } else if (window.innerWidth <= 1024) {
                    minHeight = 350; // tablet landscape
                }
                
                // Usar a maior altura (conteúdo ou mínima)
                const finalHeight = Math.max(height, minHeight);
                
                // Notificar página pai sobre a altura
                window.parent.postMessage({
                    type: 'slider-height',
                    height: finalHeight,
                    slider: '<?php echo $slidername; ?>',
                    images: images.length,
                    viewportWidth: window.innerWidth
                }, '*');
                
                return finalHeight;
            }
            return 400;
        }
        
        // Configurar eventos de touch para o slider
        function setupTouchEvents(container) {
            container.addEventListener("touchstart", handleTouchStart, { passive: true });
            container.addEventListener("touchmove", handleTouchMove, { passive: true });
            container.addEventListener("touchend", handleTouchEnd);
        }
        
        // Configurar eventos de touch para o lightbox
        function setupLightboxTouchEvents() {
            const lightboxImageContainer = document.getElementById("lightbox-image-container");
            const lightbox = document.getElementById("lightbox");
            const lightboxImg = document.getElementById("lightbox-img");
            
            if (lightbox) {
                lightbox.addEventListener("touchstart", handleLightboxTouchStart, { passive: true });
                lightbox.addEventListener("touchend", handleLightboxTouchEnd, { passive: true });
            }
            
            if (lightboxImg) {
                lightboxImg.addEventListener("touchstart", handleLightboxTouchStart, { passive: true });
                lightboxImg.addEventListener("touchend", handleLightboxTouchEnd, { passive: true });
            }
        }
        
        // Funções de touch
        function handleTouchStart(event) {
            touchStartX = event.touches[0].clientX;
            touchStartY = event.touches[0].clientY;
        }
        
        function handleTouchMove(event) {
            touchEndX = event.touches[0].clientX;
            touchEndY = event.touches[0].clientY;
        }
        
        function handleTouchEnd() {
            const dx = touchEndX - touchStartX;
            const dy = touchEndY - touchStartY;
            
            if (Math.abs(dx) > Math.abs(dy)) {
                if (Math.abs(dx) > swipeThreshold) {
                    if (dx > 0) {
                        prevSlide();
                    } else {
                        nextSlide();
                    }
                }
            } else {
                if (Math.abs(dy) > swipeThreshold) {
                    if (currentDirection === "vertical") {
                        if (dy > 0) {
                            prevSlide();
                        } else {
                            nextSlide();
                        }
                    }
                }
            }
        }
        
        function handleLightboxTouchStart(event) {
            lightboxTouchStartX = event.touches[0].clientX;
            lightboxTouchStartY = event.touches[0].clientY;
            lightboxTouchStartTime = Date.now();
            event.stopPropagation();
        }
        
        function handleLightboxTouchEnd(event) {
            const lightboxTouchEndX = event.changedTouches[0].clientX;
            const lightboxTouchEndY = event.changedTouches[0].clientY;
            const dx = lightboxTouchEndX - lightboxTouchStartX;
            const dy = lightboxTouchEndY - lightboxTouchStartY;
            const timeElapsed = Date.now() - lightboxTouchStartTime;
            
            if (timeElapsed < 100) return;
            
            const distance = Math.sqrt(dx * dx + dy * dy);
            if (distance < 40) return;
            
            const isHorizontalSwipe = Math.abs(dx) > Math.abs(dy);
            
            if (isHorizontalSwipe) {
                if (Math.abs(dx) > swipeThreshold) {
                    if (dx > 0) {
                        lightboxPrev();
                    } else {
                        lightboxNext();
                    }
                    event.preventDefault();
                }
            } else {
                if (Math.abs(dy) > swipeThreshold) {
                    if (dy > 0) {
                        lightboxPrev();
                    } else {
                        lightboxNext();
                    }
                    event.preventDefault();
                }
            }
            
            event.stopPropagation();
        }
        
        // Função para alternar entre modos
        function setView(view) {
            const sliderView = document.getElementById("slider-view");
            const galleryView = document.getElementById("gallery-view");
            const sliderBtn = document.querySelector('button[onclick="setView(\'slider\')"]');
            const galleryBtn = document.querySelector('button[onclick="setView(\'gallery\')"]');
            
            if (view === "slider") {
                sliderView.style.display = "block";
                galleryView.style.display = "none";
                sliderBtn.className = "btn btn-primary";
                galleryBtn.className = "btn btn-outline-primary";
                initSlider();
                setTimeout(adjustIframeHeight, 100); // Ajustar altura após mudar view
            } else {
                sliderView.style.display = "none";
                galleryView.style.display = "block";
                sliderBtn.className = "btn btn-outline-primary";
                galleryBtn.className = "btn btn-primary";
                stopAutoSlide();
                setTimeout(adjustIframeHeight, 100); // Ajustar altura após mudar view
            }
        }
        
        // Inicializar slider
        function initSlider() {
            const slides = document.querySelectorAll(".slide");
            const dots = document.querySelectorAll(".dot");
            
            if (slides.length === 0) return;
            
            currentSlide = 0;
            
            slides.forEach((slide, index) => {
                slide.classList.remove("active");
                slide.style.display = "none";
                slide.style.opacity = "0";
            });
            
            dots.forEach((dot, index) => {
                dot.classList.remove("active");
            });
            
            if (slides[0]) {
                slides[0].classList.add("active");
                slides[0].style.display = "flex";
                setTimeout(() => {
                    slides[0].style.opacity = "1";
                }, 50);
            }
            
            if (dots[0]) {
                dots[0].classList.add("active");
            }
            
            updateSlideCounter();
            updatePlayPauseButton();
        }
        
        // Ir para slide específico
        function goToSlide(n) {
            const slides = document.querySelectorAll(".slide");
            const dots = document.querySelectorAll(".dot");
            
            if (slides.length === 0) return;
            
            const oldSlide = currentSlide;
            currentSlide = n;
            if (currentSlide >= slides.length) currentSlide = 0;
            if (currentSlide < 0) currentSlide = slides.length - 1;
            
            const isNext = currentSlide > oldSlide || (currentSlide === 0 && oldSlide === slides.length - 1);
            
            if (currentDirection === "fade") {
                // Efeito fade
                slides.forEach((slide, index) => {
                    if (slide.classList.contains("active")) {
                        slide.style.opacity = "0";
                        setTimeout(() => {
                            slide.style.display = "none";
                            slide.classList.remove("active");
                        }, 500);
                    }
                });
                
                setTimeout(() => {
                    const newSlide = slides[currentSlide];
                    if (newSlide) {
                        newSlide.style.display = "flex";
                        newSlide.classList.add("active");
                        setTimeout(() => {
                            newSlide.style.opacity = "1";
                        }, 50);
                    }
                }, 500);
            } else {
                // Efeito slide
                const oldActive = document.querySelector(".slide.active");
                const newSlide = slides[currentSlide];
                
                if (oldActive && newSlide) {
                    let oldTranslate, newTranslate;
                    
                    if (currentDirection === "vertical") {
                        oldTranslate = isNext ? "-100%" : "100%";
                        newTranslate = isNext ? "100%" : "-100%";
                        
                        oldActive.style.transform = `translateY(${oldTranslate})`;
                        newSlide.style.transform = `translateY(${newTranslate})`;
                    } else {
                        oldTranslate = isNext ? "-100%" : "100%";
                        newTranslate = isNext ? "100%" : "-100%";
                        
                        oldActive.style.transform = `translateX(${oldTranslate})`;
                        newSlide.style.transform = `translateX(${newTranslate})`;
                    }
                    
                    oldActive.style.opacity = "0";
                    newSlide.style.opacity = "1";
                    newSlide.style.display = "flex";
                    
                    setTimeout(() => {
                        oldActive.style.transform = "translate(0)";
                        newSlide.style.transform = "translate(0)";
                        
                        setTimeout(() => {
                            oldActive.classList.remove("active");
                            oldActive.style.display = "none";
                            newSlide.classList.add("active");
                        }, 500);
                    }, 10);
                }
            }
            
            // Atualizar dots
            dots.forEach(dot => {
                dot.classList.remove("active");
            });
            if (dots[currentSlide]) {
                dots[currentSlide].classList.add("active");
            }
            
            // Atualizar contador
            updateSlideCounter();
            
            // Ajustar altura do iframe
            setTimeout(adjustIframeHeight, 50);
        }
        
        function nextSlide() {
            goToSlide(currentSlide + 1);
        }
        
        function prevSlide() {
            goToSlide(currentSlide - 1);
        }
        
        function updateSlideCounter() {
            const currentEl = document.getElementById("current-slide");
            const totalEl = document.getElementById("total-slides");
            if (currentEl) currentEl.textContent = currentSlide + 1;
            if (totalEl) totalEl.textContent = images.length;
        }
        
        // Autoplay
        function startAutoSlide() {
            const slides = document.querySelectorAll(".slide");
            if (slides.length > 1 && !slideInterval) {
                slideInterval = setInterval(nextSlide, 5000);
                isPlaying = true;
                updatePlayPauseButton();
            }
        }
        
        function stopAutoSlide() {
            if (slideInterval) {
                clearInterval(slideInterval);
                slideInterval = null;
                isPlaying = false;
                updatePlayPauseButton();
            }
        }
        
        function toggleAutoSlide() {
            const slides = document.querySelectorAll(".slide");
            if (slides.length <= 1) return;
            
            isPlaying = !isPlaying;
            
            if (isPlaying) {
                startAutoSlide();
            } else {
                stopAutoSlide();
            }
            
            updatePlayPauseButton();
        }
        
        function updatePlayPauseButton() {
            if (playPauseBtn) {
                if (isPlaying) {
                    playPauseBtn.innerHTML = '<i class="fa fa-pause fa-lg"></i>';
                    playPauseBtn.title = "Pausar slides automáticos";
                    playPauseBtn.classList.remove("btn-outline-primary");
                    playPauseBtn.classList.add("btn-primary");
                    if (modeStatus) {
                        modeStatus.textContent = "Slides automáticos ativos (5 segundos)";
                    }
                } else {
                    playPauseBtn.innerHTML = '<i class="fa fa-play fa-lg"></i>';
                    playPauseBtn.title = "Iniciar slides automáticos";
                    playPauseBtn.classList.remove("btn-primary");
                    playPauseBtn.classList.add("btn-outline-primary");
                    if (modeStatus) {
                        modeStatus.textContent = "Clique para iniciar slides automáticos";
                    }
                }
            }
        }
        
        // Lightbox
        function openLightbox(index) {
            const lightbox = document.getElementById("lightbox");
            const lightboxImg = document.getElementById("lightbox-img");
            
            if (images && images[index]) {
                currentImageIndex = index;
                lightboxImg.src = images[index].url;
                lightbox.style.display = "block";
                document.body.style.overflow = "hidden";
                
                currentZoom = 1;
                currentRotation = 0;
                updateLightboxImage();
                updateLightboxCounter();
                
                const lightboxCounter = document.getElementById("lightbox-counter");
                if (lightboxCounter) {
                    lightboxCounter.style.display = images.length > 1 ? "block" : "none";
                }
            }
        }
        
        function closeLightbox() {
            document.getElementById("lightbox").style.display = "none";
            document.body.style.overflow = "auto";
        }
        
        function lightboxPrev() {
            if (images.length <= 1) return;
            
            currentImageIndex--;
            if (currentImageIndex < 0) {
                currentImageIndex = images.length - 1;
            }
            
            const lightboxImg = document.getElementById("lightbox-img");
            lightboxImg.style.opacity = "0.5";
            lightboxImg.style.transform = "translateX(20px) scale(" + currentZoom + ") rotate(" + currentRotation + "deg)";
            
            setTimeout(() => {
                lightboxImg.src = images[currentImageIndex].url;
                currentZoom = 1;
                currentRotation = 0;
                updateLightboxImage();
                updateLightboxCounter();
                
                lightboxImg.style.opacity = "0";
                lightboxImg.style.transform = "translateX(-20px) scale(" + currentZoom + ") rotate(" + currentRotation + "deg)";
                
                setTimeout(() => {
                    lightboxImg.style.opacity = "1";
                    lightboxImg.style.transform = "translateX(0) scale(" + currentZoom + ") rotate(" + currentRotation + "deg)";
                }, 10);
            }, 200);
        }
        
        function lightboxNext() {
            if (images.length <= 1) return;
            
            currentImageIndex++;
            if (currentImageIndex >= images.length) {
                currentImageIndex = 0;
            }
            
            const lightboxImg = document.getElementById("lightbox-img");
            lightboxImg.style.opacity = "0.5";
            lightboxImg.style.transform = "translateX(-20px) scale(" + currentZoom + ") rotate(" + currentRotation + "deg)";
            
            setTimeout(() => {
                lightboxImg.src = images[currentImageIndex].url;
                currentZoom = 1;
                currentRotation = 0;
                updateLightboxImage();
                updateLightboxCounter();
                
                lightboxImg.style.opacity = "0";
                lightboxImg.style.transform = "translateX(20px) scale(" + currentZoom + ") rotate(" + currentRotation + "deg)";
                
                setTimeout(() => {
                    lightboxImg.style.opacity = "1";
                    lightboxImg.style.transform = "translateX(0) scale(" + currentZoom + ") rotate(" + currentRotation + "deg)";
                }, 10);
            }, 200);
        }
        
        function updateLightboxCounter() {
            const lightboxCounter = document.getElementById("lightbox-counter");
            if (lightboxCounter) {
                lightboxCounter.textContent = (currentImageIndex + 1) + " / " + images.length;
            }
        }
        
        function lightboxZoomIn() {
            currentZoom += 0.2;
            updateLightboxImage();
        }
        
        function lightboxZoomOut() {
            if (currentZoom > 0.3) {
                currentZoom -= 0.2;
                updateLightboxImage();
            }
        }
        
        function lightboxRotate() {
            currentRotation += 90;
            updateLightboxImage();
        }
        
        function updateLightboxImage() {
            const lightboxImg = document.getElementById("lightbox-img");
            lightboxImg.style.transform = `scale(${currentZoom}) rotate(${currentRotation}deg)`;
            lightboxImg.style.transition = "transform 0.3s ease";
        }
        
        // Teclas de atalho
        document.addEventListener("keydown", function(e) {
            const lightbox = document.getElementById("lightbox");
            
            if (lightbox.style.display === "block") {
                if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
                    lightboxPrev();
                    e.preventDefault();
                } else if (e.key === "ArrowRight" || e.key === "ArrowDown") {
                    lightboxNext();
                    e.preventDefault();
                } else if (e.key === "Escape") {
                    closeLightbox();
                    e.preventDefault();
                } else if (e.key === "+" || e.key === "=") {
                    lightboxZoomIn();
                    e.preventDefault();
                } else if (e.key === "-") {
                    lightboxZoomOut();
                    e.preventDefault();
                } else if (e.key === "r" || e.key === "R") {
                    lightboxRotate();
                    e.preventDefault();
                } else if (e.key === " ") {
                    lightboxNext();
                    e.preventDefault();
                }
            } else {
                if (e.key === "ArrowLeft") {
                    prevSlide();
                    e.preventDefault();
                } else if (e.key === "ArrowRight") {
                    nextSlide();
                    e.preventDefault();
                } else if (e.key === "ArrowUp" && currentDirection === "vertical") {
                    prevSlide();
                    e.preventDefault();
                } else if (e.key === "ArrowDown" && currentDirection === "vertical") {
                    nextSlide();
                    e.preventDefault();
                } else if (e.key === " ") {
                    toggleAutoSlide();
                    e.preventDefault();
                }
            }
        });
        
        // Ajustar altura quando as imagens carregarem
        window.addEventListener('load', function() {
            setTimeout(adjustIframeHeight, 500);
        });
        
        // Verificar altura periodicamente durante o carregamento
        let heightCheckInterval = setInterval(adjustIframeHeight, 200);
        setTimeout(() => {
            clearInterval(heightCheckInterval);
        }, 3000);
        
    </script>
    <?php endif; ?>
</body>
</html>