{#
Featured Case Studies - Page builder builder block (similar to transformations

Backend setup - fields and entry types setup

1. Fields 
"featuredCaseStudies", max relations: 3,
Source: Case Studies 

2. New Matrix block etry type (featuredCaseStudies) on the page builder pagebuilder field in the backend.

3. Entry type fields
Heading - plainText
Top Label - plainText2
Background (optional css hex or linear-gradient - plainText3
Intro text area - CKEditor field - textArea
Exerpt - plain text - "excerpt"
featuredCaseStudied (the entries from step 1)
#}
{% import '_macros/images.twig' as imageMacro %}

{% if block is defined %}
    {% set blockLayout = block.getFieldLayout() %}
    {% set rel = (blockLayout.getFieldByHandle('featuredCaseStudies') is not null) ? attribute(block, 'featuredCaseStudies') : null %}
    {% set studies = rel and rel|length ? rel.all()|slice(0, 3) : [] %}

    {% set topLabel = (blockLayout.getFieldByHandle('plainText2') is not null and block.plainText2|length) ? block.plainText2 : null %}
    {% set heading = (blockLayout.getFieldByHandle('plainText') is not null and block.plainText|length) ? block.plainText : null %}
    {% set description = (blockLayout.getFieldByHandle('textArea') is not null and block.textArea|length) ? block.textArea : null %}
    {% set bgRaw = (blockLayout.getFieldByHandle('plainText3') is not null and block.plainText3|trim|length) ? block.plainText3|trim : null %}
{% else %}
    {% set studies = [] %}
    {% set topLabel = null %}
    {% set heading = null %}
    {% set description = null %}
    {% set bgRaw = null %}
{% endif %}

{% set sectionBg = bgRaw ?: null %}

{% if studies|length %}
<section class="section-luxury bg-beige-light relative overflow-hidden bg-pattern-diagonal"{% if sectionBg %} style="background: {{ sectionBg }};"{% endif %}>
    <div class="container-default relative z-10">
        {% if topLabel or heading or description %}
        <div class="section-heading">
            {% if topLabel %}
            <div class="flex items-center justify-center gap-4 mb-6">
                <div class="w-12 h-px bg-gold"></div>
                <p class="text-gold tracking-widest text-2xl font-medium font-body">{{ topLabel }}</p>
                <div class="w-12 h-px bg-gold"></div>
            </div>
            {% endif %}
            {% if heading %}
            <h2 class="text-navy">{{ heading }}</h2>
            {% endif %}
            {% if description %}
            <div class="text-charcoal-light max-w-2xl mx-auto mt-6 leading-relaxed">
                {{ description }}
            </div>
            {% endif %}
        </div>
        {% endif %}

        {% set colClass = studies|length == 1 ? 'grid-cols-1 max-w-md mx-auto' : (studies|length == 2 ? 'grid-cols-1 md:grid-cols-2' : 'grid-cols-1 md:grid-cols-3') %}
        <div class="grid {{ colClass }} gap-8 lg:gap-12 mb-16">
            {% for study in studies %}
                {% set featuredImage = study.featuredImage is defined ? study.featuredImage.one() : null %}
                {% set excerptText = '' %}
                {# Auto excerpt: use the first paragraph from page-builder content that has more than 100 words #}
                {% if study.pagebuilder is defined and study.pagebuilder|length %}
                    {% set collectedHtml %}
                        {% for pb in study.pagebuilder.limit(12).all() %}
                            {% set pbLayout = pb.getFieldLayout() %}
                            {% if pbLayout and pbLayout.getFieldByHandle('textArea') is not null %}
                                {{ attribute(pb, 'textArea')|default('') }}
                            {% endif %}
                            {% if pbLayout and pbLayout.getFieldByHandle('wisywig') is not null %}
                                {{ attribute(pb, 'wisywig')|default('') }}
                            {% endif %}
                            {% if pbLayout and pbLayout.getFieldByHandle('plainText') is not null %}
                                {{ attribute(pb, 'plainText')|default('') }}
                            {% endif %}
                            {# Common long-copy handles used in treatment/case-study block types #}
                            {% for h in [
                                'sectionDescription',
                                'sectionContent',
                                'whyChooseDescription',
                                'whoConsiderContent',
                                'whatIsSectionDescription',
                                'block1Paragraph1',
                                'block1Paragraph2',
                                'block2Paragraph1',
                                'block2Paragraph2',
                                'whatIsBlock1Paragraph1',
                                'whatIsBlock1Paragraph2',
                                'whatIsBlock2Paragraph1',
                                'whatIsBlock2Paragraph2',
                                'testimonialQuote',
                                'whatIsTestimonialQuote'
                            ] %}
                                {% if pbLayout and pbLayout.getFieldByHandle(h) is not null %}
                                    {{ attribute(pb, h)|default('') }}
                                {% endif %}
                            {% endfor %}

                            {# Nested content in flexible-section style blocks #}
                            {% if pbLayout and pbLayout.getFieldByHandle('contentElements') is not null %}
                                {% set elementsQuery = attribute(pb, 'contentElements') %}
                                {% if elementsQuery and elementsQuery.all is defined %}
                                    {% for el in elementsQuery.all() %}
                                        {% set elLayout = el.getFieldLayout() %}
                                        {% if elLayout and elLayout.getFieldByHandle('wisywig') is not null %}
                                            {{ attribute(el, 'wisywig')|default('') }}
                                        {% endif %}
                                        {% if elLayout and elLayout.getFieldByHandle('textArea') is not null %}
                                            {{ attribute(el, 'textArea')|default('') }}
                                        {% endif %}
                                        {% if elLayout and elLayout.getFieldByHandle('plainText') is not null %}
                                            {{ attribute(el, 'plainText')|default('') }}
                                        {% endif %}
                                    {% endfor %}
                                {% endif %}
                            {% endif %}

                            {# Nested columns -> content elements #}
                            {% if pbLayout and pbLayout.getFieldByHandle('contentColumns') is not null %}
                                {% set columnsQuery = attribute(pb, 'contentColumns') %}
                                {% if columnsQuery and columnsQuery.all is defined %}
                                    {% for col in columnsQuery.all() %}
                                        {% set colLayout = col.getFieldLayout() %}
                                        {% if colLayout and colLayout.getFieldByHandle('contentElements') is not null %}
                                            {% set colElementsQuery = attribute(col, 'contentElements') %}
                                            {% if colElementsQuery and colElementsQuery.all is defined %}
                                                {% for cel in colElementsQuery.all() %}
                                                    {% set celLayout = cel.getFieldLayout() %}
                                                    {% if celLayout and celLayout.getFieldByHandle('wisywig') is not null %}
                                                        {{ attribute(cel, 'wisywig')|default('') }}
                                                    {% endif %}
                                                    {% if celLayout and celLayout.getFieldByHandle('textArea') is not null %}
                                                        {{ attribute(cel, 'textArea')|default('') }}
                                                    {% endif %}
                                                    {% if celLayout and celLayout.getFieldByHandle('plainText') is not null %}
                                                        {{ attribute(cel, 'plainText')|default('') }}
                                                    {% endif %}
                                                {% endfor %}
                                            {% endif %}
                                        {% endif %}
                                    {% endfor %}
                                {% endif %}
                            {% endif %}
                        {% endfor %}
                    {% endset %}

                    {# Keep paragraph boundaries before stripping tags #}
                    {% set normalizedText = collectedHtml
                        |replace({
                            '</p>': '\n\n',
                            '<br>': '\n',
                            '<br/>': '\n',
                            '<br />': '\n'
                        })
                        |striptags
                        |replace({'\r':'', '\t':' '})
                    %}

                    {# Split into paragraphs, find first with 65+ words #}
                    {% set paragraphs = normalizedText|split('\n\n') %}
                    {% set longParagraphs = paragraphs|filter(p => (p|trim and (p|trim|split(' ')|filter(w => w|trim)|length) >= 65)) %}
                    {% set excerptSource = longParagraphs|length ? (longParagraphs|first|trim) : '' %}

                    {# If no double-newline paragraph is long enough, try line-based chunks #}
                    {% if not excerptSource %}
                        {% set lineChunks = normalizedText|split('\n') %}
                        {% set longLineChunks = lineChunks|filter(p => (p|trim and (p|trim|split(' ')|filter(w => w|trim)|length) >= 65)) %}
                        {% set excerptSource = longLineChunks|length ? (longLineChunks|first|trim) : '' %}
                    {% endif %}
                    {# If still nothing, pick first medium paragraph (20+ words) instead of generic fallback #}
                    {% if not excerptSource %}
                        {% set mediumParagraphs = paragraphs|filter(p => (p|trim and (p|trim|split(' ')|filter(w => w|trim)|length) >= 20)) %}
                        {% set excerptSource = mediumParagraphs|length ? (mediumParagraphs|first|trim) : '' %}
                    {% endif %}

                    {% if excerptSource %}
                        {% set excerptWords = excerptSource|replace({'\n':' '})|split(' ')|filter(w => w|trim) %}
                        {% set excerptText = excerptWords|slice(0, 40)|join(' ') ~ (excerptWords|length > 40 ? '...' : '') %}
                    {% endif %}
                {% endif %}

                {% if not excerptText and study.getFieldLayout() %}
                    {% set entryLayout = study.getFieldLayout() %}
                    {% if entryLayout.getFieldByHandle('textArea') is not null %}
                        {% set excerptText = attribute(study, 'textArea')|default('')|striptags|trim %}
                    {% endif %}
                    {% if not excerptText and entryLayout.getFieldByHandle('wisywig') is not null %}
                        {% set excerptText = attribute(study, 'wisywig')|default('')|striptags|trim %}
                    {% endif %}
                {% endif %}
                {% if excerptText %}
                    {% set excerptWords = excerptText|split(' ')|filter(w => w|trim) %}
                    {% set excerptText = excerptWords|slice(0, 40)|join(' ') ~ (excerptWords|length > 40 ? '...' : '') %}
                {% endif %}
                {% if not excerptText %}
                    {% set excerptText = 'Discover the treatment journey, results, and key details in this case study.' %}
                {% endif %}

                <article class="card-luxury overflow-hidden group">
                    <a href="{{ study.url }}" class="block">
                    <div class="aspect-[4/3] overflow-hidden">
                        {% if featuredImage %}
                            {{ imageMacro.optimizedImage(featuredImage, {
                              alt: study.title,
                              class: 'w-full h-full object-cover transition-transform duration-700 group-hover:scale-110',
                              loading: 'lazy',
                              width: featuredImage.width,
                              height: featuredImage.height,
                              sizes: '(max-width: 1024px) 50vw, 33vw'
                            }) }}
                        {% else %}
                            <div class="aspect-[4/3] bg-blush/20 flex items-center justify-center">
                                <span class="text-navy/30 text-4xl font-bold">{{ study.title|slice(0, 1) }}</span>
                            </div>
                        {% endif %}
                    </div>
                    <div class="p-8 lg:p-10">
                        <h3 class="text-navy mb-4 text-xl lg:text-2xl group-hover:text-gold transition-colors">{{ study.title }}</h3>
                        <p class="text-charcoal-light text-base lg:text-[17px] mb-6 leading-relaxed">
                            {{ excerptText }}
                        </p>
                        <span class="link-primary group/link">
                            <span>Read Case Study</span>
                            <svg class="w-4 h-4 ml-2 transition-transform group-hover/link:translate-x-1" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3"/>
                            </svg>
                        </span>
                    </div>
                    </a>
                </article>
            {% endfor %}
        </div>

    </div>
</section>
{% endif %}

