<script>
document.addEventListener('DOMContentLoaded', function() {
    // Case studies data - this will be populated by Hugo
    const caseStudies = [
        {{ range where .Site.Pages "Section" "case-studies" }}
        {{ if and .Params.image .Title (ne .Title "Case Studies") }}
        {
            title: "{{ .Title | replaceRE `"` `\"` }}",
            description: "{{ if .Description }}{{ .Description | replaceRE `"` `\"` }}{{ else }}{{ .Summary | plainify | truncate 150 | replaceRE `"` `\"` }}{{ end }}",
            url: "{{ .RelPermalink }}",
            image: "{{ .Params.image }}",
            banner: {{ if .Params.banner }}"{{ .Params.banner }}"{{ else }}null{{ end }}
        },
        {{ end }}
        {{ end }}
    ].filter(study => study.title); // Remove any empty entries
    
    // Function to shuffle array and get random selection
    function getRandomCases(cases, count = 3) {
        const shuffled = [...cases].sort(() => 0.5 - Math.random());
        return shuffled.slice(0, count);
    }
    
    // Function to create case card HTML
    function createCaseCard(caseStudy) {
        const hasImage = caseStudy.image && caseStudy.image !== 'null' && caseStudy.image !== null;
        const hasBanner = caseStudy.banner && caseStudy.banner !== 'null' && caseStudy.banner !== null;
        
        let imageHTML = '';
        if (hasBanner) {
            imageHTML = `
                <a href="${caseStudy.url}" class="featured-banner-link">
                    <div class="featured-card-banner">
                        <img src="${caseStudy.banner}" alt="${caseStudy.title} banner" class="featured-case-banner" />
                        ${hasImage ? `<img src="${caseStudy.image}" alt="${caseStudy.title} logo" class="case-logo-overlay" />` : ''}
                    </div>
                </a>
            `;
        } else if (hasImage) {
            imageHTML = `
                <a href="${caseStudy.url}" class="featured-banner-link">
                    <img src="${caseStudy.image}" alt="${caseStudy.title} logo" class="featured-case-logo" />
                </a>
            `;
        }
        
        return `
            <div class="featured-case-card">
                ${imageHTML}
                <div class="featured-case-content">
                    <h3><a href="${caseStudy.url}" class="featured-case-title">${caseStudy.title}</a></h3>
                    <p class="featured-case-description">${caseStudy.description}</p>
                </div>
            </div>
        `;
    }
    
    // Populate featured cases
    const featuredCasesGrid = document.getElementById('featuredCasesGrid');
    if (featuredCasesGrid && caseStudies.length > 0) {
        const randomCases = getRandomCases(caseStudies, 3);
        featuredCasesGrid.innerHTML = randomCases.map(createCaseCard).join('');
    }
});
</script>