<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Galeri Kegiatan | Efata Gemilang Jaya</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        * {
            font-family: 'Plus Jakarta Sans', sans-serif;
            scroll-behavior: smooth;
        }

        body {
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        }

        /* Saat lightbox terbuka, scroll di disable */
        body.lightbox-open {
            overflow: hidden;
            position: fixed;
            width: 100%;
            height: 100%;
        }

        .text-gradient {
            background: linear-gradient(135deg, #1e2b3a 0%, #C5A028 100%);
            background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        /* Gallery Grid */
        .gallery-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 1.2rem;
        }

        @media (min-width: 768px) {
            .gallery-grid {
                grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
                gap: 1.5rem;
            }
        }

        .gallery-card {
            background: white;
            border: 1px solid rgba(212, 175, 55, 0.15);
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            border-radius: 1.5rem;
            overflow: hidden;
            cursor: pointer;
        }

        @media (min-width: 768px) {
            .gallery-card {
                border-radius: 2rem;
            }
        }

        .gallery-card:hover {
            border-color: #C5A028;
            transform: translateY(-5px);
            box-shadow: 0 20px 40px -15px rgba(30, 43, 58, 0.15);
        }

        .gallery-img-container {
            position: relative;
            overflow: hidden;
            aspect-ratio: 4 / 3;
            background-color: #E6D5B8;
        }

        .gallery-img {
            transition: transform 0.6s cubic-bezier(0.4, 0, 0.2, 1);
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .gallery-card:hover .gallery-img {
            transform: scale(1.08);
        }

        /* Pagination Styles */
        .pagination-item {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 2.5rem;
            height: 2.5rem;
            border-radius: 0.75rem;
            font-weight: 600;
            transition: all 0.2s ease;
            cursor: pointer;
            background-color: white;
            color: #1e2b3a;
            border: 1px solid rgba(212, 175, 55, 0.3);
        }

        .pagination-item:hover {
            background-color: #E6D5B8;
            border-color: #C5A028;
            transform: translateY(-2px);
        }

        .pagination-item.active {
            background-color: #1e2b3a;
            color: white;
            border-color: #1e2b3a;
        }

        .pagination-item.disabled {
            opacity: 0.5;
            cursor: not-allowed;
            pointer-events: none;
        }

        /* LIGHTBOX - DIPERBAIKI */
        .lightbox {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            z-index: 9999;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .lightbox.active {
            opacity: 1;
            visibility: visible;
        }

        .lightbox-content {
            position: relative;
            background: white;
            padding: 20px;
            border-radius: 20px;
            max-width: 85%;
            width: auto;
            min-width: 250px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
            cursor: default;
        }

        .lightbox-image {
            max-width: 100%;
            max-height: 75vh;
            width: auto;
            height: auto;
            object-fit: contain;
            border-radius: 12px;
        }

        .lightbox-close {
            position: absolute;
            top: -18px;
            right: -18px;
            background: #1e2b3a;
            border: none;
            color: white;
            font-size: 20px;
            cursor: pointer;
            transition: all 0.2s;
            width: 38px;
            height: 38px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        }

        .lightbox-close:hover {
            background: #C5A028;
            transform: scale(1.1);
        }

        .lightbox-title {
            margin-top: 15px;
            font-size: 14px;
            font-weight: 600;
            color: #1e2b3a;
            text-align: center;
            max-width: 100%;
            word-break: break-word;
            padding: 0 8px;
        }

        /* Responsive untuk mobile */
        @media (max-width: 640px) {
            .lightbox-content {
                padding: 15px;
                border-radius: 16px;
                max-width: 90%;
            }

            .lightbox-image {
                max-height: 60vh;
            }

            .lightbox-close {
                top: -12px;
                right: -12px;
                width: 32px;
                height: 32px;
                font-size: 18px;
            }

            .lightbox-title {
                font-size: 12px;
                margin-top: 10px;
            }
        }

        /* Mobile menu styles */
        .mobile-menu {
            transition: all 0.3s ease-in-out;
        }

        .hamburger-line {
            transition: all 0.3s ease;
        }

        .mobile-menu.open {
            opacity: 1;
            visibility: visible;
            transform: translateY(0);
        }

        .mobile-menu.closed {
            opacity: 0;
            visibility: hidden;
            transform: translateY(-10px);
        }

        /* Glass Navbar */
        .glass-nav {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(16px) saturate(180%);
            -webkit-backdrop-filter: blur(16px) saturate(180%);
            border-bottom: 1px solid rgba(212, 175, 55, 0.15);
        }
    </style>
</head>

<body class="text-slate-700 antialiased">

    <?php include '../components/header.php'; ?>

    <!-- HEADER GALERI -->
    <header class="max-w-7xl mx-auto px-6 pt-16 md:pt-20 pb-10 md:pb-12 text-center">
        <span class="px-3 md:px-4 py-1.5 bg-[#C5A028]/10 text-[#C5A028] text-xs font-bold uppercase tracking-widest rounded-full border border-[#C5A028]/20">Dokumentasi Kegiatan</span>
        <h1 class="text-3xl md:text-6xl font-extrabold text-[#1e2b3a] mt-4 md:mt-6 mb-3 md:mb-4">Galeri <span class="text-gradient">Kebersamaan Kami</span></h1>
        <p class="text-slate-500 text-sm md:text-lg max-w-2xl mx-auto leading-relaxed px-2">
            Intip kilasan momen profesionalisme, pelatihan intensif, penyaluran tenaga kerja, serta aktivitas harian dari seluruh keluarga besar Efata Gemilang Jaya.
        </p>

        <div class="flex flex-wrap justify-center gap-6 md:gap-8 mt-10 md:mt-12 py-6 md:py-8 border-y border-slate-200">
            <div class="text-center min-w-[80px] md:min-w-0">
                <p class="text-xl md:text-3xl font-bold text-[#1e2b3a]" id="statTotalFoto">0</p>
                <p class="text-xs md:text-sm text-slate-400 font-medium uppercase">Total Dokumentasi</p>
            </div>
        </div>
    </header>

    <!-- MAIN GALERI -->
    <main class="max-w-7xl mx-auto px-6 pb-16 md:pb-24">
        <div class="flex flex-wrap justify-between items-center mb-6">
            <p class="text-slate-500 text-sm md:text-base">
                Menampilkan <span id="startCount">1</span> - <span id="endCount">12</span> dari <span id="totalCount">0</span> foto
            </p>
            <div class="flex gap-2">
                <select id="itemsPerPage" class="bg-white border border-slate-200 rounded-xl px-3 py-2 text-sm text-slate-700 focus:outline-none focus:border-[#C5A028] focus:ring-2 focus:ring-[#C5A028]/20">
                    <option value="6">6 per halaman</option>
                    <option value="12" selected>12 per halaman</option>
                    <option value="24">24 per halaman</option>
                    <option value="36">36 per halaman</option>
                </select>
            </div>
        </div>

        <div id="galleryGrid" class="gallery-grid min-h-[500px]"></div>

        <div class="mt-12 flex flex-wrap justify-center items-center gap-2">
            <button id="prevPage" class="pagination-item">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
                </svg>
            </button>
            <div id="paginationNumbers" class="flex flex-wrap justify-center gap-2"></div>
            <button id="nextPage" class="pagination-item">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
                </svg>
            </button>
        </div>

        <div class="mt-16 md:mt-20 bg-[#1e2b3a] rounded-[2rem] md:rounded-[3rem] p-8 md:p-12 text-center text-white relative overflow-hidden">
            <div class="relative z-10">
                <h2 class="text-xl md:text-3xl font-bold mb-3 md:mb-4">Butuh Layanan Tenaga Kerja Tepercaya?</h2>
                <p class="text-slate-300 text-sm md:text-base mb-6 md:mb-8 max-w-xl mx-auto px-2">Dapatkan info ketersediaan Baby Sitter, ART, Driver, dan Perawat Lansia terbaik yang siap bertugas.</p>
                <a href="https://wa.me/6285283399086" target="_blank" class="inline-block bg-[#C5A028] text-[#1e2b3a] px-6 md:px-10 py-3 md:py-4 rounded-full font-bold shadow-lg hover:bg-white hover:text-[#1e2b3a] transition-all transform hover:scale-105 text-sm md:text-base">
                    Hubungi via WhatsApp Sekarang
                </a>
            </div>
            <div class="absolute -right-20 -bottom-20 w-48 md:w-64 h-48 md:h-64 bg-white/5 rounded-full"></div>
        </div>
    </main>

    <!-- LIGHTBOX MODAL -->
    <div id="lightbox" class="lightbox">
        <div class="lightbox-content">
            <button id="closeLightbox" class="lightbox-close">&times;</button>
            <img id="lightboxImg" src="" alt="" class="lightbox-image">
            <div id="lightboxTitle" class="lightbox-title"></div>
        </div>
    </div>

    <?php include '../components/footer.php'; ?>

    <style>
        @keyframes pageEnter {
            0% {
                opacity: 0;
                transform: scale(0.95);
            }

            100% {
                opacity: 1;
                transform: scale(1);
            }
        }

        body {
            animation: pageEnter 0.8s cubic-bezier(0.4, 0, 0.2, 1) forwards;
        }
    </style>

    <!-- SCRIPT PHP UNTUK MEMBACA FOLDER GALERI -->
    <?php
    $documentRoot = $_SERVER['DOCUMENT_ROOT'];
    $galleryPath = $documentRoot . '/egj/assets/image/galeri/';
    $images = [];

    if (is_dir($galleryPath)) {
        $files = scandir($galleryPath);
        foreach ($files as $file) {
            if ($file == '.' || $file == '..') continue;
            $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
            if (in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
                $imageUrl = '/egj/assets/image/galeri/' . $file;
                $images[] = [
                    'url' => $imageUrl,
                    'name' => pathinfo($file, PATHINFO_FILENAME)
                ];
            }
        }
        sort($images);
    }
    ?>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const galleryData = <?php echo json_encode($images); ?>;

            console.log('Jumlah gambar ditemukan:', galleryData.length);

            if (galleryData.length === 0) {
                document.getElementById('galleryGrid').innerHTML = `
                    <div class="col-span-full text-center py-12">
                        <p class="text-slate-400 text-lg">Belum ada dokumentasi foto.</p>
                        <p class="text-slate-400 text-sm mt-2">Silakan tambahkan file gambar ke folder:</p>
                        <p class="text-slate-400 text-sm font-mono mt-1">/egj/assets/image/galeri/</p>
                    </div>
                `;
                document.getElementById('totalCount').textContent = '0';
                document.getElementById('statTotalFoto').textContent = '0';
                return;
            }

            document.getElementById('statTotalFoto').textContent = galleryData.length;

            let currentPage = 1;
            let itemsPerPage = 12;
            let filteredData = [...galleryData];

            const grid = document.getElementById('galleryGrid');
            const paginationNumbers = document.getElementById('paginationNumbers');
            const prevBtn = document.getElementById('prevPage');
            const nextBtn = document.getElementById('nextPage');
            const startCount = document.getElementById('startCount');
            const endCount = document.getElementById('endCount');
            const totalCount = document.getElementById('totalCount');
            const itemsPerPageSelect = document.getElementById('itemsPerPage');

            // LIGHTBOX ELEMENTS
            const lightbox = document.getElementById('lightbox');
            const lightboxImg = document.getElementById('lightboxImg');
            const lightboxTitle = document.getElementById('lightboxTitle');
            const closeLightbox = document.getElementById('closeLightbox');

            totalCount.textContent = galleryData.length;

            // Fungsi untuk mendapatkan nama file untuk ALT text dan title
            function formatTitle(filename) {
                let title = filename.replace(/[_-]/g, ' ');
                title = title.replace(/^whatsapp\s+image\s+\d+/i, '');
                title = title.replace(/^image[-_]?\d*/i, '');
                title = title.trim();
                if (title === '') title = 'Dokumentasi Efata';
                title = title.replace(/\b\w/g, l => l.toUpperCase());
                if (title.length > 50) title = title.substring(0, 47) + '...';
                return title;
            }

            // Fungsi buka lightbox dengan scroll ke atas terlebih dahulu
            let scrollPosition = 0;
            let currentCardElement = null;

            function openLightbox(imageUrl, titleText, cardElement) {
                // Simpan elemen card yang diklik
                currentCardElement = cardElement;

                // Scroll ke posisi card yang diklik agar di tengah viewport
                if (currentCardElement) {
                    const cardRect = currentCardElement.getBoundingClientRect();
                    const absoluteCardTop = window.pageYOffset + cardRect.top;
                    const windowHeight = window.innerHeight;
                    const cardHeight = cardRect.height;

                    // Scroll agar card berada di tengah viewport
                    const scrollToPosition = absoluteCardTop - (windowHeight / 2) + (cardHeight / 2);

                    window.scrollTo({
                        top: Math.max(0, scrollToPosition),
                        behavior: 'smooth'
                    });

                    // Tunggu scroll selesai (300ms) baru tampilkan lightbox
                    setTimeout(() => {
                        // Simpan posisi scroll setelah scroll selesai
                        scrollPosition = window.pageYOffset || document.documentElement.scrollTop;

                        // Terapkan class untuk lock scroll
                        document.body.classList.add('lightbox-open');
                        document.body.style.top = `-${scrollPosition}px`;

                        // Set gambar
                        lightboxImg.src = imageUrl;
                        lightboxTitle.textContent = titleText;

                        // Tampilkan lightbox
                        lightbox.classList.add('active');
                    }, 300);
                } else {
                    // Fallback jika tidak ada element
                    scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
                    document.body.classList.add('lightbox-open');
                    document.body.style.top = `-${scrollPosition}px`;
                    lightboxImg.src = imageUrl;
                    lightboxTitle.textContent = titleText;
                    lightbox.classList.add('active');
                }
            }

            // Fungsi tutup lightbox
            function closeLightboxModal() {
                // Sembunyikan lightbox
                lightbox.classList.remove('active');

                // Hapus lock scroll dan kembalikan ke posisi scroll yang disimpan
                document.body.classList.remove('lightbox-open');
                document.body.style.top = '';
                window.scrollTo(0, scrollPosition);

                // Clear gambar setelah animasi selesai
                setTimeout(() => {
                    lightboxImg.src = '';
                    lightboxTitle.textContent = '';
                }, 300);
            }

            window.openLightbox = openLightbox;

            if (closeLightbox) {
                closeLightbox.addEventListener('click', function(e) {
                    e.stopPropagation();
                    closeLightboxModal();
                });
            }

            // Tutup lightbox saat klik di luar modal
            if (lightbox) {
                lightbox.addEventListener('click', function(e) {
                    if (e.target === lightbox) {
                        closeLightboxModal();
                    }
                });
            }

            // Escape key untuk menutup lightbox
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape' && lightbox.classList.contains('active')) {
                    closeLightboxModal();
                }
            });

            function renderGallery() {
                const start = (currentPage - 1) * itemsPerPage;
                const end = Math.min(start + itemsPerPage, filteredData.length);
                const pageData = filteredData.slice(start, end);

                startCount.textContent = start + 1;
                endCount.textContent = end;
                totalCount.textContent = filteredData.length;

                if (filteredData.length === 0) {
                    grid.innerHTML = `<div class="col-span-full text-center py-12"><p class="text-slate-400 text-lg">Belum ada dokumentasi.</p></div>`;
                    return;
                }

                grid.innerHTML = pageData.map((item, index) => {
                    const title = formatTitle(item.name);
                    const escapedUrl = item.url.replace(/'/g, "\\'");
                    const escapedTitle = title.replace(/'/g, "\\'");
                    const cardId = `card_${currentPage}_${index}`;
                    return `
                    <div id="${cardId}" class="gallery-card" onclick="openLightbox('${escapedUrl}', '${escapedTitle}', this)">
                        <div class="gallery-img-container">
                            <img src="${item.url}" alt="${title}" class="gallery-img" loading="lazy" onerror="this.src='https://placehold.co/600x400/1e2b3a/C5A028?text=Gambar+Tidak+Ditemukan'">
                        </div>
                    </div>
                `
                }).join('');
            }

            function renderPagination() {
                const totalPages = Math.ceil(filteredData.length / itemsPerPage);
                if (totalPages <= 1) {
                    paginationNumbers.innerHTML = totalPages === 1 ? `<span class="pagination-item active">1</span>` : '';
                    prevBtn.classList.add('disabled');
                    nextBtn.classList.add('disabled');
                    return;
                }

                let startPage = Math.max(1, currentPage - 2);
                let endPage = Math.min(totalPages, currentPage + 2);
                if (currentPage <= 3) endPage = Math.min(5, totalPages);
                if (currentPage > totalPages - 3) startPage = Math.max(1, totalPages - 4);

                let html = '';
                for (let i = startPage; i <= endPage; i++) {
                    html += `<span class="pagination-item ${i === currentPage ? 'active' : ''}" data-page="${i}">${i}</span>`;
                }
                paginationNumbers.innerHTML = html;
                prevBtn.classList.toggle('disabled', currentPage === 1);
                nextBtn.classList.toggle('disabled', currentPage === totalPages);

                document.querySelectorAll('.pagination-item[data-page]').forEach(btn => {
                    btn.addEventListener('click', () => {
                        currentPage = parseInt(btn.dataset.page);
                        renderGallery();
                        renderPagination();
                        document.getElementById('galleryGrid').scrollIntoView({
                            behavior: 'smooth',
                            block: 'start'
                        });
                    });
                });
            }

            prevBtn.addEventListener('click', () => {
                const totalPages = Math.ceil(filteredData.length / itemsPerPage);
                if (currentPage > 1) {
                    currentPage--;
                    renderGallery();
                    renderPagination();
                    document.getElementById('galleryGrid').scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });

            nextBtn.addEventListener('click', () => {
                const totalPages = Math.ceil(filteredData.length / itemsPerPage);
                if (currentPage < totalPages) {
                    currentPage++;
                    renderGallery();
                    renderPagination();
                    document.getElementById('galleryGrid').scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });

            itemsPerPageSelect.addEventListener('change', function() {
                itemsPerPage = parseInt(this.value);
                currentPage = 1;
                renderGallery();
                renderPagination();
            });

            renderGallery();
            renderPagination();
        });
    </script>
</body>

</html>