{% extends "_layouts/base.twig" %}

{% set heroImage = entry.heroImage.one() ?? entry.thumbnail.one() %}
{% set sectors = entry.categories.all() %}
{% set serviceCategories = entry.servicesCategories.all() %}
{% set testimonial = entry.testimonial.one() %}
{% set maxRelated = 2 %}
{% set manualRelated = entry.featuredCaseStudiesTwo.all() %}
{% set relationTargets = sectors | length ? sectors : serviceCategories %}
{% set relatedStudies = [] %}
{% set excludeIds = [entry.id] %}

{% for study in manualRelated %}
{% if study.id != entry.id and relatedStudies | length < maxRelated %} {% set relatedStudies=relatedStudies |
    merge([study]) %} {% set excludeIds=excludeIds | merge([study.id]) %} {% endif %} {% endfor %} {% set
    needed=maxRelated - (relatedStudies | length) %} {% if needed> 0 and relationTargets | length %}
    {% set autoRelated = craft.entries()
    .section('caseStudies')
    .id('not ' ~ excludeIds | join(','))
    .relatedTo(relationTargets)
    .limit(needed)
    .all() %}
    {% set relatedStudies = relatedStudies | merge(autoRelated) %}
    {% set excludeIds = excludeIds | merge(autoRelated | map(s => s.id)) %}
    {% set needed = maxRelated - (relatedStudies | length) %}
    {% endif %}

    {% if needed > 0 %}
    {% set relatedStudies = relatedStudies | merge(
    craft.entries()
    .section('caseStudies')
    .id('not ' ~ excludeIds | join(','))
    .limit(needed)
    .all()
    ) %}
    {% endif %}

    {% block content %}

    <article class="bg-white">

        {% include "_includes/articleHero.twig" with { entry: entry, heroImage: heroImage, color: 'navy', textColor:
        'white' } only %}

        <section class="case-study-body bg-white pb-l pt-l lg:pt-xl">
            <div class="container">
                <div class="grid gap-2xl lg:grid-cols-[220px_minmax(0,1fr)] lg:items-start lg:gap-x-2xl">
                    <aside
                        class="case-study-side-nav hidden lg:block lg:sticky lg:top-[calc(var(--nav-height)+var(--spacing-l))]">
                        <nav aria-label="Case study sections">
                            <ol class="case-study-nav flex flex-col gap-xs"></ol>
                        </nav>
                    </aside>

                    <div class="case-study-content min-w-0 pv-s lg:pb-m [&_.container]:max-w-none [&_.container]:px-0">
                        {% include "_includes/caseStudySummary.twig" with {
                        entry: entry,
                        sectors: sectors,
                        serviceCategories: serviceCategories
                        } only %}

                        {% include "_includes/content.twig" with {
                        blocks: entry.bodyContent.all(),
                        mediaFullWidth: true,
                        contentStartedBeforeBlocks: entry.richText or entry.clientName or sectors | length or
                        serviceCategories | length
                        } only %}
                    </div>
                </div>
            </div>
        </section>

        {% if testimonial %}
        <section class="bg-navy py-2xl text-white">
            <div class="container">
                <figure class="mx-auto max-w-[1100px] text-center">
                    {% if testimonial.quote %}
                    <blockquote class="font-nine-elms text-3 leading-snug text-white [&_p]:m-0">
                        &ldquo;{{ testimonial.quote }}&rdquo;
                    </blockquote>
                    {% endif %}

                    <figcaption class="mt-l flex flex-col items-center gap-2xs font-rosario">
                        <span class="text-0 text-turquoise">{{ testimonial.title }}</span>
                        {% if testimonial.attribution %}
                        <span class="text--1 text-white/70">{{ testimonial.attribution }}</span>
                        {% endif %}
                    </figcaption>
                </figure>
            </div>
        </section>
        {% endif %}

        {% if relatedStudies | length %}
        <section class="bg-white py-2xl">
            <div class="container">
                <div class="flex flex-col gap-l">
                    <div class="flex flex-col gap-xs md:flex-row md:items-end md:justify-between">
                        <h2 class="h3 text-navy">More Work</h2>
                        <a href="/work" class="button">View all case studies</a>
                    </div>

                    <div class="grid gap-l md:grid-cols-2">
                        {% for study in relatedStudies %}
                        {% set thumb = study.thumbnail.one() %}
                        <article class="group flex flex-col gap-s">
                            <a href="{{ study.url }}" class="block overflow-hidden rounded-sm bg-navy/10 aspect-4/3">
                                {% if thumb %}
                                <img src="{{ thumb.getUrl({ width: 800, height: 600 }) }}"
                                    alt="{{ thumb.alt ?: (study.clientName ?: study.title) }}"
                                    class="h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"
                                    loading="lazy">
                                {% else %}
                                <div class="h-full w-full bg-linear-to-br from-navy/5 to-indigo/10"></div>
                                {% endif %}
                            </a>
                            <div class="flex flex-col gap-2xs">
                                {% if study.clientName %}
                                <span class="font-rosario text--2 uppercase tracking-widest text-navy/50">
                                    {{ study.clientName }}
                                </span>
                                {% endif %}
                                <h3 class="font-nine-elms text-1 leading-snug text-navy">
                                    <a href="{{ study.url }}" class="transition-colors duration-200 hover:text-indigo">
                                        {{ study.title }}
                                    </a>
                                </h3>
                            </div>
                        </article>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </section>
        {% endif %}
    </article>

    {% include "_includes/cta.twig" %}

    {% endblock %}

    {% block scripts %}
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const sideNav = document.querySelector('.case-study-side-nav');
            const navList = document.querySelector('.case-study-nav');
            const headings = Array.from(document.querySelectorAll('.case-study-content h2, .case-study-content h3'));

            if (!sideNav || !navList) {
                return;
            }

            if (!headings.length) {
                if (!sideNav.querySelector('img')) {
                    sideNav.classList.add('lg:hidden');
                }
                return;
            }

            const slugCounts = new Map();
            const slugify = (value) => {
                const base = value
                    .toLowerCase()
                    .trim()
                    .replace(/[^a-z0-9]+/g, '-')
                    .replace(/^-|-$/g, '') || 'section';
                const count = slugCounts.get(base) || 0;
                slugCounts.set(base, count + 1);
                return count ? `${base}-${count + 1}` : base;
            };

            headings.forEach((heading) => {
                if (!heading.id) {
                    heading.id = slugify(heading.textContent);
                }

                const item = document.createElement('li');
                const link = document.createElement('a');
                link.href = `#${heading.id}`;
                link.textContent = heading.textContent.trim();
                link.className = 'block border-l-2 border-transparent py-2xs pl-s font-rosario text--1 text-navy/50 no-underline transition-colors duration-200 hover:border-indigo hover:text-indigo';

                item.appendChild(link);
                navList.appendChild(item);
            });

            const links = Array.from(navList.querySelectorAll('a'));
            const headingById = new Map(headings.map((heading) => [heading.id, heading]));

            const setActive = (id) => {
                links.forEach((link) => {
                    const isActive = link.getAttribute('href') === `#${id}`;
                    link.classList.toggle('border-indigo', isActive);
                    link.classList.toggle('font-semibold', isActive);
                    link.classList.toggle('text-indigo', isActive);
                    link.classList.toggle('border-transparent', !isActive);
                    link.classList.toggle('text-navy/50', !isActive);
                    link.toggleAttribute('aria-current', isActive ? 'location' : false);
                });
            };

            setActive(headings[0].id);

            let clickScrolling = false;
            let scrollEndTimer;

            const endClickScroll = () => {
                clickScrolling = false;
            };

            links.forEach((link) => {
                link.addEventListener('click', (event) => {
                    event.preventDefault();
                    const id = link.getAttribute('href').slice(1);
                    const target = headingById.get(id);
                    if (!target) {
                        return;
                    }

                    clickScrolling = true;
                    setActive(id);
                    target.scrollIntoView({ behavior: 'smooth', block: 'start' });

                    clearTimeout(scrollEndTimer);
                    scrollEndTimer = setTimeout(endClickScroll, 1000);
                });
            });

            window.addEventListener('scrollend', () => {
                if (clickScrolling) {
                    clearTimeout(scrollEndTimer);
                    endClickScroll();
                }
            }, { passive: true });

            const observer = new IntersectionObserver((entries) => {
                if (clickScrolling) {
                    return;
                }

                entries.forEach((entry) => {
                    if (entry.isIntersecting) {
                        setActive(entry.target.id);
                    }
                });
            }, {
                rootMargin: '-35% 0px -55% 0px',
                threshold: 0
            });

            headings.forEach((heading) => observer.observe(heading));
        });
    </script>
    {% endblock %}