---
import { extractImageUrl, PAGE_ENTITY_ID } from '../../lib/functions.js';

interface OrcasitasItem {
    iframeSrc?: string;
    image?: string;
    imageSrc?: string;
    altImage?: string;
    description?: string;
    descriptionImage?: string;
    thumbnailUrl?: string;
    uploadDate?: string;
    author?: string;
    positionCompany?: string;
}

const {
    loadScript = true,
    items = [],
    slidesToShow = 5,
    slidesToScroll = 1,
}: { loadScript?: boolean; items?: OrcasitasItem[]; slidesToShow?: number; slidesToScroll?: number } = Astro.props;

// isPartOf hacia el nodo de página (#webpage por defecto). Genérico: opt-out con pageId="".
const { pageId = PAGE_ENTITY_ID, itemListId = '' } = Astro.props;

const carouselId = "glider-carousel-"+Math.floor(Math.random()*1000);
const buttonsId = "glider-carousel-buttons-"+Math.floor(Math.random()*1000);
const prevId = "glider-carousel-prev-"+Math.floor(Math.random()*1000);
const nextId = "glider-carousel-next-"+Math.floor(Math.random()*1000);

const randomId = Math.floor(Math.random() * 1000);

const escapeJson = (s = "") => String(s).replace(/<[^>]*>/g, '').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/[\n\r\t]+/g, ' ');

const buildVideoItem = (item: OrcasitasItem) => {
    const fields = [
        `"@type": "VideoObject"`,
        item.author ? `"name": "${escapeJson(item.author)}"` : '',
        item.description ? `"description": "${escapeJson(item.description)}"` : '',
        item.thumbnailUrl ? `"thumbnailUrl": "${escapeJson(extractImageUrl(item.thumbnailUrl))}"` : '',
        item.iframeSrc ? `"embedUrl": "${escapeJson(item.iframeSrc)}"` : '',
        item.uploadDate ? `"uploadDate": "${escapeJson(item.uploadDate)}"` : '',
        item.author ? `"author": { "@type": "Person", "name": "${escapeJson(item.author)}"${item.positionCompany ? `, "jobTitle": "${escapeJson(item.positionCompany)}"` : ''} }` : '',
    ].filter(Boolean).join(', ');
    return `{ ${fields} }`;
};

const buildImageItem = (item: OrcasitasItem) => {
    const fields = [
        `"@type": "ImageObject"`,
        item.image ? `"contentUrl": "${escapeJson(extractImageUrl(item.image))}"` : '',
        item.altImage ? `"name": "${escapeJson(item.altImage)}"` : '',
        item.descriptionImage ? `"description": "${escapeJson(item.descriptionImage)}"` : '',
    ].filter(Boolean).join(', ');
    return `{ ${fields} }`;
};

const structuredData = items.length > 0 ? `<script type="application/ld+json">
{
    "@context": "https://schema.org",
    "@type": "ItemList",${itemListId ? `
    "@id": "${itemListId}",` : ''}${pageId ? `
    "isPartOf": { "@id": "${pageId}" },` : ''}
    "numberOfItems": ${items.length},
    "itemListElement": [${items.map((item: OrcasitasItem, index: number) => `{
        "@type": "ListItem",
        "position": ${index + 1},
        "item": ${item.iframeSrc ? buildVideoItem(item) : buildImageItem(item)}
    }`).join(',')}]
}
</script>` : '';

---

    {loadScript && 
        <div>
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/glider-js@1/glider.min.css"/>
            <script is:inline src="https://cdn.jsdelivr.net/npm/glider-js@1/glider.min.js"></script>
        </div>
    }

    <style is:global>
        .glider {
            overflow: hidden;
        }
        .glider-track{
            display: flex;
            align-items: start !important;
        }
        .glider-dots {
            @media (max-width: 767px) {
                display: none !important;
            }
        }
    </style>
    <div class="w-full max-w-7xl">
        <div id={carouselId} class="glider w-full">
            {items.map((item, idx) => (
                <div class="flex flex-col items-center p-10 bg-white">
                {item.iframeSrc ? (
                    <>
                        <div class="w-full">
                            <span class={`popup-iframe-trigger-${randomId} cursor-pointer`} data-iframesrc={item.iframeSrc}>
                                <img src={item.imageSrc} alt={item.author || item.description || 'Video thumbnail'} width="400" height="225" loading="lazy" class="w-full h-full rounded-2xl p-2 transition-transform hover:scale-105 cursor-pointer"/>
                            </span>
                        </div>
                        {(item.description || item.author || item.positionCompany) && (
                            <div class="p-6 w-full flex-grow flex flex-col">
                                <div class="mt-2 flex items-center gap-2 flex-grow">
                                    <div class="flex flex-col text-[#262626] h-full">
                                        {item.description && (
                                            <p class="text-base font-inter font-normal leading-6 mb-6">{item.description}</p>
                                        )}
                                        {(item.author || item.positionCompany) && (
                                            <p class="text-sm font-semibold">
                                                {item.author}
                                                {item.author && item.positionCompany && <br />}
                                                {item.positionCompany}
                                            </p>
                                        )}
                                    </div>
                                </div>
                            </div>
                        )}
                    </>
                ) : (
                    <>
                        <img src={extractImageUrl(item.image)} alt={item.altImage} width="250" height="100" class={`${items.length === 1 ? '!max-w-[600px]' : items.length === 2 ? '!max-w-[400px]' : '!max-w-[250px]'} w-fit`} loading="lazy" />
                        <p>{item.descriptionImage}</p>
                    </>
                )}
                </div>
            ))}
        </div>
        <div id={buttonsId} class="carouselGlider hidden md:flex"></div>
    </div>

