{#
# Transformations Component
# Navy background with gold accents - luxury before/after slider
#
# Usage: 
#   {% include 'components/transformations.twig' %} - Auto-detects context
#   {% include 'components/transformations.twig' with { block: block } %} - From page builder
#
# For homepage: Shows transformations with featuredOnHomepage checked
# For treatment pages: Shows transformations selected in featuredTransformations field
# For page builder: Shows transformations from block settings
#}

{% import '_macros/images.twig' as imageMacro %}

{# Determine which transformations to show #}
{# 
  IMPORTANT: Update the field handle below to match your backend setup
  Common field handles: 'transformations', 'selectedTransformations', 'featuredTransformations'
#}

{% if block is defined %}
    {# Page Builder: block is the Featured transformations entry – get selected entries from field #}
    {% set blockLayout = block.getFieldLayout() %}
    {% set rel = (blockLayout.getFieldByHandle('featuredTransformations') is not null) ? attribute(block, 'featuredTransformations') : null %}
    {% if rel and rel|length %}
        {% set transformations = rel.all() %}
    {% else %}
        {% set transformations = [] %}
    {% endif %}
{% else %}
    {% set isHomepage = entry is defined and entry.section.handle == 'homepage' %}
    
    {% if isHomepage %}
        {# Homepage: Show featured transformations #}
        {% set allTransformations = craft.entries()
            .section('transformations')
            .all() %}
        {% set transformations = allTransformations|filter(t => t.featuredOnHomepage) %}
    {% else %}
        {# Treatment page: Show all transformations (or can be filtered) #}
        {% set transformations = craft.entries()
            .section('transformations')
            .limit(3)
            .all() %}
    {% endif %}
{% endif %}

{# Get dynamic heading and text from block if available – no defaults #}
{% set topLabel = (block is defined and block.getFieldLayout().getFieldByHandle('plainText2') is not null and block.plainText2|length) ? block.plainText2 : null %}
{% set heading = (block is defined and block.getFieldLayout().getFieldByHandle('plainText') is not null and block.plainText|length) ? block.plainText : null %}
{% set description = (block is defined and block.getFieldLayout().getFieldByHandle('textArea') is not null and block.textArea|length) ? block.textArea : null %}

{% if transformations|length %}
<section class="section-luxury relative overflow-hidden" style="background: linear-gradient(135deg, #2c4a5c 0%, #1e3644 100%);">
    <!-- Decorative elements -->
    <div class="absolute top-0 left-0 w-96 h-96 border border-gold/10 rounded-full -translate-x-1/2 -translate-y-1/2"></div>
    <div class="absolute bottom-0 right-0 w-80 h-80 border border-gold/10 rounded-full translate-x-1/2 translate-y-1/2"></div>
    
    <!-- Subtle pattern overlay -->
    <div class="absolute inset-0 opacity-[0.02]" style="background-image: url('data:image/svg+xml,%3Csvg width=&quot;60&quot; height=&quot;60&quot; viewBox=&quot;0 0 60 60&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;%3E%3Cg fill=&quot;none&quot; fill-rule=&quot;evenodd&quot;%3E%3Cg fill=&quot;%23c8a882&quot; fill-opacity=&quot;1&quot;%3E%3Cpath d=&quot;M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z&quot;/%3E%3C/g%3E%3C/g%3E%3C/svg%3E');"></div>
    
    <div class="container-default relative z-10">
        <!-- Elegant Heading -->
        {% 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-white">{{ heading }}</h2>
            {% endif %}
            {% if description %}
            <p class="text-white/80 max-w-2xl mx-auto mt-6 leading-relaxed">
                {{ description }}
            </p>
            {% endif %}
        </div>
        {% endif %}
        
        <!-- Before/After Sliders Grid -->
        <div class="grid md:grid-cols-3 gap-10 lg:gap-14 items-start">
            {% for transformation in transformations %}
                {% set beforeImg = transformation.beforeImage.one() %}
                {% set afterImg = transformation.afterImage.one() %}
                
                {% if beforeImg and afterImg %}
                <div class="group">
                    <div class="before-after-slider relative rounded-xl overflow-hidden border-2 border-gold/30 aspect-[4/5] transition-transform duration-500 group-hover:scale-[1.01]" data-slider-id="{{ loop.index }}" style="box-shadow: inset 0 0 40px -10px rgba(0, 0, 0, 0.15), 0 2px 12px -2px rgba(0, 0, 0, 0.05);">
                        <!-- After Image (background/full width) -->
                        <div class="after-image-wrapper absolute inset-0 pointer-events-none">
                            {{ imageMacro.optimizedImage(afterImg, {
                              alt: 'After - ' ~ transformation.title,
                              class: 'after-img absolute inset-0 w-full h-full object-cover object-center transition-transform duration-500 group-hover:scale-105',
                              loading: 'lazy',
                              width: afterImg.width,
                              height: afterImg.height,
                              sizes: '(max-width: 1024px) 50vw, 33vw'
                            }) }}
                        </div>
                        
                        <!-- Before Image (clipped by mask, not scaled) -->
                        <div class="before-image-wrapper absolute inset-0 z-10 pointer-events-none" style="width: 100%; height: 100%; clip-path: inset(0 50% 0 0);">
                            {{ imageMacro.optimizedImage(beforeImg, {
                              alt: 'Before - ' ~ transformation.title,
                              class: 'before-img absolute inset-0 w-full h-full object-cover object-center transition-transform duration-500 group-hover:scale-105 pointer-events-none',
                              loading: 'lazy',
                              width: beforeImg.width,
                              height: beforeImg.height,
                              sizes: '(max-width: 1024px) 50vw, 33vw'
                            }) }}
                        </div>
                        
                        <!-- Slider Handle -->
                        <div class="slider-handle absolute top-0 bottom-0 flex items-center justify-center z-30 cursor-ew-resize" data-initial-left="50">
                            <!-- Vertical Line -->
                            <div class="absolute top-0 bottom-0 w-0.5 bg-gold shadow-lg"></div>
                            
                            <!-- Handle Circle -->
                            <div class="relative z-10 w-14 h-14 rounded-full bg-white shadow-xl flex items-center justify-center border-4 border-gold transition-transform group-hover:scale-110 pointer-events-none">
                                <svg class="w-6 h-6 text-navy" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M9 8l-4 4 4 4m6-8l4 4-4 4"/>
                                </svg>
                            </div>
                        </div>
                        
                        <!-- Labels -->
                        <div class="absolute bottom-4 left-4 px-4 py-2 backdrop-blur-sm rounded-lg text-xs font-bold uppercase tracking-wider text-white z-20" style="background-image: linear-gradient(135deg, #2c4a5c, #1e3644);">Before</div>
                        <div class="absolute bottom-4 right-4 px-4 py-2 bg-white backdrop-blur-sm rounded-lg text-xs font-bold uppercase tracking-wider z-20" style="color: #D58D72;">After</div>
                    </div>
                    <div class="mt-6 text-center">
                        {% if transformation.title|length %}<h5 class="text-white font-semibold mb-2 text-lg">{{ transformation.title }}</h5>{% endif %}
                        {% set timeframeRaw = transformation.plainText2 ?? null %}
                        {% set timeframe = timeframeRaw.value is defined ? timeframeRaw.value : timeframeRaw %}
                        {% if timeframe|length %}
                        <p class="text-white/70 text-sm">{{ timeframe }}</p>
                        {% endif %}
                    </div>
                </div>
                {% endif %}
            {% endfor %}
        </div>
        
        <!-- View All Button -->
        <div class="text-center mt-16">
            <a href="/transformations" class="inline-flex items-center justify-center group text-white font-body font-semibold text-[20px] px-8 py-3.5 rounded transition-colors duration-300 hover:bg-[#c0775f]" style="background-color:#D58D72;">
                <span>View All Transformations</span>
                <svg class="w-4 h-4 ml-3 transition-transform group-hover:translate-x-1" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3"/>
                </svg>
            </a>
        </div>
    </div>
    
    <!-- Bottom gold accent line -->
    <div class="absolute bottom-0 left-0 right-0 h-px bg-gradient-to-r from-transparent via-gold/40 to-transparent"></div>
</section>
{% endif %}

<!-- Before/After Slider Script -->
<script>
(function() {
    function initBeforeAfterSliders() {
        const sliders = document.querySelectorAll('[data-slider-id]');
        
        sliders.forEach(slider => {
            const beforeWrapper = slider.querySelector('.before-image-wrapper');
            const afterWrapper = slider.querySelector('.after-image-wrapper');
            const beforeImg = beforeWrapper ? beforeWrapper.querySelector('.before-img') : null;
            const afterImg = afterWrapper ? afterWrapper.querySelector('.after-img') : null;
            const handle = slider.querySelector('.slider-handle');
            let isDragging = false;
            
            if (!beforeWrapper || !handle || !beforeImg || !afterImg) return;
            
            // Ensure both images use identical object-position for perfect alignment
            function syncImagePositioning() {
                // Explicitly set both images to center-center positioning
                // This ensures they align perfectly - both images will be centered the same way
                beforeImg.style.objectPosition = 'center center';
                afterImg.style.objectPosition = 'center center';
                
                // Also ensure object-fit is identical
                beforeImg.style.objectFit = 'cover';
                afterImg.style.objectFit = 'cover';
            }
            
            function updatePosition(clientX) {
                const rect = slider.getBoundingClientRect();
                let x = clientX - rect.left;
                x = Math.max(0, Math.min(rect.width, x));
                
                // Single source of truth: percentage (0-100)
                // 0 = before fully hidden, 100 = before fully visible
                const percentage = Math.round((x / rect.width) * 100);
                
                // Ensure percentage is clamped to 0-100
                const clampedPercent = Math.max(0, Math.min(100, percentage));
                
                // clip-path: inset(top right bottom left)
                // To show left X% of image, we clip (100-X)% from the right
                // Examples:
                //   clampedPercent = 0   → clip 100% from right → show 0%   (hidden)
                //   clampedPercent = 50  → clip 50% from right  → show 50%  (half)
                //   clampedPercent = 100 → clip 0% from right   → show 100% (full)
                const clipFromRight = 100 - clampedPercent;
                beforeWrapper.style.clipPath = `inset(0 ${clipFromRight}% 0 0)`;
                
                // Handle position: center aligns with the clip edge
                // The handle's center (via translateX(-50%)) sits at clampedPercent%
                handle.style.left = clampedPercent + '%';
                handle.style.transform = 'translateX(-50%)';
            }
            
            // Initialize position after images load
            function initializeSlider() {
                // Sync image positioning first
                syncImagePositioning();
                
                // Wait for layout to settle
                const initPosition = () => {
                    const rect = slider.getBoundingClientRect();
                    if (rect.width > 0 && rect.height > 0) {
                        // Start at 50% (centered)
                        const centerX = rect.left + rect.width / 2;
                        updatePosition(centerX);
                    } else {
                        requestAnimationFrame(initPosition);
                    }
                };
                initPosition();
            }
            
            // Sync positioning when images load
            if (afterImg.complete && beforeImg.complete) {
                syncImagePositioning();
            } else {
                afterImg.addEventListener('load', syncImagePositioning);
                beforeImg.addEventListener('load', syncImagePositioning);
            }
            
            function handleStart(e) {
                isDragging = true;
                slider.style.cursor = 'ew-resize';
                e.preventDefault();
                const x = e.touches ? e.touches[0].clientX : e.clientX;
                updatePosition(x);
            }
            
            function handleMove(e) {
                if (!isDragging) return;
                e.preventDefault();
                const x = e.touches ? e.touches[0].clientX : e.clientX;
                updatePosition(x);
            }
            
            function handleEnd() {
                isDragging = false;
                slider.style.cursor = '';
            }
            
            // Mouse events
            slider.addEventListener('mousedown', handleStart);
            document.addEventListener('mousemove', handleMove);
            document.addEventListener('mouseup', handleEnd);
            
            // Touch events
            slider.addEventListener('touchstart', handleStart, { passive: false });
            document.addEventListener('touchmove', handleMove, { passive: false });
            document.addEventListener('touchend', handleEnd);
            
            // Click to jump
            slider.addEventListener('click', (e) => {
                if (!isDragging) {
                    updatePosition(e.clientX);
                }
            });

            // Initialize slider position
            initializeSlider();
            
            // Also initialize on window load and resize
            window.addEventListener('load', initializeSlider);
            let resizeTimeout;
            window.addEventListener('resize', () => {
                clearTimeout(resizeTimeout);
                resizeTimeout = setTimeout(initializeSlider, 100);
            });
        });
    }
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initBeforeAfterSliders);
    } else {
        initBeforeAfterSliders();
    }
})();
</script>
