// Global Modal Functions
window.openCampaignModal = function () {
    const modal = document.getElementById('campaignModal');
    if (modal) {
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
};

window.closeCampaignModal = function () {
    const modal = document.getElementById('campaignModal');
    if (modal) {
        modal.classList.remove('active');
        document.body.style.overflow = 'auto';
    }
};

window.openWelcomeModal = function () {
    const modal = document.getElementById('welcomeModal');
    if (modal) {
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
};

window.closeWelcomeModal = function () {
    const modal = document.getElementById('welcomeModal');
    if (modal) {
        modal.classList.remove('active');
        document.body.style.overflow = 'auto';
    }
};

document.addEventListener('DOMContentLoaded', () => {

    /* =======================================
       1. Navbar Scroll Effect & Active Links
       ======================================= */
    const navbar = document.getElementById('navbar');

    window.addEventListener('scroll', () => {
        if (window.scrollY > 50) {
            navbar.classList.add('scrolled');
        } else {
            navbar.classList.remove('scrolled');
        }
    });

    /* =======================================
       2. Mobile Menu Toggle
       ======================================= */
    const hamburger = document.getElementById('hamburger');
    const mobileMenu = document.getElementById('mobile-menu');
    const mobileLinks = document.querySelectorAll('.mobile-link, .mobile-cta');

    hamburger.addEventListener('click', () => {
        mobileMenu.classList.toggle('open');
        const icon = mobileMenu.classList.contains('open') ? 'close-outline' : 'menu-outline';
        hamburger.innerHTML = `<ion-icon name="${icon}"></ion-icon>`;
    });

    mobileLinks.forEach(link => {
        link.addEventListener('click', () => {
            mobileMenu.classList.remove('open');
            hamburger.innerHTML = `<ion-icon name="menu-outline"></ion-icon>`;
        });
    });

    /* =======================================
       3. Scroll Reveal Animations
       ======================================= */
    const revealElements = document.querySelectorAll('.reveal');

    const revealOptions = {
        threshold: 0.1,
        rootMargin: "0px 0px -50px 0px"
    };

    const revealObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('active');
                observer.unobserve(entry.target);
            }
        });
    }, revealOptions);

    revealElements.forEach(el => revealObserver.observe(el));

    /* =======================================
       4. Data: Coordinators & Map Pins
       ======================================= */
    const coordinators = [
        { id: 1, name: "Hon Adebayo Adeyemi", role: "LGA Coordinator", lga: "Ado Ekiti", lat: 7.6211, lng: 5.2215, phone: "08142240018", img: "https://ui-avatars.com/api/?name=Adebayo+Adeyemi&background=0C6B40&color=fff&size=256" },
        { id: 2, name: "Afuye Adewale Omotayo", role: "LGA Coordinator", lga: "Ikere", lat: 7.4994, lng: 5.2294, phone: "07036384555", img: "https://ui-avatars.com/api/?name=Afuye+Adewale+Omotayo&background=FBB040&color=fff&size=256" },
        { id: 3, name: "Hon Kole Komolafe", role: "LGA Coordinator", lga: "Efon", lat: 7.6469, lng: 4.9654, phone: "08038482259", img: "https://ui-avatars.com/api/?name=Kole+Komolafe&background=0C6B40&color=fff&size=256" },
        { id: 4, name: "Mr Bankole Segun", role: "LGA Coordinator", lga: "Moba", lat: 8.0000, lng: 5.0833, phone: "08039737392", img: "https://ui-avatars.com/api/?name=Bankole+Segun&background=FBB040&color=fff&size=256" },
        { id: 5, name: "Mrs Yetunde Aribasoye", role: "LGA Coordinator", lga: "Ikole", lat: 7.7983, lng: 5.5145, phone: "07064479512", img: "https://ui-avatars.com/api/?name=Yetunde+Aribasoye&background=0C6B40&color=fff&size=256" },
        { id: 6, name: "Ajayi Ebenezer Oluropo", role: "LGA Coordinator", lga: "Ise/Orun", lat: 7.4583, lng: 5.4167, phone: "09023752908", img: "https://ui-avatars.com/api/?name=Ajayi+Ebenezer+Oluropo&background=FBB040&color=fff&size=256" },
        { id: 7, name: "Ajiboye Boboye", role: "LGA Coordinator", lga: "Emure", lat: 7.4333, lng: 5.4667, phone: "08060616486", img: "https://ui-avatars.com/api/?name=Ajiboye+Boboye&background=0C6B40&color=fff&size=256" },
        { id: 8, name: "Adeleye Alufa", role: "LGA Coordinator", lga: "Ijero", lat: 7.8167, lng: 5.0667, phone: "07066908189", img: "https://ui-avatars.com/api/?name=Adeleye+Alufa&background=FBB040&color=fff&size=256" },
        { id: 9, name: "Ogunlade Tunde", role: "LGA Coordinator", lga: "Oye", lat: 7.7981, lng: 5.3308, phone: "08143912680", img: "https://ui-avatars.com/api/?name=Ogunlade+Tunde&background=0C6B40&color=fff&size=256" },
        { id: 10, name: "Ogunsakin Folasade", role: "LGA Coordinator", lga: "Gbonyin", lat: 7.6166, lng: 5.4667, phone: "08163107062", img: "https://ui-avatars.com/api/?name=Ogunsakin+Folasade&background=FBB040&color=fff&size=256" },
        { id: 11, name: "Babatunde Damilare", role: "LGA Coordinator", lga: "Ilejemeje", lat: 7.9667, lng: 5.1833, phone: "08101819599", img: "https://ui-avatars.com/api/?name=Babatunde+Damilare&background=0C6B40&color=fff&size=256" },
        { id: 12, name: "Oluwatuyi Kehinde", role: "LGA Coordinator", lga: "Ekiti East", lat: 7.7500, lng: 5.6167, phone: "08061614328", img: "https://ui-avatars.com/api/?name=Oluwatuyi+Kehinde&background=FBB040&color=fff&size=256" },
        { id: 13, name: "Mr Felix Olajide", role: "LGA Coordinator", lga: "Ekiti South West", lat: 7.4833, lng: 5.0833, phone: "08030701080", img: "https://ui-avatars.com/api/?name=Felix+Olajide&background=0C6B40&color=fff&size=256" },
        { id: 14, name: "Kemisola Oke", role: "LGA Coordinator", lga: "Ekiti West", lat: 7.6974, lng: 4.9602, phone: "08106945857", img: "https://ui-avatars.com/api/?name=Kemisola+Oke&background=FBB040&color=fff&size=256" },
        { id: 15, name: "Oluwaseun Ajijola", role: "LGA Coordinator", lga: "Irepodun/Ifelodun", lat: 7.6521, lng: 5.3121, phone: "08163755213", img: "https://ui-avatars.com/api/?name=Oluwaseun+Ajijola&background=0C6B40&color=fff&size=256" },
        { id: 16, name: "Johnson Folarin", role: "LGA Coordinator", lga: "Ido Osi", lat: 7.8500, lng: 5.1667, phone: "07065544834", img: "https://ui-avatars.com/api/?name=Johnson+Folarin&background=FBB040&color=fff&size=256" }
    ];

    // Inject Coordinators to Grid (if team-grid exists)
    const teamGrid = document.getElementById('team-grid');
    if (teamGrid) {
        coordinators.forEach(member => {
            const el = document.createElement('div');
            el.className = 'team-member card';
            el.innerHTML = `
                <img src="${member.img}" alt="${member.name}">
                <h4 style="font-size: 1rem;">${member.name}</h4>
                <p class="role" style="font-size: 0.8rem;">${member.role}</p>
                <div style="margin-top: 12px; display: flex; flex-direction: column; gap: 4px;">
                    <p class="lga" style="font-size: 0.85rem;"><ion-icon name="location-outline"></ion-icon> ${member.lga}</p>
                    <p class="phone" style="font-size: 0.85rem; color: var(--cbm-gray-dark); display: flex; align-items: center; justify-content: center; gap: 4px;"><ion-icon name="call-outline"></ion-icon> ${member.phone}</p>
                </div>
            `;
            teamGrid.appendChild(el);
        });
    }

    // Leadership Council Data
    const councilMembers = [
        { name: "Asiwaju K. Oluwafemi", role: "State Director", img: "Council/f8f950be-0501-425f-a675-54930afe5c80.JPG" },
        { name: "Prince Adegboye Olumide Festus", role: "State Deputy Director", img: "Council/a9c94ea8-27ea-4c0c-96d8-d7018394ff2e.JPG" },
        { name: "Oluwaseun Ajifowobaje", role: "State Secretary", img: "Council/313ee093-aaa1-40ff-957c-c22bec371694.JPG" },
        { name: "Babatola Oyewole", role: "Assistant Secretary", img: "Council/dacebfa9-e851-48f5-9407-07c104cfd71a.JPG" },
        { name: "Oluwatosin Fadipe", role: "Director of Human Resources", img: "Council/a675b4db-0871-4bf5-8f1b-2db2c4ada25d.JPG" },
        { name: "Aluko Aanu Albert", role: "Deputy State Coordinator", img: "Council/6f053b0a-25e3-4752-b92d-de4f88b43a95.JPG" },
        { name: "Olusola Adenijo", role: "State Treasurer", img: "Council/9be40cb4-6266-41c1-9faa-b305ef77e151.JPG" },
        { name: "Alofe Ayo Moses", role: "Director of Media and Communication", img: "Council/cf9a6d8c-5c4f-458c-a6b4-f160880628c5.JPG" },
        { name: "Tiwaloluwa Omope", role: "Director of Strategy, Policy and ICT", img: "Council/77054efa-45ab-44d3-adab-000f3a498f8f.JPG" },
        { name: "Barr. Shola Gabriel", role: "Legal Adviser", img: "Council/3fc49ff3-f761-48f6-8510-b83a74cf2f7e.JPG" },
        { name: "Owolewa Taiwo", role: "Director of Student Mobilization", img: "Council/58efb985-707d-4484-8701-f0dd5e495255.JPG" },
        { name: "Dr. Ayomide Olanipekun", role: "Director of Medical Outreach", img: "Council/700dfed0-ce8c-44ab-af73-9ff577d20ee9.JPG" },
        { name: "Dr. Habibat Fayoke Yusuf", role: "Director of Muslim Affairs", img: "Council/4c868db4-32dc-46b1-bc8e-a20d482c4559.JPG" },
        { name: "Amb. Olu-Ajayi Maxwell Olusegun", role: "Director Contact & Mobilization", img: "Council/8ae55f0a-92eb-4e80-8149-fb43e75cdb23.JPG" },
        { name: "Ogundile Abayomi", role: "Director of New Media", img: "Council/7b343467-b797-44af-a80f-b6d838a3bcc6.JPG" },
        { name: "Oluwaseyi Lawal Ayodele", role: "Director of Technology, Market and Commerce", img: "Council/88ee723a-f781-45b9-b4ae-aa977cef67b2.JPG" },
        { name: "Asiwaju Oladimeji", role: "Director of Research and Documentation", img: "Council/f7b7405f-9011-4dc4-99ba-7185b1c46e08.JPG" },
        { name: "Ademola Okunola", role: "Director of Branding and Event Coordination", img: "Council/45d02f02-be50-4efb-b180-eb72d1e027a9.JPG" },
        { name: "Rasheed Adewunmi", role: "Director of Support Groups and Coalition Coordination", img: "Council/9013ab62-cfda-49de-8fc0-d94e9f057df6.JPG" },
        { name: "Owoseni Bamiyo Morakinyo", role: "Asst. Organizing Secretary", img: "Council/7e76a48c-cb30-4e78-9730-0da71203774f.JPG" },
        { name: "Olasunbo Abimbola Debby", role: "Director of Market Women and Traders Mobilization", img: "Council/887e2f35-a747-4746-ae90-f7d2e39c172b.JPG" },
        { name: "Dr. Sikiru Olowoyo", role: "Director of Informal Sector Mobilization", img: "Council/9a423873-60b6-4c5f-94c0-a1425b473856.JPG" },
        { name: "Sola Ifeoluwa Gbelee", role: "Spokesperson", img: "Council/de7b06a0-9a9c-4098-8ce3-1a247b204b70.JPG" },
        { name: "Michael Adeshina", role: "Director of Entertainment", img: "Council/33219f38-c7f0-4f4c-8d7d-c9b8a6de862f.JPG" },
    ];

    const councilGrid = document.getElementById('council-grid');
    const councilGridFull = document.getElementById('council-grid-full');
    
    // Helper to render a member
    const renderMember = (member, container) => {
        const el = document.createElement('div');
        el.className = 'team-member card';
        
        el.innerHTML = `
            <div class="member-img-wrapper" style="width: 100%; aspect-ratio: 1; border-radius: var(--border-radius); overflow: hidden; margin-bottom: 16px; border: 1px solid var(--cbm-white); box-shadow: var(--shadow-md);">
                <img src="${member.img}" alt="${member.name}" style="width: 100%; height: 100%; object-fit: cover; object-position: top;">
            </div>
            <h4 style="font-size: 1.1rem; margin-bottom: 4px;">${member.name}</h4>
            <p class="role" style="font-size: 0.85rem; color: var(--cbm-green); font-weight: 600;">${member.role}</p>
        `;
        container.appendChild(el);
    };

    if (councilGrid) {
        // Home page: Skip index 0 (State Director) since it's hardcoded at the top, and show next 4
        councilMembers.slice(1, 5).forEach((member) => renderMember(member, councilGrid));
    }
    
    if (councilGridFull) {
        // Team page: Show all except State Director (who might also be hardcoded at top of team page)
        councilMembers.slice(1).forEach((member) => renderMember(member, councilGridFull));
    }

    /* =======================================
       5. Interactive Map Logic (Leaflet)
       ======================================= */
    const mapBoard = document.getElementById('map-board');

    // Create Map using Leaflet if available
    if (mapBoard && typeof L !== 'undefined') {
        // Initialize map centered roughly on Ekiti State
        const map = L.map('map-board', {
            zoomControl: false,
            scrollWheelZoom: false // Prevent accidentally zooming while scrolling page
        }).setView([7.65, 5.25], 10);

        // Add CartoDB Light basemap for that premium, clean Stripe-like look
        L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>',
            subdomains: 'abcd',
            maxZoom: 20
        }).addTo(map);

        coordinators.forEach(coord => {
            // Reusing our custom CSS pin for the marker
            const customIcon = L.divIcon({
                className: 'custom-leaflet-pin',
                html: '<div class="map-pin" style="position:relative; transform:translate(-50%, -50%); left:16px; top:16px;"></div>',
                iconSize: [32, 32],
                iconAnchor: [16, 16],
                popupAnchor: [0, -16]
            });

            // Reusing our tooltip HTML for the popup
            const popupContent = `
                <div class="map-tooltip active" style="position:relative; box-shadow:none; padding:16px; width:100%; transform:none;">
                    <div class="tt-header">
                        <img src="${coord.img}" alt="Avatar">
                        <div class="tt-info">
                            <h4>${coord.name}</h4>
                            <span class="tt-role">${coord.role}</span>
                        </div>
                    </div>
                    <div class="tt-body" style="display: flex; flex-direction: column; gap: 6px;">
                        <div style="display: flex; align-items: center; gap: 6px;"><ion-icon name="location-outline" style="color: var(--cbm-green);"></ion-icon> <span>${coord.lga}</span></div>
                        <div style="display: flex; align-items: center; gap: 6px; color: var(--cbm-gray-dark);"><ion-icon name="call-outline" style="color: var(--cbm-green);"></ion-icon> <span>${coord.phone}</span></div>
                    </div>
                </div>
            `;

            L.marker([coord.lat, coord.lng], { icon: customIcon })
                .addTo(map)
                .bindPopup(popupContent, {
                    closeButton: false,
                    minWidth: 240,
                    className: 'custom-leaflet-popup'
                });
        });
    }

    /* =======================================
       6. Form Submission Simulation
       ======================================= */
    const regForm = document.getElementById('registrationForm');
    if (regForm) {
        regForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const btn = regForm.querySelector('button');
            const originalText = btn.textContent;

            btn.textContent = 'Processing...';
            btn.disabled = true;
            try {
                const formData = new FormData(regForm);
                const response = await fetch('submit.php', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (result.status === 'success') {
                    // Show Welcome Modal
                    if (typeof openWelcomeModal === 'function') {
                        openWelcomeModal();
                    } else {
                        alert("Welcome to the movement! Your registration was successful.");
                    }
                    regForm.reset();
                } else {
                    alert("Error: " + result.message);
                }
            } catch (error) {
                console.error("Submission failed:", error);
                alert("Something went wrong. Please try again.");
            } finally {
                btn.textContent = originalText;
                btn.disabled = false;
            }
        });
    }

    /* =======================================
       7. Headless WordPress Integration
       ======================================= */
    const WP_API_BASE = 'https://blog.cbmekiti.com/wp-json/wp/v2';

    // Utility to format date
    const formatDate = (dateString) => {
        const options = { year: 'numeric', month: 'long', day: 'numeric' };
        return new Date(dateString).toLocaleDateString('en-US', options);
    };

    // Utility to decode HTML entities
    const decodeHTML = (html) => {
        const txt = document.createElement("textarea");
        txt.innerHTML = html;
        return txt.value;
    };

    // Render a single news card
    const createPostCard = (post) => {
        const title = decodeHTML(post.title.rendered);
        let excerpt = decodeHTML(post.excerpt.rendered).replace(/(<([^>]+)>)/gi, "");
        if (excerpt.length > 120) excerpt = excerpt.substring(0, 120) + '...';

        const date = formatDate(post.date);

        let imgUrl = 'https://images.unsplash.com/photo-1529156069898-49953e39b3ac?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80'; // fallback
        if (post._embedded && post._embedded['wp:featuredmedia'] && post._embedded['wp:featuredmedia'][0] && post._embedded['wp:featuredmedia'][0].source_url) {
            imgUrl = post._embedded['wp:featuredmedia'][0].source_url;
        } else if (post.content && post.content.rendered) {
            // Extract first image from content if featured media is blocked/missing
            const imgMatch = post.content.rendered.match(/<img[^>]+src="([^">]+)"/);
            if (imgMatch && imgMatch[1]) {
                imgUrl = imgMatch[1];
            }
        }

        return `
            <a href="blog-info.html?id=${post.id}" class="news-card" data-post-url="${post.link}">
                <img src="${imgUrl}" alt="${title}" class="news-img dynamic-img">
                <div class="news-content">
                    <span class="news-date">${date}</span>
                    <h3 style="font-size: 1.25rem;">${title}</h3>
                    <p style="font-size: 0.95rem;">${excerpt}</p>
                </div>
            </a>
        `;
    };

    // Fetch Multiple Posts
    const fetchPosts = async (containerId, limit) => {
        const container = document.getElementById(containerId);
        if (!container) return;

        try {
            const res = await fetch(`${WP_API_BASE}/posts?_embed&per_page=${limit}`);
            if (!res.ok) throw new Error('Network response was not ok');
            const posts = await res.json();

            if (posts.length === 0) {
                container.innerHTML = `<div class="text-center" style="grid-column: 1 / -1;"><p>No updates available yet.</p></div>`;
                return;
            }

            container.innerHTML = posts.map(post => createPostCard(post)).join('');

            // Background fetch true featured images bypassing API block
            const cards = container.querySelectorAll('.news-card');
            cards.forEach(async (card) => {
                try {
                    const url = card.getAttribute('data-post-url');
                    if (!url) return;
                    const res = await fetch(url);
                    const html = await res.text();
                    const match = html.match(/<meta\s+property=["']og:image["']\s+content=["']([^"']+)["']/i);
                    if (match && match[1]) {
                        card.querySelector('.dynamic-img').src = match[1];
                    }
                } catch (e) { }
            });
        } catch (error) {
            console.error('Error fetching WP posts:', error);
            container.innerHTML = `<div class="text-center" style="grid-column: 1 / -1;"><p style="color:red;">Failed to load updates. Please try again later.</p></div>`;
        }
    };

    // Fetch Single Post
    const fetchSinglePost = async () => {
        const container = document.getElementById('single-post-container');
        if (!container) return;

        const urlParams = new URLSearchParams(window.location.search);
        const postId = urlParams.get('id');

        if (!postId) {
            container.innerHTML = `<div class="text-center" style="padding: 64px 0;"><h2>Post Not Found</h2><a href="blogs.html" class="btn btn-primary m-t-1">Return to News</a></div>`;
            return;
        }

        try {
            const res = await fetch(`${WP_API_BASE}/posts/${postId}?_embed`);
            if (!res.ok) throw new Error('Post not found');
            const post = await res.json();

            const title = decodeHTML(post.title.rendered);
            const content = post.content.rendered;
            const date = formatDate(post.date);

            let imgUrl = 'https://images.unsplash.com/photo-1517486808906-6ca8b3f04846?ixlib=rb-4.0.3&auto=format&fit=crop&w=1200&q=80'; // fallback
            if (post._embedded && post._embedded['wp:featuredmedia'] && post._embedded['wp:featuredmedia'][0] && post._embedded['wp:featuredmedia'][0].source_url) {
                imgUrl = post._embedded['wp:featuredmedia'][0].source_url;
            } else if (content) {
                // Extract first image from content if featured media is blocked/missing
                const imgMatch = content.match(/<img[^>]+src="([^">]+)"/);
                if (imgMatch && imgMatch[1]) {
                    imgUrl = imgMatch[1];
                }
            }

            let authorName = "Media Team";
            let authorImg = "https://images.unsplash.com/photo-1506277886164-e25aa3f4ef7f?ixlib=rb-4.0.3&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80";
            if (post._embedded && post._embedded['author'] && post._embedded['author'][0]) {
                authorName = post._embedded['author'][0].name;
                if (post._embedded['author'][0].avatar_urls && post._embedded['author'][0].avatar_urls['96']) {
                    authorImg = post._embedded['author'][0].avatar_urls['96'];
                }
            }

            container.innerHTML = `
                <div style="margin-top: 24px;">
                    <span class="tag" style="background: var(--cbm-green-light); color: var(--cbm-green); padding: 6px 12px; margin-bottom: 16px;">General Updates</span>
                    <span class="news-date" style="display: inline-block; margin-left: 16px; color: var(--cbm-gray);">${date} &bull; By ${authorName}</span>
                </div>
                
                <h1 style="font-size: 3rem; margin: 16px 0 32px; line-height: 1.2;">${title}</h1>
                
                <img src="${imgUrl}" id="single-hero-img" alt="${title}" style="width: 100%; max-height: 500px; object-fit: cover; border-radius: 16px; margin-bottom: 48px; box-shadow: var(--shadow-md);">
                
                <div class="blog-content" style="font-size: 1.125rem; color: var(--cbm-gray-dark); line-height: 1.8;">
                    ${content}
                </div>

                <div class="author-box">
                    <img src="${authorImg}" alt="${authorName}">
                    <div>
                        <h4 style="margin-bottom: 4px; font-size: 1.1rem;">${authorName}</h4>
                        <p style="font-size: 0.9rem; color: var(--cbm-gray); margin: 0;">Official communications and updates from the central command.</p>
                    </div>
                </div>
            `;

            // Background fetch true featured image bypassing API block
            try {
                const htmlRes = await fetch(post.link);
                const htmlText = await htmlRes.text();
                const match = htmlText.match(/<meta\s+property=["']og:image["']\s+content=["']([^"']+)["']/i);
                if (match && match[1]) {
                    document.getElementById('single-hero-img').src = match[1];
                }
            } catch (e) { }
        } catch (error) {
            console.error('Error fetching single post:', error);
            container.innerHTML = `<div class="text-center" style="padding: 64px 0;"><h2 style="color:red;">Error loading article</h2><p>Please check your connection or try again later.</p></div>`;
        }
    };

    // Execute fetches
    fetchPosts('home-news-grid', 2);
    fetchPosts('all-news-grid', 9);
    fetchSinglePost();

    /* =======================================
       8. Image Slider Logic
       ======================================= */
    const sliderContainer = document.getElementById('main-slider');
    const sliderDots = document.querySelectorAll('.slider-indicators .dot');
    const prevBtn = document.getElementById('slider-prev');
    const nextBtn = document.getElementById('slider-next');

    if (sliderContainer) {
        let currentSlide = 0;
        const totalSlides = 4; // Since we have 4 slides
        let slideInterval;

        const updateSlider = () => {
            sliderContainer.style.transform = `translateX(-${currentSlide * 100}%)`;
            sliderDots.forEach((dot, idx) => {
                dot.style.opacity = idx === currentSlide ? '1' : '0.5';
            });
        };

        const nextSlide = () => {
            currentSlide = (currentSlide + 1) % totalSlides;
            updateSlider();
        };

        const prevSlide = () => {
            currentSlide = (currentSlide - 1 + totalSlides) % totalSlides;
            updateSlider();
        };

        // Event Listeners
        if(nextBtn) nextBtn.addEventListener('click', () => {
            nextSlide();
            resetInterval();
        });
        
        if(prevBtn) prevBtn.addEventListener('click', () => {
            prevSlide();
            resetInterval();
        });

        sliderDots.forEach(dot => {
            dot.addEventListener('click', (e) => {
                currentSlide = parseInt(e.target.getAttribute('data-index'));
                updateSlider();
                resetInterval();
            });
        });

        // Auto Slide
        const startInterval = () => {
            slideInterval = setInterval(nextSlide, 5000);
        };

        const resetInterval = () => {
            clearInterval(slideInterval);
            startInterval();
        };

        startInterval();
    }

});