<div id={"popup-iframe-modal-" + randomId } class="fixed w-full h-full top-0 left-0 z-9999 hidden">
    <div class="flex flex-col justify-center items-center w-full h-full bg-gray-100/90 p-4">
        <div class="w-full flex justify-end">
            <button class="js-close-popup w-auto m-4 p-2 bg-white rounded transition-transform hover:scale-125 cursor-pointer">X</button>
        </div>
        <div class="w-full h-full flex items-center justify-center">
            <iframe
                title="Reproductor de vídeo"
                class="rounded-xl shadow-lg max-w-full md:max-w-3/4 aspect-video"
                src=""
                frameborder="0"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                allowfullscreen=""></iframe>
        </div>
    </div>
</div>

<script is:inline define:vars={{ randomId }}>

    const iframePopup = document.getElementById(`popup-iframe-modal-${randomId}`);
    document.querySelectorAll(`.popup-iframe-trigger-${randomId}`).forEach(btn => {
        btn.addEventListener('click', (e) => {
            const iframeSrc = btn.getAttribute('data-iframesrc');
            iframePopup.classList.remove('hidden');    
            iframePopup.querySelector('iframe').setAttribute('src', iframeSrc);          
        });
    });

    iframePopup.querySelector('.js-close-popup').addEventListener('click', () => {
        iframePopup.classList.add('hidden');
        iframePopup.querySelector('iframe').setAttribute('src', '');
    });

</script>
    

    <script is:inline define:vars={{carouselId, buttonsId, prevId, nextId, slidesToShow, slidesToScroll}}>
        document.addEventListener('DOMContentLoaded', function() {

            new Glider(document.querySelector('#' + carouselId), {

                // `auto` allows automatic responsive
                // width calculations
                slidesToShow: slidesToShow,
                slidesToScroll: '1',

                // should have been named `itemMinWidth`
                // slides grow to fit the container viewport
                // ignored unless `slidesToShow` is set to `auto`
                itemWidth: undefined,

                // if true, slides wont be resized to fit viewport
                // requires `itemWidth` to be set
                // * this may cause fractional slides
                exactWidth: false,

                // speed aggravator - higher is slower
                duration: .5,

                // dot container element or selector
                dots: '#' + buttonsId,

                // arrow container elements or selector
                arrows: {
                    prev: '#' + prevId,
                    // may also pass element directly
                    next: '#' + nextId
                },

                // allow mouse dragging
                draggable: true,
                // how much to scroll with each mouse delta
                dragVelocity: 3.3,

                // use any custom easing function
                // compatible with most easing plugins
                easing: function (x, t, b, c, d) {
                    return c*(t/=d)*t + b;
                },

                // event control
                scrollPropagate: false,
                eventPropagate: true,

                // Force centering slide after scroll event
                scrollLock: false,
                // how long to wait after scroll event before locking
                // if too low, it might interrupt normal scrolling
                scrollLockDelay: 150,

                // Force centering slide after resize event
                resizeLock: true,
                
                // Glider.js breakpoints are mobile-first
                responsive: [
                    {
                        breakpoint: 1400,
                        settings: {
                            slidesToShow: slidesToShow,
                            slidesToScroll: 1
                        }
                    },
                    {
                        breakpoint: 1200,
                        settings: {
                            slidesToShow: (slidesToShow >= 5)? slidesToShow - 1 : slidesToShow,
                            slidesToScroll: 1
                        }
                    },
                    {
                        breakpoint: 900,
                        settings: {
                            slidesToShow: 3,
                            slidesToScroll: 1
                        }
                    },
                    {
                        breakpoint: 767,
                        settings: {
                            slidesToShow: 3,
                            slidesToScroll: 3
                        }
                    },
                    {
                        breakpoint: 575,
                        settings: {
                            slidesToShow: 2,
                            slidesToScroll: 1
                        }
                    },
                    {
                        breakpoint: 0,
                        settings: {
                            slidesToShow: 1,
                            slidesToScroll: 1
                        }
                    }
                ]
            });

            // Auto-play functionality
            // Source - https://stackoverflow.com/a
// Posted by Varuna
// Retrieved 2025-12-10, License - CC BY-SA 4.0

var slider = new Glider(document.querySelector('.glider'), {
    slidesToScroll: 1,
    slidesToShow: 1,
    dots: '#dots',
    arrows: {
        prev: '.glider-prev',
        next: '.glider-next'
    }
});

slideAutoPaly(slider, '.glider');

function slideAutoPaly(glider, selector, delay = 5000, repeat = true) {
    let autoplay = null;
    const slidesCount = glider.track.childElementCount;
    let nextIndex = 1;
    let pause = true;

    function slide() {
        autoplay = setInterval(() => {
            if (nextIndex >= slidesCount) {
                if (!repeat) {
                    clearInterval(autoplay);
                } else {
                    nextIndex = 0;
                }
            }
            glider.scrollItem(nextIndex++);
        }, delay);
    }

    slide();

    var element = document.querySelector(selector);
    element.addEventListener('mouseover', (event) => {
        if (pause) {
            clearInterval(autoplay);
            pause = false;
        }
    }, 300);

    element.addEventListener('mouseout', (event) => {
        if (!pause) {
            slide();
            pause = true;
        }
    }, 300);
}


        });
    </script>
    
<Fragment set:html={structuredData} />
    
