<?php
require_once 'config.php';
require_once 'auth_helper.php';

$is_logged_in = isset($_SESSION['user_id']);
$is_admin = hasRole(['admin_paroki', 'ketua_wilayah']);
$user_name = $_SESSION['username'] ?? '';
$user_role = $_SESSION['role'] ?? '';
$role_label = $is_logged_in ? getRoleName($user_role) : '';


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    try {
        if ($action === 'update_paroki' && hasRole(['admin_paroki'])) {
            $sql = "UPDATE paroki SET 
                    nama_paroki = :nama_paroki,
                    alamat = :alamat,
                    sejarah = :sejarah,
                    pastor_paroki = :pastor_paroki
                    WHERE id_paroki = :id_paroki";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':id_paroki' => $_POST['id_paroki'],
                ':nama_paroki' => $_POST['nama_paroki'],
                ':alamat' => $_POST['alamat'],
                ':sejarah' => $_POST['sejarah'],
                ':pastor_paroki' => $_POST['pastor_paroki']
            ]);
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Informasi paroki berhasil diupdate!'];
        }
        elseif ($action === 'create_pastor') {
            $sql = "INSERT INTO pastor (nama_pastor, tugas_pastoral, tanggal_lahir, no_hp) 
                    VALUES (:nama_pastor, :tugas_pastoral, :tanggal_lahir, :no_hp)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':nama_pastor' => $_POST['nama_pastor'],
                ':tugas_pastoral' => $_POST['tugas_pastoral'],
                ':tanggal_lahir' => $_POST['tanggal_lahir'] ?: null,
                ':no_hp' => $_POST['no_hp']
            ]);
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Data pastor berhasil ditambahkan!'];
        } elseif ($action === 'update_pastor') {
            $sql = "UPDATE pastor SET 
                    nama_pastor = :nama_pastor,
                    tugas_pastoral = :tugas_pastoral,
                    tanggal_lahir = :tanggal_lahir,
                    no_hp = :no_hp
                    WHERE id_pastor = :id_pastor";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':id_pastor' => $_POST['id_pastor'],
                ':nama_pastor' => $_POST['nama_pastor'],
                ':tugas_pastoral' => $_POST['tugas_pastoral'],
                ':tanggal_lahir' => $_POST['tanggal_lahir'] ?: null,
                ':no_hp' => $_POST['no_hp']
            ]);

            $_SESSION['message'] = ['type' => 'success', 'text' => 'Data pastor berhasil diupdate!'];
        } elseif ($action === 'delete_pastor') {
            $sql = "DELETE FROM pastor WHERE id_pastor = :id_pastor";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':id_pastor' => $_POST['id_pastor']]);
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Data pastor berhasil dihapus!'];
        }
    } catch (PDOException $e) {
        $_SESSION['message'] = ['type' => 'error', 'text' => 'Error: ' . $e->getMessage()];
    }

    header('Location: paroki.php');
    exit;
}

// Query data
/* Menarik 1 baris record tunggal acuan profil institusi Paroki sebagai master identitas */
$paroki = $pdo->query("SELECT * FROM paroki LIMIT 1")->fetch();

/* Menarik katalog data lengkap Pastor se-paroki murni sebagai rujukan list pengurus dan cetak */
$pastor_list = $pdo->query("SELECT * FROM pastor ORDER BY nama_pastor")->fetchAll();
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Paroki - Sistem Informasi KUB Katedral Kupang</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.3.0/exceljs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/Flip.min.js"></script>
    <script src="https://unpkg.com/lenis@1/dist/lenis.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/lenis@1/dist/lenis.css">
    <link rel="stylesheet" href="style.css?v=<?= time() ?>">
    <style>
        /* CSS Override for Edit Button as requested */
        .card .btn-warning {
            background-color: #C83F12 !important;
            border-color: #C83F12 !important;
            color: #ffffff !important;
            box-shadow: none !important;
            transition: all 0.3s ease !important;
        }
        
        .card .btn-warning:hover {
            background-color: #a6340e !important;
            border-color: #a6340e !important;
            color: #ffffff !important;
            box-shadow: 0 6px 15px rgba(200, 63, 18, 0.45) !important;
            transform: translateY(-2px);
        }

        .card .btn-danger {
            background-color: var(--primary-light) !important;
            border-color: var(--primary-light) !important;
            color: #ffffff !important;
            box-shadow: none !important;
            transition: all 0.3s ease !important;
        }

        .card .btn-danger:hover {
            background-color: var(--primary) !important;
            border-color: var(--primary) !important;
            color: #ffffff !important;
            box-shadow: 0 6px 15px rgba(139, 26, 26, 0.45) !important;
            transform: translateY(-2px);
        }

        /* Hide scrollbar completely but keep scrolling functional */
        ::-webkit-scrollbar {
            display: none;
        }

        body {
            -ms-overflow-style: none;
            /* IE and Edge */
            scrollbar-width: none;
            /* Firefox */
        }

        /* Scroll-reveal animation for stat cards */
        .stat-card {
            opacity: 0;
            transform: translateY(40px);
        }

        .pastor-scroll-container::-webkit-scrollbar {
            width: 8px;
        }

        .pastor-scroll-container::-webkit-scrollbar-track {
            background: rgba(197, 165, 90, 0.1);
            border-radius: 4px;
        }

        .pastor-scroll-container::-webkit-scrollbar-thumb {
            background: var(--gold);
            border-radius: 4px;
        }

        .pastor-scroll-container::-webkit-scrollbar-thumb:hover {
            background: #b8860b;
        }

        .stat-card.stat-visible {
            animation: statFadeUp 0.6s ease-out forwards;
        }

        /* Stagger using nth-child */
        .stat-card:nth-child(2).stat-visible {
            animation-delay: 0.1s;
        }

        .stat-card:nth-child(3).stat-visible {
            animation-delay: 0.2s;
        }

        .stat-card:nth-child(4).stat-visible {
            animation-delay: 0.3s;
        }

        @keyframes statFadeUp {
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 3D Coverflow Carousel (TikTok/Fuze Studio Style) */
        .coverflow-carousel {
            position: relative;
            width: 100%;
            height: 600px;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: visible;
            /* Bebaskan dari clipping agar button x:-150 tidak terpotong (overflow diserap oleh body) */
            perspective: 1200px;
            background: transparent;
            padding: 0px 0;
            margin-top: -18px;
        }

        .coverflow-nav {
            position: absolute;
            top: 50%;
            transform: translateY(-50%) translateZ(200px);
            width: 100%;
            max-width: 1200px;
            display: flex;
            justify-content: space-between;
            padding: 0 40px;
            z-index: 100;
            pointer-events: none;
        }

        .coverflow-btn {
            pointer-events: auto;
            background: var(--primary);
            border: none;
            color: #ffffff;
            width: 55px;
            height: 55px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 28px;
            cursor: pointer;
            box-shadow: 0 10px 20px rgba(139, 26, 26, 0.3);
            position: relative;
            overflow: hidden;
            opacity: 0;
            transition: background-color 0.4s ease;
        }

        .coverflow-btn.prev {
            margin-left: -1.2%;
        }

        .coverflow-btn .btn-fill {
            position: absolute;
            top: 100%;
            left: 50%;
            transform: translate(-50%, 0);
            width: 150px;
            height: 150px;
            background: var(--primary-dark);
            border-radius: 50%;
            z-index: 1;
            pointer-events: none;
        }

        .coverflow-btn:hover {
            color: #ffffff;
        }

        .btn-text-inner {
            position: relative;
            z-index: 2;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .coverflow-wrapper {
            position: absolute;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            transform-style: preserve-3d;
        }

        .coverflow-item {
            position: absolute;
            width: 300px;
            height: 390px;
            left: 50%;
            top: 50%;
            margin-left: -160px;
            /* Setengah dari 320px agar tepat di tengah */
            margin-top: -205px;
            /* Setengah dari 410px agar tepat di tengah */
            border-radius: 11px;
            overflow: hidden;
            cursor: grab;
            will-change: transform, filter;
            background: #111;
        }

        .coverflow-wrapper {
            visibility: hidden;
            opacity: 0;
        }

        .coverflow-item:active {
            cursor: grabbing;
        }

        .coverflow-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            pointer-events: none;
            user-select: none;
            -webkit-user-drag: none;
        }



        .coverflow-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.4);
            display: flex;
            justify-content: center;
            align-items: center;
            opacity: 0;
            transition: opacity 0.4s ease;
            pointer-events: auto;
            /* Changed to auto so it detects hover/click */
            cursor: pointer;
            /* Ensure user knows it is clickable */
        }

        .coverflow-item:hover .coverflow-overlay {
            opacity: 1;
        }

        .coverflow-overlay .eye-icon {
            width: 60px;
            height: 60px;
            color: #fff;
            border-radius: 50%;
            padding: 15px;
            transform: scale(0.5);
            transition: transform 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            pointer-events: none;
            /* Let the click pass through the icon to the overlay/item */
        }

        .coverflow-item:hover .coverflow-overlay .eye-icon {
            transform: scale(1);
        }

        /* Lightbox Fullscreen */
        .lightbox-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(0, 0, 0, 0);
            z-index: 9999998;
        }

        .lightbox-close {
            display: none;
            position: fixed;
            top: 25px;
            right: 35px;
            color: white;
            font-size: 45px;
            cursor: pointer;
            text-shadow: 0 2px 10px rgba(0, 0, 0, 0.8);
            z-index: 10000000;
        }



        /* Carousel Restored Styles */
        .carousel-container {
            width: 100%;
            height: 75vh;
            position: relative;
            overflow: hidden;
            margin-top: 0;
            z-index: 1;
        }

        .carousel-wrapper {
            width: 100%;
            height: 100%;
            position: relative;
        }

        .carousel-slide {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            transition: opacity 0.8s ease;
            z-index: 1;
        }

        .carousel-slide.active {
            opacity: 1;
            z-index: 2;
        }

        .carousel-slide img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            filter: brightness(0.5);
        }

        .carousel-button {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(0, 0, 0, 0.5);
            color: white;
            border: none;
            padding: 15px 20px;
            font-size: 24px;
            cursor: pointer;
            z-index: 10;
            border-radius: 5px;
        }

        .carousel-button:hover {
            background: rgba(0, 0, 0, 0.8);
        }

        .carousel-button.prev {
            left: 20px;
        }

        .carousel-button.next {
            right: 20px;
        }

        .carousel-indicators {
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 10px;
            z-index: 10;
        }

        .carousel-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.5);
            cursor: pointer;
        }

        .carousel-indicator.active {
            background: white;
        }

        .carousel-caption {
            position: relative;
            color: var(--primary);
            text-align: center;
            z-index: 10;
            width: 100%;
        }

        .carousel-caption h2 {
            font-size: 42px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.9);
            font-family: 'Neue Montreal', 'Inter', sans-serif;
        }

        /* Override cache constraints for pastor-card */
        .pastor-card {
            background-color: #ffffff !important;
            transition: background-color 0.3s ease, box-shadow 0.2s ease !important;
        }

        .pastor-card:hover {
            background-color: rgba(218, 165, 32, 0.08) !important;
            box-shadow: 0 4px 12px rgba(218, 165, 32, 0.15) !important;
        }
    </style>
</head>

<body>
    <div id="loadingOverlay">
        <div class="spinner"></div>
        <p style="margin-top:10px; font-weight:bold;">Sedang mendownload file excel...</p>
    </div>

    <img src="logo1.jpg" id="logoExport" style="display:none;" crossorigin="anonymous">

    <?php $active_page = 'paroki.php';
    include 'navbar.php'; ?>

    <!-- Spacer to prevent overlap -->
    <div style="height: 100px; width: 100%; display: block;"></div>

    <!-- Carousel Caption di atas Slider -->
    <div class="carousel-caption" id="captionParoki"
        style="margin-bottom: 0px; overflow: visible; margin-top: 0%; padding-top: 1px; perspective: 800px; background: none !important; padding: 0; opacity: 0;">
        <h2 id="mainParokiTitle"
            style="font-family: 'Neue_Montreal', 'Neue Montreal', sans-serif; font-size: 32px; color: var(--primary); font-weight: 700; text-shadow: 0 0px 10px rgba(0,0,0,0.05); letter-spacing: -0.5px; margin: 0; display: inline-block;">
            KATEDRAL KRISTUS RAJA KUPANG</h2>
    </div>

    <!-- 3D Coverflow Carousel -->
    <div class="coverflow-carousel" id="churchCoverflow">
        <div class="coverflow-nav">
            <button class="coverflow-btn prev" id="cfPrev">
                <div class="btn-fill"></div>
                <div class="btn-text-inner">‹</div>
            </button>
            <button class="coverflow-btn next" id="cfNext">
                <div class="btn-fill"></div>
                <div class="btn-text-inner">›</div>
            </button>
        </div>
        <div class="coverflow-wrapper" id="cfWrapper">
            <!-- Items -> onclick event added via JS below -->
            <div class="coverflow-item">
                <img src="assets/images/gereja katedral1.png" alt="Gereja Katedral Kupang 1">
                <div class="coverflow-overlay">
                    <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 24 24" class="eye-icon">
                        <path fill="#ffffff" fill-rule="evenodd" d="M15 3.75a.75.75 0 0 1 .75-.75h4.5a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-1.5 0V5.56l-3.97 3.97a.75.75 0 1 1-1.06-1.06l3.97-3.97h-2.69a.75.75 0 0 1-.75-.75Zm-12 0A.75.75 0 0 1 3.75 3h4.5a.75.75 0 0 1 0 1.5H5.56l3.97 3.97a.75.75 0 0 1-1.06 1.06L4.5 5.56v2.69a.75.75 0 0 1-1.5 0v-4.5Zm11.47 11.78a.75.75 0 1 1 1.06-1.06l3.97 3.97v-2.69a.75.75 0 0 1 1.5 0v4.5a.75.75 0 0 1-.75.75h-4.5a.75.75 0 0 1 0-1.5h2.69l-3.97-3.97Zm-4.94-1.06a.75.75 0 0 1 0 1.06L5.56 19.5h2.69a.75.75 0 0 1 0 1.5h-4.5a.75.75 0 0 1-.75-.75v-4.5a.75.75 0 0 1 1.5 0v2.69l3.97-3.97a.75.75 0 0 1 1.06 0Z" clip-rule="evenodd"/>
                    </svg>
                </div>
            </div>
            <div class="coverflow-item">
                <img src="assets/images/Katedral_Kupang.jpeg" alt="Gereja Katedral Kupang 2">
                <div class="coverflow-overlay">
                    <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 24 24" class="eye-icon">
                        <path fill="#ffffff" fill-rule="evenodd" d="M15 3.75a.75.75 0 0 1 .75-.75h4.5a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-1.5 0V5.56l-3.97 3.97a.75.75 0 1 1-1.06-1.06l3.97-3.97h-2.69a.75.75 0 0 1-.75-.75Zm-12 0A.75.75 0 0 1 3.75 3h4.5a.75.75 0 0 1 0 1.5H5.56l3.97 3.97a.75.75 0 0 1-1.06 1.06L4.5 5.56v2.69a.75.75 0 0 1-1.5 0v-4.5Zm11.47 11.78a.75.75 0 1 1 1.06-1.06l3.97 3.97v-2.69a.75.75 0 0 1 1.5 0v4.5a.75.75 0 0 1-.75.75h-4.5a.75.75 0 0 1 0-1.5h2.69l-3.97-3.97Zm-4.94-1.06a.75.75 0 0 1 0 1.06L5.56 19.5h2.69a.75.75 0 0 1 0 1.5h-4.5a.75.75 0 0 1-.75-.75v-4.5a.75.75 0 0 1 1.5 0v2.69l3.97-3.97a.75.75 0 0 1 1.06 0Z" clip-rule="evenodd"/>
                    </svg>
                </div>
            </div>
            <div class="coverflow-item">
                <img src="assets/images/katedral-1.jpg.webp" alt="Gereja Katedral Kupang 3">
                <div class="coverflow-overlay">
                    <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 24 24" class="eye-icon">
                        <path fill="#ffffff" fill-rule="evenodd" d="M15 3.75a.75.75 0 0 1 .75-.75h4.5a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-1.5 0V5.56l-3.97 3.97a.75.75 0 1 1-1.06-1.06l3.97-3.97h-2.69a.75.75 0 0 1-.75-.75Zm-12 0A.75.75 0 0 1 3.75 3h4.5a.75.75 0 0 1 0 1.5H5.56l3.97 3.97a.75.75 0 0 1-1.06 1.06L4.5 5.56v2.69a.75.75 0 0 1-1.5 0v-4.5Zm11.47 11.78a.75.75 0 1 1 1.06-1.06l3.97 3.97v-2.69a.75.75 0 0 1 1.5 0v4.5a.75.75 0 0 1-.75.75h-4.5a.75.75 0 0 1 0-1.5h2.69l-3.97-3.97Zm-4.94-1.06a.75.75 0 0 1 0 1.06L5.56 19.5h2.69a.75.75 0 0 1 0 1.5h-4.5a.75.75 0 0 1-.75-.75v-4.5a.75.75 0 0 1 1.5 0v2.69l3.97-3.97a.75.75 0 0 1 1.06 0Z" clip-rule="evenodd"/>
                    </svg>
                </div>
            </div>
            <div class="coverflow-item">
                <img src="assets/images/Katedral_1.jpg" alt="Gereja Katedral Kupang 4">
                <div class="coverflow-overlay">
                    <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 24 24" class="eye-icon">
                        <path fill="#ffffff" fill-rule="evenodd" d="M15 3.75a.75.75 0 0 1 .75-.75h4.5a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-1.5 0V5.56l-3.97 3.97a.75.75 0 1 1-1.06-1.06l3.97-3.97h-2.69a.75.75 0 0 1-.75-.75Zm-12 0A.75.75 0 0 1 3.75 3h4.5a.75.75 0 0 1 0 1.5H5.56l3.97 3.97a.75.75 0 0 1-1.06 1.06L4.5 5.56v2.69a.75.75 0 0 1-1.5 0v-4.5Zm11.47 11.78a.75.75 0 1 1 1.06-1.06l3.97 3.97v-2.69a.75.75 0 0 1 1.5 0v4.5a.75.75 0 0 1-.75.75h-4.5a.75.75 0 0 1 0-1.5h2.69l-3.97-3.97Zm-4.94-1.06a.75.75 0 0 1 0 1.06L5.56 19.5h2.69a.75.75 0 0 1 0 1.5h-4.5a.75.75 0 0 1-.75-.75v-4.5a.75.75 0 0 1 1.5 0v2.69l3.97-3.97a.75.75 0 0 1 1.06 0Z" clip-rule="evenodd"/>
                    </svg>
                </div>
            </div>
            <div class="coverflow-item">
                <img src="assets/images/Katedral_2.jpg" alt="Gereja Katedral Kupang 5">
                <div class="coverflow-overlay">
                    <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 24 24" class="eye-icon">
                        <path fill="#ffffff" fill-rule="evenodd" d="M15 3.75a.75.75 0 0 1 .75-.75h4.5a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-1.5 0V5.56l-3.97 3.97a.75.75 0 1 1-1.06-1.06l3.97-3.97h-2.69a.75.75 0 0 1-.75-.75Zm-12 0A.75.75 0 0 1 3.75 3h4.5a.75.75 0 0 1 0 1.5H5.56l3.97 3.97a.75.75 0 0 1-1.06 1.06L4.5 5.56v2.69a.75.75 0 0 1-1.5 0v-4.5Zm11.47 11.78a.75.75 0 1 1 1.06-1.06l3.97 3.97v-2.69a.75.75 0 0 1 1.5 0v4.5a.75.75 0 0 1-.75.75h-4.5a.75.75 0 0 1 0-1.5h2.69l-3.97-3.97Zm-4.94-1.06a.75.75 0 0 1 0 1.06L5.56 19.5h2.69a.75.75 0 0 1 0 1.5h-4.5a.75.75 0 0 1-.75-.75v-4.5a.75.75 0 0 1 1.5 0v2.69l3.97-3.97a.75.75 0 0 1 1.06 0Z" clip-rule="evenodd"/>
                    </svg>
                </div>
            </div>
        </div>
    </div>

    <!-- Lightbox Modal untuk Gambar Fullscreen -->
    <div class="lightbox-modal" id="lightboxModal"></div>
    <span class="lightbox-close" id="lightboxClose" onclick="closeLightbox()">&times;</span>
    <img id="lightboxImage" src="" alt="Fullscreen Katedral"
        style="display: none; position: fixed; z-index: 9999999; object-fit: cover; border-radius: 11px; pointer-events: none;">

    <div class="container" style="margin-top: 3%;">
        <?php if (isset($_SESSION['message'])): ?>
            <div class="alert <?= $_SESSION['message']['type'] ?>">
                <span><?= $_SESSION['message']['text'] ?></span>
                <span class="close-alert" onclick="this.parentElement.remove()">×</span>
            </div>
            <?php unset($_SESSION['message']); ?>
        <?php endif; ?>

        <!-- Parish Information -->
        <div class="card" style="transition: box-shadow 0.3s ease;" 
             onmouseover="this.style.boxShadow='0 10px 30px rgba(168, 139, 61, 0.15)'" 
             onmouseout="this.style.boxShadow=''">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                <h3 class="card-title" style="margin: 0;">Informasi Paroki</h3>
                <?php if ($is_logged_in && hasRole(['admin_paroki'])): ?>
                    <button class="btn btn-sm btn-warning"
                        onclick="editParoki(<?= htmlspecialchars(json_encode($paroki)) ?>)">Edit</button>
                <?php endif; ?>
            </div>

            <?php if ($paroki): ?>
                <div class="info-grid">
                    <div class="info-item">
                        <label>Nama Paroki</label>
                        <p><?= htmlspecialchars($paroki['nama_paroki']) ?></p>
                    </div>
                    <div class="info-item">
                        <label>Pastor Paroki</label>
                        <p><?= htmlspecialchars($paroki['pastor_paroki']) ?></p>
                    </div>
                    <div class="info-item">
                        <label>Alamat</label>
                        <p><?= htmlspecialchars($paroki['alamat']) ?></p>
                    </div>
                </div>
                <div class="info-item">
                    <label>Sejarah Singkat</label>
                    <p><?= nl2br(htmlspecialchars($paroki['sejarah'])) ?></p>
                </div>
            <?php endif; ?>
        </div>



        <!-- Pastor Directory -->
        <div class="card" style="transition: box-shadow 0.3s ease;" 
             onmouseover="this.style.boxShadow='0 10px 30px rgba(168, 139, 61, 0.15)'" 
             onmouseout="this.style.boxShadow=''">
            <div class="page-header" style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #eee;">
                <h2 style="margin: 0;">Daftar Pastor</h2>
                <div class="header-actions">
                    <div style="position: relative; display: inline-block;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color: var(--text-muted); position: absolute; left: 12px; top: 50%; transform: translateY(-50%); pointer-events: none;">
                            <circle cx="11" cy="11" r="8"></circle>
                            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                        </svg>
                        <input type="text" class="search-box" id="searchPastor" placeholder="Cari Pastor..."
                            style="width: 200px; padding-left: 35px; border: 1px solid rgba(168, 139, 61, 0.1); background: rgba(168, 139, 61, 0.02); box-shadow: 0 2px 5px rgba(168, 139, 61, 0.05); transition: box-shadow 0.3s ease;" 
                            onmouseover="this.style.boxShadow='0 5px 15px rgba(168, 139, 61, 0.15)'" 
                            onmouseout="this.style.boxShadow='0 2px 5px rgba(168, 139, 61, 0.05)'"
                            onkeyup="searchTable('pastorTableBody', 'searchPastor')">
                    </div>
                    <?php if ($is_logged_in && hasRole(['admin_paroki', 'ketua_wilayah', 'ketua_kub'])): ?>
                        <button class="btn btn-print" onclick="confirmPrintPastor()" style="display: inline-flex; align-items: center; gap: 6px;">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <polyline points="6 9 6 2 18 2 18 9"></polyline>
                                <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"></path>
                                <rect x="6" y="14" width="12" height="8"></rect>
                            </svg>
                            Print
                        </button>
                        <button class="btn btn-export" onclick="confirmExportExcelPastor()" style="display: inline-flex; align-items: center; gap: 6px;">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M14 2H6a2 2 0 0 0-2 2v16c0 1.1.9 2 2 2h12a2 2 0 0 0 2-2V8l-6-6z"/>
                                <path d="M14 3v5h5M16 13H8M16 17H8M10 9H8"/>
                            </svg>
                            Export Excel
                        </button>
                        <?php if (hasRole(['admin_paroki'])): ?>
                            <button class="btn" onclick="openModal('create_pastor')">+ Tambah Pastor</button>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>

            <div class="table-wrapper pastor-scroll-container" data-lenis-prevent="true" style="max-height: 380px; overflow-y: auto;">
                <table class="table" id="pastorTable" style="margin-bottom: 0;">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Nama Pastor</th>
                            <th>Tugas Pastoral</th>
                            <th>Tanggal Lahir</th>
                            <th>No. HP</th>
                            <?php if ($is_logged_in && hasRole(['admin_paroki'])): ?>
                                <th class="no-print">Aksi</th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody id="pastorTableBody">
                        <!-- Siklus perulangan PHP: Menguraikan variabel list dari database lalu diubah ke dalam bentuk deretan baris HTML murni -->
                        <?php $no = 1;
                        foreach ($pastor_list as $pastor): ?>
                            <tr>
                                <td><?= $no++ ?></td>
                                <td>
                                    <strong><?= htmlspecialchars($pastor['nama_pastor']) ?></strong>
                                </td>
                                <td>
                                    <?php if (!empty($pastor['tugas_pastoral'])): ?>
                                        <?= htmlspecialchars($pastor['tugas_pastoral']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum ada tugas</span>
                                    <?php endif; ?>
                                </td>
                                <td><?= isset($pastor['tanggal_lahir']) && $pastor['tanggal_lahir'] ? date('d-m-Y', strtotime($pastor['tanggal_lahir'])) : '<span style="color: #999; font-size: 12px; font-style: italic;">Belum diisi</span>' ?></td>
                                <td><?= isset($pastor['no_hp']) && $pastor['no_hp'] ? htmlspecialchars($pastor['no_hp']) : '<span style="color: #999; font-size: 12px; font-style: italic;">Belum diisi</span>' ?></td>
                                <?php if ($is_logged_in && hasRole(['admin_paroki'])): ?>
                                    <td class="no-print">
                                        <button class="btn btn-sm btn-warning" onclick='editPastor(<?= htmlspecialchars(json_encode($pastor), ENT_QUOTES) ?>)'>Edit</button>
                                        <button class="btn btn-sm btn-danger" onclick="deletePastor(<?= $pastor['id_pastor'] ?>, '<?= htmlspecialchars($pastor['nama_pastor'], ENT_QUOTES) ?>')">Hapus</button>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Hidden Table for Print/Export -->
        <div style="display:none;" id="pastorPrintSection">
            <div class="print-header" id="printPastorHeader"></div>

            <table class="print-table" id="pastorTable">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Nama Lengkap</th>
                        <th>Tugas Pastoral</th>
                        <th>Tanggal Lahir</th>
                        <th>No. HP</th>
                    </tr>
                </thead>
                <tbody id="pastorTableBodyPrint">
                    <?php $no = 1;
                    foreach ($pastor_list as $p): ?>
                        <tr>
                            <td style="text-align:center;"><?= $no++ ?></td>
                            <td><?= htmlspecialchars($p['nama_pastor']) ?></td>
                            <td><?= htmlspecialchars($p['tugas_pastoral'] ?? '-') ?></td>
                            <td><?= isset($p['tanggal_lahir']) && $p['tanggal_lahir'] ? date('d-m-Y', strtotime($p['tanggal_lahir'])) : '-' ?></td>
                            <td><?= htmlspecialchars($p['no_hp'] ?? '-') ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <div class="print-footer" id="printPastorFooter"></div>
        </div>
    </div>

    <!-- Modal Edit Paroki -->
    <div id="parokiModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Edit Informasi Paroki</h3>
                <button class="close" onclick="closeModal('parokiModal')">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_paroki">
                    <input type="hidden" name="id_paroki" id="paroki_id">

                    <div class="form-group">
                        <label>Nama Paroki *</label>
                        <input type="text" name="nama_paroki" id="paroki_nama" required>
                    </div>



                    <div class="form-group">
                        <label>Alamat</label>
                        <textarea name="alamat" id="paroki_alamat"></textarea>
                    </div>

                    <div class="form-group">
                        <label>Pastor Paroki</label>
                        <input type="text" name="pastor_paroki" id="paroki_pastor">
                    </div>

                    <div class="form-group">
                        <label>Sejarah Singkat</label>
                        <textarea name="sejarah" id="paroki_sejarah"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-print"
                        onclick="closeModal('parokiModal')">Batal</button>
                    <button type="submit" class="btn btn-export">Simpan</button>
                </div>
            </form>
        </div>
    </div>


    <!-- Modal Pastor -->
    <div id="pastorModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="pastorModalTitle">Tambah Pastor</h3>
                <button class="close" onclick="closeModal('pastorModal')">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" id="pastor_action" value="create_pastor">
                    <input type="hidden" name="id_pastor" id="pastor_id">

                    <div class="form-group">
                        <label>Tugas Pastoral *</label>
                        <select name="tugas_pastoral" id="pastor_tugas_pastoral" required>
                            <option value="">Pilih Tugas Pastoral</option>
                            <option value="Pastor Paroki">Pastor Paroki</option>
                            <option value="Pastor Rekan">Pastor Rekan</option>
                            <option value="Uskup">Uskup</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Nama Pastor *</label>
                        <input type="text" name="nama_pastor" id="pastor_nama" placeholder="Isi nama Pastor" required>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Tanggal Lahir</label>
                            <input type="date" name="tanggal_lahir" id="pastor_tgl_lahir">
                        </div>
                        <div class="form-group">
                            <label>No. HP</label>
                            <input type="text" name="no_hp" id="pastor_no_hp" placeholder="Isi No. HP">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-print"
                        onclick="closeModal('pastorModal')">Batal</button>
                    <button type="submit" class="btn btn-export">Simpan</button>
                </div>
            </form>
        </div>
    </div>

    <div id="deletePastorModal" class="modal">
        <div class="modal-content" style="max-width: 400px;">
            <div class="modal-header">
                <h3>Hapus Pastor</h3>
                <button class="close" onclick="closeModal('deletePastorModal')">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="delete_pastor">
                    <input type="hidden" name="id_pastor" id="delete_pastor_id">
                    <p>Yakin ingin menghapus data <strong id="delete_pastor_nama"></strong>?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-print" onclick="closeModal('deletePastorModal')">Batal</button>
                    <button type="submit" class="btn btn-export">Hapus</button>
                </div>
            </form>
        </div>
    </div>

    </div>

    <script>
        // Carousel functionality
        let currentSlide = 0;
        const slides = document.querySelectorAll('.carousel-slide');
        const indicators = document.querySelectorAll('.carousel-indicator');
        const totalSlides = slides.length;
        let autoSlideInterval;

        /* Fungsi untuk menampilkan gambar utama sesuai indeks pada fitur slideshow/carousel di bagian atas */
        function showSlide(index) {
            // Remove active class from all slides and indicators
            slides.forEach(slide => slide.classList.remove('active'));
            indicators.forEach(ind => ind.classList.remove('active'));

            // Wrap around if index goes beyond bounds
            if (index >= totalSlides) {
                currentSlide = 0;
            } else if (index < 0) {
                currentSlide = totalSlides - 1;
            } else {
                currentSlide = index;
            }

            // Add active class to current slide and indicator
            slides[currentSlide].classList.add('active');
            indicators[currentSlide].classList.add('active');
        }

        /* Fungsi untuk berpindah slide (maju atau mundur) ketika tombol navigasi panah diklik */
        function changeSlide(direction) {
            showSlide(currentSlide + direction);
            resetAutoSlide();
        }

        function goToSlide(index) {
            showSlide(index);
            resetAutoSlide();
        }

        function autoSlide() {
            currentSlide++;
            showSlide(currentSlide);
        }

        function resetAutoSlide() {
            clearInterval(autoSlideInterval);
            autoSlideInterval = setInterval(autoSlide, 5000); // Auto slide every 5 seconds
        }

        // Start auto-slide when page loads
        document.addEventListener('DOMContentLoaded', function() {
            autoSlideInterval = setInterval(autoSlide, 5000);
        });

        function initModalLenis(modalId) {
            setTimeout(() => {
                const modal = document.getElementById(modalId);
                if (!modal) return;
                const modalBody = modal.querySelector('.modal-body');
                if (!modalBody) return;

                let contentWrapper = modalBody.querySelector('.lenis-modal-inner');
                if (!contentWrapper) {
                    contentWrapper = document.createElement('div');
                    contentWrapper.className = 'lenis-modal-inner';
                    while (modalBody.firstChild) {
                        contentWrapper.appendChild(modalBody.firstChild);
                    }
                    modalBody.appendChild(contentWrapper);
                }

                if (window.modalLenis) {
                    window.modalLenis.destroy();
                }

                window.modalLenis = new Lenis({
                    wrapper: modalBody,
                    content: contentWrapper,
                    lerp: 0.08,
                    duration: 1.2,
                    smoothWheel: true,
                    wheelMultiplier: 0.8
                });
            }, 10); // Small delay to allow display:block to render before calculating heights
        }

        /* Fungsi untuk menampilkan jendela pop-up (modal) saat ingin menambah data pastor baru */
        function openModal(type) {
            document.body.style.overflow = 'hidden';
            if (window.lenis) window.lenis.stop();
            if (type === 'create_pastor') {
                document.getElementById('pastorModal').style.display = 'block';
                document.getElementById('pastorModalTitle').innerText = 'Tambah Pastor';
                document.getElementById('pastor_action').value = 'create_pastor';
                document.querySelector('#pastorModal form').reset();
                initModalLenis('pastorModal');
            }
        }

        /* Fungsi untuk menutup jendela pop-up (modal) dan mengembalikan interaksi layar ke kondisi semula */
        function closeModal(modalId) {
            if (window.modalLenis) {
                window.modalLenis.destroy();
                window.modalLenis = null;
            }
            document.getElementById(modalId).style.display = 'none';
            document.body.style.overflow = '';
            if (window.lenis) window.lenis.start();
        }

        /* Fungsi untuk menarik isian data profil paroki agar form edit terisi otomatis */
        function editParoki(data) {
            document.body.style.overflow = 'hidden';
            if (window.lenis) window.lenis.stop();
            document.getElementById('parokiModal').style.display = 'block';
            document.getElementById('paroki_id').value = data.id_paroki;
            document.getElementById('paroki_nama').value = data.nama_paroki;
            document.getElementById('paroki_alamat').value = data.alamat || '';
            document.getElementById('paroki_pastor').value = data.pastor_paroki || '';
            document.getElementById('paroki_sejarah').value = data.sejarah || '';
            initModalLenis('parokiModal');
        }

        /* Fungsi untuk memuat ulang data di tabel ke dalam pop-up form edit agar siap diperbarui */
        function editPastor(data) {
            document.body.style.overflow = 'hidden';
            if (window.lenis) window.lenis.stop();
            document.getElementById('pastorModal').style.display = 'block';
            document.getElementById('pastorModalTitle').innerText = 'Edit Pastor';
            document.getElementById('pastor_action').value = 'update_pastor';
            document.getElementById('pastor_id').value = data.id_pastor;
            document.getElementById('pastor_tugas_pastoral').value = data.tugas_pastoral || '';
            document.getElementById('pastor_nama').value = data.nama_pastor;
            document.getElementById('pastor_tgl_lahir').value = data.tanggal_lahir || '';
            document.getElementById('pastor_no_hp').value = data.no_hp || '';
            initModalLenis('pastorModal');
        }

        /* Fungsi untuk memunculkan kotak dialog konfirmasi sebelum data dihapus secara permanen */
        function deletePastor(id, nama) {
            document.body.style.overflow = 'hidden';
            if (window.lenis) window.lenis.stop();
            document.getElementById('deletePastorModal').style.display = 'block';
            document.getElementById('delete_pastor_id').value = id;
            document.getElementById('delete_pastor_nama').innerText = nama;
            initModalLenis('deletePastorModal');
        }

        /* Fungsi pencarian/filter tabel secara instan (real-time) hanya dengan mengetikkan kata kunci text */
        function searchTable(tableId, searchId) {
            const input = document.getElementById(searchId);
            const filter = input.value.toUpperCase();
            const table = document.getElementById(tableId);
            const tr = table.getElementsByTagName('tr');

            for (let i = 1; i < tr.length; i++) {
                let found = false;
                const td = tr[i].getElementsByTagName('td');
                for (let j = 0; j < td.length; j++) {
                    if (td[j].innerText.toUpperCase().indexOf(filter) > -1) {
                        found = true;
                        break;
                    }
                }
                tr[i].style.display = found ? '' : 'none';
            }
        }

        window.onclick = function(e) {
            if (e.target.classList.contains('modal')) {
                e.target.style.display = 'none';
            }
        }

        /* Fungsi andalan untuk mendownload dan merapikan seluruh isi data Pastor ke dalam file Microsoft Excel */
        async function confirmExportExcelPastor() {
            document.getElementById('loadingOverlay').style.display = 'flex';
            try {
                var logoImg = document.getElementById('logoExport');
                var base64Logo = '';
                if (logoImg && logoImg.naturalWidth > 0) {
                    var cvs = document.createElement('canvas');
                    cvs.width = logoImg.naturalWidth;
                    cvs.height = logoImg.naturalHeight;
                    cvs.getContext('2d').drawImage(logoImg, 0, 0);
                    base64Logo = cvs.toDataURL('image/png');
                }

                var workbook = new ExcelJS.Workbook();
                var ws = workbook.addWorksheet('Daftar Pastor');

                ws.columns = [
                    { width: 6 }, { width: 30 }, { width: 25 },
                    { width: 18 }, { width: 20 }
                ];

                // === KOP SURAT ===
                ws.mergeCells('A1:E1');
                ws.getCell('A1').value = 'PAROKI KRISTUS RAJA KATEDRAL KUPANG';
                ws.getCell('A1').font = { name: 'Times New Roman', size: 14, bold: true };
                ws.getCell('A1').alignment = { horizontal: 'center', vertical: 'middle' };
                ws.getRow(1).height = 22;

                ws.mergeCells('A2:E2');
                ws.getCell('A2').value = 'KEUSKUPAN AGUNG KUPANG - TIMOR';
                ws.getCell('A2').font = { name: 'Times New Roman', size: 12, bold: true };
                ws.getCell('A2').alignment = { horizontal: 'center', vertical: 'middle' };
                ws.getRow(2).height = 20;

                // Garis kop surat (double bottom border)
                for (var col = 1; col <= 5; col++) {
                    ws.getRow(2).getCell(col).border = {
                        bottom: { style: 'double', color: { argb: 'FF000000' } }
                    };
                }

                // Logo
                if (base64Logo) {
                    var imageId = workbook.addImage({ base64: base64Logo, extension: 'png' });
                    // Ukuran logo fix 40px karena Kop Surat paroki statis 2 baris (Keuskupan)
                    // Digunakan pecahan (0.1) untuk memberi jarak spasi/padding aman dari tepi margin
                    var logoSize = 40;
                    ws.addImage(imageId, { 
                        tl: { col: 0.1, row: 0.1 }, 
                        ext: { width: logoSize, height: logoSize } 
                    });
                }

                // Spacer
                ws.getRow(3).height = 8;

                // === TANGGAL CETAK ===
                var now = new Date();
                var days = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];
                var months = ['Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
                var printStr = 'Dicetak pada: ' + days[now.getDay()] + ', ' + now.getDate() + ' ' + months[now.getMonth()] + ' ' + now.getFullYear() + ' Pukul ' + String(now.getHours()).padStart(2,'0') + ':' + String(now.getMinutes()).padStart(2,'0');

                ws.mergeCells('A4:E4');
                ws.getCell('A4').value = printStr;
                ws.getCell('A4').font = { italic: true, size: 9 };
                ws.getCell('A4').alignment = { horizontal: 'right' };

                // === JUDUL ===
                ws.mergeCells('A5:E5');
                ws.getCell('A5').value = 'DAFTAR IMAM / PASTOR';
                ws.getCell('A5').font = { size: 14, bold: true, underline: true };
                ws.getCell('A5').alignment = { horizontal: 'center' };

                ws.getRow(6).height = 8;

                // === HEADER TABEL ===
                var headerRow = ws.addRow(['No', 'Nama Lengkap', 'Tugas Pastoral', 'Tanggal Lahir', 'No. HP']);
                headerRow.height = 22;
                headerRow.eachCell(function(cell) {
                    cell.font = { bold: true, size: 10 };
                    cell.alignment = { horizontal: 'center', vertical: 'middle' };
                    cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
                    cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } };
                });

                // === DATA ROWS ===
                document.querySelectorAll('#pastorTableBodyPrint tr').forEach(function(row) {
                    var c = row.cells;
                    if (c && c.length >= 5) {
                        var dr = ws.addRow([c[0].innerText.trim(), c[1].innerText.trim(), c[2].innerText.trim(), c[3].innerText.trim(), c[4].innerText.trim()]);
                        dr.eachCell(function(cell, colNumber) {
                            cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } };
                            cell.font = { size: 10 };
                            if (colNumber === 1 || colNumber === 5) cell.alignment = { horizontal: 'center' };
                        });
                    }
                });

                // === SIMPAN ===
                var dateFile = now.toISOString().split('T')[0];
                var buffer = await workbook.xlsx.writeBuffer();
                saveAs(new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), 'Daftar_Pastor_' + dateFile + '.xlsx');
            } catch (error) {
                console.error('Excel Export Error:', error);
                alert('Gagal mengekspor data ke Excel: ' + error.message);
            } finally {
                document.getElementById('loadingOverlay').style.display = 'none';
            }
        }




        /* Fungsi untuk membangun ulang tampilan tabel agar rapi dan siap masuk ke antarmuka printer fisik */
        async function confirmPrintPastor() {
            const logoImg = document.getElementById('logoExport');
            let base64Logo = "";
            if (logoImg) {
                const canvas = document.createElement("canvas");
                canvas.width = logoImg.naturalWidth;
                canvas.height = logoImg.naturalHeight;
                const ctx = canvas.getContext("2d");
                ctx.drawImage(logoImg, 0, 0);
                base64Logo = canvas.toDataURL("image/jpeg");
            }

            const now = new Date();
            const days = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
            const months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
            const dayName = days[now.getDay()];
            const printDateTimeStr = `Dicetak pada: ${dayName}, ${now.getDate()} ${months[now.getMonth()]} ${now.getFullYear()} Pukul ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;

            // Build rows from pastor print table
            let tableRows = '';
            document.querySelectorAll('#pastorTableBodyPrint tr').forEach(row => {
                const c = row.cells;
                tableRows += `<tr>
                    <td style="text-align:center;">${c[0].innerText}</td>
                    <td>${c[1].innerText}</td>
                    <td>${c[2].innerText}</td>
                    <td>${c[3].innerText}</td>
                    <td style="text-align:center;">${c[4].innerText}</td>
                </tr>`;
            });

            // Create temporary print overlay but keep it visually hidden from screen
            const printOverlay = document.createElement('div');
            printOverlay.id = 'tempPrintOverlay';
            printOverlay.style.cssText = 'display:none;';
            printOverlay.innerHTML = `
            <div style="padding: 20px;">
                <div style="position:relative; min-height:77px; border-bottom:3px double #000; padding-bottom:8px; margin-bottom:13px;">
                    <img src="${base64Logo}" style="position:absolute; left:0; top:0; width:70px;">
                    <div style="width:100%; text-align:center; padding-top:5px;">
                        <h2 style="margin:0; font-size:18px;">PAROKI KRISTUS RAJA KATEDRAL KUPANG</h2>
                        <h3 style="margin:2px 0; font-size:16px;">KEUSKUPAN AGUNG KUPANG - TIMOR</h3>
                    </div>
                </div>
                <div style="text-align:right; font-size:10pt; margin-bottom:8px;"><i>${printDateTimeStr}</i></div>
                <div style="text-align:center; margin-bottom:17px;">
                    <h3 style="text-decoration:underline; font-size:16px;">DAFTAR IMAM / PASTOR</h3>
                </div>
                <table class="table" style="width:100%;">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Nama Lengkap</th>
                            <th>Tugas Pastoral</th>
                            <th>Tanggal Lahir</th>
                            <th>No. HP</th>
                        </tr>
                    </thead>
                    <tbody>${tableRows}</tbody>
                </table>
            </div>`;

            // Inject temporary print style to hide everything else during print ONLY
            const printStyle = document.createElement('style');
            printStyle.id = 'tempPrintStyle';
            printStyle.innerHTML = `
                @media print {
                    body > *:not(#tempPrintOverlay) { display: none !important; }
                    #tempPrintOverlay { display: block !important; position: absolute; left: 0; top: 0; width: 100%; padding: 20px; box-sizing: border-box; }
                    @page { margin: 15mm; size: auto; }
                    .table th { background-color: #f0f0f0 !important; color: #000 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
                }
            `;

            document.head.appendChild(printStyle);
            document.body.appendChild(printOverlay);

            setTimeout(() => {
                window.print();
            }, 300);
        }

        // Remove print overlay & styles after printing
        window.onafterprint = function() {
            const overlay = document.getElementById('tempPrintOverlay');
            if (overlay) overlay.remove();
            const style = document.getElementById('tempPrintStyle');
            if (style) style.remove();
        };

        window.onclick = function(e) {
            if (e.target.classList.contains('modal')) {
                e.target.style.display = 'none';
            }
        }
    </script>

    <script src="navbar.js?v=6"></script>

    <script>
        // ========== SCROLL-TRIGGERED ANIMATIONS (Page-specific) ==========
        document.addEventListener("DOMContentLoaded", () => {
            gsap.registerPlugin(ScrollTrigger, Flip);

            ScrollTrigger.create({
                trigger: '.stats-grid',
                start: 'top 85%',
                onEnter: () => document.querySelectorAll('.stat-card').forEach(c => c.classList.add('stat-visible')),
                onLeaveBack: () => document.querySelectorAll('.stat-card').forEach(c => c.classList.remove('stat-visible'))
            });

            const gridCards = document.querySelectorAll('.grid-2 > .card');
            gridCards.forEach((card, i) => {
                gsap.from(card, {
                    x: i === 0 ? -80 : 80,
                    opacity: 0,
                    duration: 0.8,
                    ease: 'power3.out',
                    scrollTrigger: {
                        trigger: card,
                        start: 'top 80%',
                        toggleActions: 'play reverse play reverse'
                    }
                });
            });

            document.querySelectorAll('.container > .card').forEach(card => {
                gsap.from(card, {
                    y: 50,
                    opacity: 0,
                    duration: 0.8,
                    ease: 'power3.out',
                    scrollTrigger: {
                        trigger: card,
                        start: 'top 80%',
                        toggleActions: 'play reverse play reverse'
                    }
                });
            });

            gsap.from('.activity-item', {
                x: 60,
                opacity: 0,
                duration: 0.6,
                stagger: 0.1,
                ease: 'power3.out',
                scrollTrigger: {
                    trigger: '.activity-item',
                    start: 'top 85%',
                    toggleActions: 'play none none reverse' // None untuk onLeave bawah agar tidak hilang saat lewat, reverse saat scroll naik kembali
                }
            });

            gsap.from('.kub-stat-item', {
                y: 30,
                opacity: 0,
                duration: 0.5,
                stagger: 0.08,
                ease: 'power3.out',
                scrollTrigger: {
                    trigger: '.kub-stat-item',
                    start: 'top 85%',
                    toggleActions: 'play none none reverse'
                }
            });

            // ========== 3D COVERFLOW CAROUSEL (TIKTOK STYLE) LOGIC ==========
            const cfItems = document.querySelectorAll('.coverflow-item');
            const btnPrev = document.getElementById('cfPrev');
            const btnNext = document.getElementById('cfNext');
            const cfWrapper = document.getElementById('cfWrapper');
            let cfCurrentIndex = 2; // Default to Center item (0 to 4)
            const cfTotalItems = cfItems.length;

            /* Fungsi inti animasi Coverflow 3D ala TikTok untuk mengkalkulasi rotasi dan pergerakan kartu pastor */
            function updateCoverflow() {
                cfItems.forEach((item, i) => {
                    // ANTI-SPAM: Kill semua animasi GSAP yang masih berjalan pada kartu ini
                    gsap.killTweensOf(item);
                    // Reset opacity agar tidak terjebak transparan dari animasi terpotong
                    gsap.set(item, {
                        opacity: 1
                    });

                    // Kalkulasi Normalized Index
                    let activeIdx = ((cfCurrentIndex % cfTotalItems) + cfTotalItems) % cfTotalItems;

                    // Kalkulasi Infinite Offset
                    let offset = i - activeIdx;
                    if (offset > Math.floor(cfTotalItems / 2)) {
                        offset -= cfTotalItems;
                    } else if (offset < -Math.floor(cfTotalItems / 2)) {
                        offset += cfTotalItems;
                    }

                    let scale = 1;
                    let translateX = 0;
                    let translateZ = 0;
                    let rotateY = 0;
                    let zIndex = 10;
                    let brightness = 1;

                    if (offset === 0) {
                        scale = 1.1;
                        translateX = 0;
                        translateZ = 80;
                        rotateY = 0;
                        zIndex = 20;
                        brightness = 1;
                    } else if (Math.abs(offset) === 1) {
                        scale = 0.99; // -10% from 1.03
                        translateX = offset > 0 ? 275 : -275; /* +10% from 250 */
                        translateZ = -60;
                        rotateY = 0;
                        zIndex = 15;
                        brightness = 1;
                    } else if (Math.abs(offset) >= 2) {
                        scale = 0.87; // -10% from 0.97
                        const extraSpacing = (Math.abs(offset) - 2) * 145; /* +10% from 132 */
                        translateX = offset > 0 ? 532 + extraSpacing : -532 - extraSpacing; /* +10% from 484 */
                        translateZ = -180;
                        rotateY = 0;
                        zIndex = 10 - Math.abs(offset);
                        brightness = 1;
                    }

                    // Deteksi wrap
                    const prevOffset = parseFloat(item.dataset.lastOffset);
                    const isWrapping = !isNaN(prevOffset) && (Math.abs(prevOffset - offset) > 2);

                    if (isWrapping) {
                        // SMOOTH PORTAL: Animasi 2 fase (anti-spam safe)
                        // killTweensOf + opacity reset sudah di-handle di awal forEach
                        const tl = gsap.timeline();

                        // Fase 1: Shrink + fade out di posisi lama (0.2 detik)
                        tl.to(item, {
                            scale: 0.3,
                            opacity: 0,
                            filter: 'brightness(0)',
                            duration: 0.2,
                            ease: "power2.in"
                        });

                        // Teleport instan ke posisi baru (tidak terlihat karena opacity 0)
                        tl.set(item, {
                            x: translateX,
                            z: translateZ,
                            rotationY: rotateY,
                            zIndex: zIndex
                        });

                        // Fase 2: Grow + fade in di posisi baru (0.35 detik)
                        tl.to(item, {
                            scale: scale,
                            opacity: 1,
                            filter: `brightness(${brightness})`,
                            duration: 0.35,
                            ease: "power2.out"
                        });
                    } else {
                        gsap.to(item, {
                            x: translateX,
                            z: translateZ,
                            rotationY: rotateY,
                            scale: scale,
                            zIndex: zIndex,
                            filter: `brightness(${brightness})`,
                            duration: 0.8,
                            ease: "power3.out",
                            overwrite: true
                        });
                    }

                    item.dataset.lastOffset = offset;
                });
            }

            // --- ANTI-SPAM DEBOUNCE ---
            let cfCooldown = false;
            const CF_COOLDOWN_MS = 300;

            function cfSlide(direction) {
                if (cfCooldown) return;
                cfCooldown = true;
                cfCurrentIndex += direction;
                updateCoverflow();
                setTimeout(() => {
                    cfCooldown = false;
                }, CF_COOLDOWN_MS);
            }

            // Click interaction
            let cfWasDragged = false;

            // Mouse Events for drag vs click differentiation
            let startDragX = 0;
            let startDragY = 0;

            cfWrapper.addEventListener('mousedown', (e) => {
                cfWasDragged = false;
                startDragX = e.clientX;
                startDragY = e.clientY;
            });
            cfWrapper.addEventListener('mousemove', (e) => {
                if (isDraggingCF) {
                    const diffX = Math.abs(e.clientX - startDragX);
                    const diffY = Math.abs(e.clientY - startDragY);
                    // Only count as drag if moved more than 5 pixels
                    if (diffX > 5 || diffY > 5) {
                        cfWasDragged = true;
                    }
                }
            });
            cfWrapper.addEventListener('touchstart', (e) => {
                cfWasDragged = false;
                if (e.touches.length > 0) {
                    startDragX = e.touches[0].clientX;
                    startDragY = e.touches[0].clientY;
                }
            });
            cfWrapper.addEventListener('touchmove', (e) => {
                if (isDraggingCF && e.touches.length > 0) {
                    const diffX = Math.abs(e.touches[0].clientX - startDragX);
                    const diffY = Math.abs(e.touches[0].clientY - startDragY);
                    if (diffX > 5 || diffY > 5) {
                        cfWasDragged = true;
                    }
                }
            });

            cfItems.forEach((item, index) => {
                item.addEventListener('click', (e) => {
                    if (cfCooldown) return;
                    if (cfWasDragged) return; // Prevent click trigger after drag

                    // Calculate active index correctly based on current normalized position
                    let activeIdx = ((cfCurrentIndex % cfTotalItems) + cfTotalItems) % cfTotalItems;
                    let step = index - activeIdx;

                    // Normalize the step difference for an infinite loop with 5 items
                    if (step > Math.floor(cfTotalItems / 2)) step -= cfTotalItems;
                    else if (step < -Math.floor(cfTotalItems / 2)) step += cfTotalItems;

                    // If step is exactly 0, this is the center item!
                    if (step === 0) {
                        e.stopPropagation(); // Stop drag listeners if we hit the center button
                        openLightbox(item);
                    } else {
                        // Otherwise, slide towards the clicked item
                        cfCooldown = true;
                        cfCurrentIndex += step;
                        updateCoverflow();
                        setTimeout(() => {
                            cfCooldown = false;
                        }, CF_COOLDOWN_MS);
                    }
                });
            });

            // Lightbox functions (Andy Hardy Style - Pure GSAP Custom Koordinat)
            let activeLightboxItem = null;
            let activeLightboxImg = null;

            function openLightbox(item) {
                const modal = document.getElementById('lightboxModal');
                const imgTarget = document.getElementById('lightboxImage');
                const imgSource = item.querySelector('img');
                const closeBtn = document.getElementById('lightboxClose');

                if (!imgSource || !imgTarget) return;

                activeLightboxItem = item;
                activeLightboxImg = imgSource;

                // 1. Hentikan Scroll (Lenis & CSS)
                if (window.lenis) window.lenis.stop();
                document.body.style.overflow = 'hidden';

                // 2. Hentikan auto-slider
                if (typeof stopAutoSlide === 'function') stopAutoSlide();

                // 2. Ambil ukuran asli gambar di carousel pada layar!
                const rect = imgSource.getBoundingClientRect();

                // 3. Set kloning gambar (imgTarget) tepat di posisi awal imgSource
                imgTarget.src = imgSource.src;
                imgTarget.style.display = 'block';

                // Set Modal
                modal.style.display = 'block';
                modal.classList.add('active');
                gsap.killTweensOf(modal);
                gsap.set(modal, {
                    backgroundColor: "rgba(0,0,0,0)",
                    pointerEvents: "auto"
                });

                // Set Gambar awal (Posisi awal sama persis)
                gsap.killTweensOf(imgTarget);

                // Gunakan trik object-fit cover terus menerus tapi dalam kotak yang melar
                // Browser modern akan menyesuaikan crop "cover" secara halus jika kotaknya membesar rata proporsional
                gsap.set(imgTarget, {
                    top: rect.top,
                    left: rect.left,
                    width: rect.width,
                    height: rect.height,
                    borderRadius: "11px",
                    objectFit: "cover",
                    pointerEvents: "auto",
                    zIndex: 9999999,
                    display: "block"
                });

                // 4. Hitung posisi layar tengah ukuran "fullscreen" raksasa namun merespon aspek rasio
                // Kita gunakan 90vw / 90vh
                const vW = window.innerWidth;
                const vH = window.innerHeight;
                const targetW = vW * 0.9;
                const targetH = vH * 0.9;
                const targetTop = (vH - targetH) / 2;
                const targetLeft = (vW - targetW) / 2;

                // Animasikan Close Btn Tampil
                closeBtn.style.display = 'block';

                // Animasikan Modal memudar gelap tapi sedikit transparan agar gambar belakang terlihat samar
                gsap.to(modal, {
                    backgroundColor: "rgba(0,0,0,0.85)",
                    duration: 0.8,
                    ease: "power2.out"
                });

                gsap.killTweensOf(closeBtn);
                gsap.fromTo(closeBtn, {
                    opacity: 0,
                    scale: 0.5,
                    rotation: -90
                }, {
                    opacity: 1,
                    scale: 1,
                    rotation: 0,
                    duration: 0.8,
                    ease: "back.out(2)",
                    delay: 0.2
                });

                // Sembunyikan gambar asli di carousel agar tidak dobel
                gsap.set(imgSource, {
                    opacity: 0
                });

                // Dapatkan rasio asli gambar (lebar asli / tinggi asli)
                const naturalRatio = imgSource.naturalWidth / imgSource.naturalHeight;

                // Hitung dimensi akhir (target) agar gambar Utuh (mirip efek contain tapi kita hitung manual)
                let finalW = targetW;
                let finalH = targetW / naturalRatio;

                // Jika tingginya melebihi batas layar, gunakan tinggi layar sebagai patokan
                if (finalH > targetH) {
                    finalH = targetH;
                    finalW = finalH * naturalRatio;
                }

                // Hitung posisi tengah akhir
                const finalTop = (vH - finalH) / 2;
                const finalLeft = (vW - finalW) / 2;

                // Animasi Pembesaran Mulus
                // Kita tetap menggunakan objectFit: 'cover' selama di jalan, lalu mendarat di bentuk aslinya
                gsap.to(imgTarget, {
                    top: finalTop,
                    left: finalLeft,
                    width: finalW,
                    height: finalH,
                    borderRadius: "15px",
                    duration: 0.8,
                    ease: "power3.inOut" // Easings power3/expo memberikan efek swoop yang pas
                });


            }

            window.closeLightbox = function() {
                const modal = document.getElementById('lightboxModal');
                const imgTarget = document.getElementById('lightboxImage');
                const closeBtn = document.getElementById('lightboxClose');

                if (!activeLightboxImg) {
                    modal.style.display = 'none';
                    modal.classList.remove('active');
                    if (window.lenis) window.lenis.start();
                    document.body.style.overflow = '';
                    return;
                }

                // 1. Dapatkan posisi mutakhir slot gambar tersebut di dalam carousel bilamana user sempat scroll
                const rect = activeLightboxImg.getBoundingClientRect();

                // Animasikan Layar & Tombol X menghilang
                gsap.to(modal, {
                    backgroundColor: "rgba(0,0,0,0)",
                    pointerEvents: "none",
                    duration: 0.7,
                    ease: "power2.inOut"
                });
                gsap.to(closeBtn, {
                    opacity: 0,
                    rotation: 90,
                    scale: 0.5,
                    duration: 0.4,
                    ease: "power2.in"
                });

                // 2. Terbangkan KEMBALI gambar raksasa mengecil masuk persis ke slot yang menunggunya di carousel
                // Kita kembalikan objectFit nya ke 'cover' agar dia "terpotong" lagi masuk ke dalam bentuk kartunya.
                gsap.to(imgTarget, {
                    top: rect.top,
                    left: rect.left,
                    width: rect.width,
                    height: rect.height,
                    borderRadius: "11px",
                    objectFit: "cover",
                    duration: 0.7,
                    ease: "expo.inOut",
                    onComplete: () => {
                        // Munculkan kembali paku payung carousel asli
                        gsap.set(activeLightboxImg, {
                            opacity: 1
                        });

                        // Bersihkan panggung
                        modal.style.display = 'none';
                        modal.classList.remove('active');
                        imgTarget.style.display = 'none';
                        closeBtn.style.display = 'none';

                        activeLightboxImg = null;
                        activeLightboxItem = null;

                        // Lanjutkan perputaran slideshow
                        if (typeof startAutoSlide === 'function') startAutoSlide();

                        // Lanjutkan Scroll (Lenis & CSS)
                        if (window.lenis) window.lenis.start();
                        document.body.style.overflow = '';
                    }
                });
            };

            // Fitur: Tutup dengan Keyboard (Esc)
            window.addEventListener('keydown', function(e) {
                const modal = document.getElementById('lightboxModal');
                if (modal && modal.classList.contains('active')) {
                    if (e.key === 'Escape') closeLightbox();
                }
            });

            // Tutup lightbox jika mengklik background atau lukisannya sendiri
            document.getElementById('lightboxModal').addEventListener('click', closeLightbox);
            document.getElementById('lightboxImage').addEventListener('click', closeLightbox);

            // Navigation Arrows (anti-spam)
            btnPrev.addEventListener('click', () => cfSlide(-1));
            btnNext.addEventListener('click', () => cfSlide(1));

            // Bootstrap
            updateCoverflow();

            // Efek reveal mulus menggunakan autoAlpha GSAP (otomatis handle visibility:hidden & opacity:0 dari CSS)
            gsap.to('.coverflow-wrapper', {
                autoAlpha: 1,
                duration: 0,
                ease: "power2.out",
                delay: 0.1
            });

            // --- AUTO-SLIDE (Setiap 4 Detik) ---
            let cfAutoSlideInterval;

            function startAutoSlide() {
                // Jangan jalankan timer if lightbox is open
                const modal = document.getElementById('lightboxModal');
                if (modal && modal.classList.contains('active')) return;

                clearInterval(cfAutoSlideInterval); // Cegah double timer
                cfAutoSlideInterval = setInterval(() => {
                    cfSlide(1);
                }, 4000);
            }

            function stopAutoSlide() {
                clearInterval(cfAutoSlideInterval);
            }

            // Mulai auto-slide saat halaman dimuat pertama kali
            startAutoSlide();

            // Mouse Drag & Touch Swipe
            let startX = 0;
            let isDraggingCF = false;

            // Mouse Events
            cfWrapper.addEventListener('mousedown', (e) => {
                isDraggingCF = true;
                startX = e.clientX;
                cfWrapper.style.cursor = 'grabbing';
            });

            window.addEventListener('mousemove', (e) => {
                if (!isDraggingCF) return;
                const diff = e.clientX - startX;

                // Jika digeser lebih dari 50px, pindah slide
                if (diff > 50) {
                    cfSlide(-1);
                    isDraggingCF = false; // Stop tracking until next mousedown
                    startX = e.clientX; // Reset startX
                } else if (diff < -50) {
                    cfSlide(1);
                    isDraggingCF = false;
                    startX = e.clientX;
                }
            });

            window.addEventListener('mouseup', () => {
                isDraggingCF = false;
                cfWrapper.style.cursor = '';
            });

            // Touch Events
            cfWrapper.addEventListener('touchstart', (e) => {
                isDraggingCF = true;
                startX = e.touches[0].clientX;
            });

            window.addEventListener('touchmove', (e) => {
                if (!isDraggingCF) return;
                const diff = e.touches[0].clientX - startX;

                if (diff > 40) {
                    cfSlide(-1);
                    isDraggingCF = false;
                    startX = e.touches[0].clientX;
                } else if (diff < -40) {
                    cfSlide(1);
                    isDraggingCF = false;
                    startX = e.touches[0].clientX;
                }
            });

            window.addEventListener('touchend', () => {
                isDraggingCF = false;
            });

            // ========== GSAP MAGNETIC + GOLD FILL HOVER — 100% IDENTIK panel menu ==========
            [btnPrev, btnNext].forEach(btn => {
                const btnFill = btn.querySelector('.btn-fill');
                let rect = null;

                // --- MOUSEENTER (100% identik floating-menu-btn) ---
                btn.addEventListener('mouseenter', function() {
                    rect = btn.getBoundingClientRect();
                    if (btnFill) {
                        gsap.killTweensOf(btnFill);
                        gsap.set(btnFill, {
                            top: "100%",
                            borderRadius: "50%"
                        });
                        gsap.to(btnFill, {
                            top: "-10px",
                            borderRadius: "50%",
                            duration: 0.4,
                            ease: "power3.out"
                        });

                        // Shadow & background ke gold (persis floating-menu-btn)
                        gsap.killTweensOf(btn, "boxShadow,backgroundColor");
                        gsap.to(btn, {
                            boxShadow: "0 10px 20px rgba(197, 165, 90, 0.4)",
                            duration: 0.4,
                            ease: "power3.out"
                        });
                        gsap.to(btn, {
                            backgroundColor: "#c5a55a",
                            duration: 0.1,
                            delay: 0.3
                        });
                    }
                });

                // --- MOUSEMOVE (100% identik floating-menu-btn) ---
                btn.addEventListener('mousemove', function(e) {
                    if (!rect) rect = btn.getBoundingClientRect();

                    const centerX = rect.left + window.scrollX + rect.width / 2;
                    const centerY = rect.top + window.scrollY + rect.height / 2;

                    const x = e.pageX - centerX;
                    const y = e.pageY - centerY;

                    let innerContent = btn.querySelector('.btn-text-inner');

                    // Multiplier identik panel menu: 0.45
                    gsap.to(btn, {
                        x: x * 0.45,
                        y: y * 0.45,
                        duration: 1.5,
                        ease: "power4.out"
                    });

                    // Parallax inner identik panel menu: 0.25
                    if (innerContent) {
                        gsap.to(innerContent, {
                            x: x * 0.25,
                            y: y * 0.25,
                            duration: 1.5,
                            ease: "power4.out"
                        });
                    }
                });

                // --- MOUSELEAVE (100% identik floating-menu-btn) ---
                btn.addEventListener('mouseleave', function() {
                    rect = null;

                    if (btnFill) {
                        gsap.killTweensOf(btnFill);
                        // Fill keluar ke ATAS (persis panel menu: -150px, bukan 100%)
                        gsap.to(btnFill, {
                            top: "-150px",
                            borderRadius: "50%",
                            duration: 0.4,
                            ease: "power3.out"
                        });

                        // Background INSTAN kembali ke maroon (persis panel menu: gsap.set)
                        gsap.killTweensOf(btn, "boxShadow,backgroundColor");
                        gsap.set(btn, {
                            backgroundColor: "#8B1A1A"
                        });
                        gsap.to(btn, {
                            boxShadow: "0 10px 20px rgba(139, 26, 26, 0.3)",
                            duration: 0.4,
                            ease: "power3.out"
                        });
                    }

                    let innerContent = btn.querySelector('.btn-text-inner');

                    // Bounce elastis kembali ke posisi asal (persis panel menu: 1.5s, elastic.out(1, 0.3))
                    gsap.to(btn, {
                        x: 0,
                        y: 0,
                        duration: 1.5,
                        ease: "elastic.out(1, 0.3)"
                    });

                    if (innerContent) {
                        gsap.to(innerContent, {
                            x: 0,
                            y: 0,
                            duration: 1.5,
                            ease: "elastic.out(1, 0.3)"
                        });
                    }
                });
            });

            // Hentikan auto-slide saat ada interaksi user
            cfWrapper.addEventListener('mouseenter', stopAutoSlide);
            cfWrapper.addEventListener('mouseleave', startAutoSlide);
            if (cfWrapper.parentElement) {
                cfWrapper.parentElement.addEventListener('touchstart', stopAutoSlide);
                cfWrapper.parentElement.addEventListener('touchend', startAutoSlide);
            }
            // ========== GSAP LENIS ANIMASI UNTUK JUDUL PAROKI ==========
            const titleElement = document.getElementById('mainParokiTitle');
            if (titleElement) {
                // Memecah teks menjadi kata untuk di-animasikan satu per satu (Stagger effect)
                // Karena kita dilarang pakai script ribet/library berat seperti SplitText, kita buat fungsi split sederhana
                const text = titleElement.innerText;
                titleElement.innerHTML = '';

                const words = text.trim().split(' ').filter(w => w.length > 0);
                words.forEach((word, index) => {
                    const wordSpan = document.createElement('span');
                    // Guna style overflow hidden agar bisa efek reveal/muncul dari atas garis tak terlihat
                    wordSpan.style.display = 'inline-block';
                    wordSpan.style.overflow = 'hidden';
                    wordSpan.style.verticalAlign = 'middle';
                    wordSpan.style.lineHeight = '1.2';
                    wordSpan.style.paddingTop = '4px'; // Mencegah huruf terpotong atas
                    wordSpan.style.paddingBottom = '4px'; // Mencegah huruf terpotong bawah
                    // Spasi setelah setiap kata kecuali yang terakhir
                    if (index < words.length - 1) wordSpan.style.marginRight = '10px';

                    const innerSpan = document.createElement('span');
                    innerSpan.innerText = word;
                    innerSpan.style.display = 'inline-block';
                    innerSpan.className = 'title-word';

                    wordSpan.appendChild(innerSpan);
                    titleElement.appendChild(wordSpan);
                });

                // Munculkan container utama secara instan via opacity
                gsap.to('#captionParoki', {
                    opacity: 1,
                    duration: 0.1
                });

                // Animasikan tiap kata muncul dari atas ke bawah menggunakan GSAP
                // Gunakan opacity murni agar tidak ter-overwrite state visibility dari ScrollTrigger
                gsap.fromTo('.title-word', {
                    y: '-100%',
                    opacity: 0
                }, {
                    y: '0%',
                    opacity: 1,
                    duration: 0.7,
                    stagger: 0.05,
                    ease: "power3.out",
                    delay: 0.3 // Timer delay agar load pas dengan navbar
                });
            }

            // ========== GSAP LENIS ANIMASI UNTUK TOMBOL CAROUSEL ==========
            // Animasikan tombol kiri dan kanan carousel agar bergeser dari samping
            // Terlihat seperti dilempar memutar dan berhenti mendadak namun mulus (expo.out / power4.out)
            gsap.fromTo('.coverflow-btn.prev', {
                x: -150,
                opacity: 0,
                rotation: -110
            }, {
                x: 0,
                opacity: 1,
                rotation: 0,
                duration: 1.2,
                ease: "expo.out",
                delay: 0.1
            });

            gsap.fromTo('.coverflow-btn.next', {
                x: 150,
                opacity: 0,
                rotation: 110
            }, {
                x: 0,
                opacity: 1,
                rotation: 0,
                duration: 1.2,
                ease: "expo.out",
                delay: 0.1
            });

            // ========== GSAP PUPIL MATA MELIRIK KURSOR ==========
            const eyeOverlays = document.querySelectorAll('.coverflow-overlay');
            eyeOverlays.forEach(overlay => {
                const eyeSvg = overlay.querySelector('.eye-icon');
                if (!eyeSvg) return;

                // Elemen yang akan kita gerakkan hanya bola matanya (circle/pupil)
                const pupil = eyeSvg.querySelector('circle');
                if (!pupil) return;

                overlay.addEventListener('mousemove', (e) => {
                    const rect = overlay.getBoundingClientRect();

                    // Hitung rentang posisi mouse (dari -1 ke 1) relatif terhadap titik tengah
                    const xProgress = ((e.clientX - rect.left) / rect.width) * 2 - 1;
                    const yProgress = ((e.clientY - rect.top) / rect.height) * 2 - 1;

                    // Batasi pergerakan pupil maksimal 4 pixel ke segala arah agar tidak keluar dari area putih matanya
                    const maxMovement = 2.2;

                    gsap.to(pupil, {
                        x: xProgress * maxMovement,
                        y: yProgress * maxMovement,
                        duration: 0.15,
                        ease: "power1.out"
                    });
                });

                // Saat kursor meninggalkan gambar, bola mata kembali melirik ke tengah
                overlay.addEventListener('mouseleave', () => {
                    gsap.to(pupil, {
                        x: 0,
                        y: 0,
                        duration: 0.5,
                        ease: "back.out(1.5)"
                    });
                });
            });

            // ========== GSAP LENIS ANIMASI SCROLL 3D PADA CAROUSEL ==========
            // Memberikan efek putaran 3D (perspective shift) saat di-scroll naik/turun
            const carouselContainer = document.querySelector('.coverflow-carousel');
            if (carouselContainer) {
                gsap.fromTo(carouselContainer, {
                    rotationX: 15, // Mulai dari agak menunduk ke bawah
                    y: '0%', // Mulai di posisi normal
                    scale: 0.95
                }, {
                    rotationX: -5, // Berubah mendongak ke atas saat di-scroll
                    y: '15%', // Bergerak lebih lambat ke bawah (parallax standar) agar tidak bertabrakan dengan arah atas kartu-kartu di bawah
                    scale: 1,
                    ease: "none",
                    scrollTrigger: {
                        trigger: carouselContainer,
                        start: "top 90%",
                        end: "bottom 10%",
                        scrub: 1
                    }
                });
            }

            // ========== GSAP LENIS ANIMASI SCROLL 3D PADA JUDUL ==========
            // Memberikan efek putaran 3D (perspective shift) pada judul saat di-scroll, seperti carousel
            const captionParoki = document.getElementById('captionParoki');
            if (captionParoki) {
                gsap.fromTo(captionParoki, {
                    rotationX: 12,
                    y: 0,
                    scale: 0.96
                }, {
                    rotationX: -5,
                    y: 40, // Bergerak proporsional ke bawah selaras dengan carousel
                    scale: 1,
                    ease: "none",
                    scrollTrigger: {
                        trigger: captionParoki,
                        start: "top 90%",
                        end: "bottom 20%",
                        scrub: 1
                    }
                });
            }

        });
    </script>
    <script src="navbar.js?v=6"></script>
</body>

</html>
