@php
    if (!function_exists('resolve_preview_image_url')) {
        function resolve_preview_image_url($imageState) {
            if (!$imageState) {
                return null;
            }
            if (is_array($imageState)) {
                $imageState = reset($imageState);
            }
            if (is_object($imageState) && method_exists($imageState, 'temporaryUrl')) {
                return $imageState->temporaryUrl();
            }
            if (is_string($imageState)) {
                if (str_starts_with($imageState, 'http://') || str_starts_with($imageState, 'https://')) {
                    return $imageState;
                }
                
                $url = \Illuminate\Support\Facades\Storage::url($imageState);
                
                $requestHost = request()->getHost();
                if (str_contains($url, $requestHost)) {
                    $parsedUrl = parse_url($url);
                    return ($parsedUrl['path'] ?? '') . (isset($parsedUrl['query']) ? '?' . $parsedUrl['query'] : '');
                }
                
                return $url;
            }
            return null;
        }
    }
@endphp
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ $page?->title ?? 'Live Preview' }} - Live Preview</title>
    
    <!-- Load Tailwind CSS CDN for premium styling -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Load Fonts dynamically -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Anek+Bangla:wght@300;400;600;700&family=Hind+Siliguri:wght@300;400;600;700&family=Inter:wght@300;400;600;700&family=Outfit:wght@300;400;600;700&display=swap" rel="stylesheet">

    <style>
        :root {
            --primary-color: {{ $page->primary_color }};
            --secondary-color: {{ $page->secondary_color }};
            --gradient-angle: {{ $page->gradient_angle }}deg;
            --font-family: '{{ $page->font_family }}', sans-serif;
        }

        body {
            font-family: var(--font-family);
        }

        .theme-bg {
            background: linear-gradient(var(--gradient-angle), var(--primary-color), var(--secondary-color));
        }

        .text-theme {
            color: var(--primary-color);
        }

        .btn-theme {
            background: linear-gradient(var(--gradient-angle), var(--primary-color), var(--secondary-color));
            color: white;
            transition: all 0.3s ease;
        }

        .btn-theme:hover {
            opacity: 0.9;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
    </style>
</head>
<body class="bg-gray-50 text-gray-800 antialiased">

    <!-- Landing Page Render -->
    <div id="landing-page-root" class="theme-{{ $page?->template_style ?? 'classic' }} min-h-screen">
        
        @if($sections->isEmpty())
            <div class="flex flex-col items-center justify-center min-h-[400px] text-center p-12 bg-white">
                <div class="w-16 h-16 rounded-full bg-indigo-50 flex items-center justify-center text-indigo-600 mb-4 animate-bounce">
                    <svg class="w-8 h-8" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v3m0 0v3m0-3h3m-3 0H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                </div>
                <h3 class="text-lg font-bold text-gray-900 mb-1">কোনো পেজ ব্লক যোগ করা হয়নি</h3>
                <p class="text-sm text-gray-500 max-w-sm mx-auto">বাম পাশের এডিটর থেকে "Add to page Blocks" বাটনে ক্লিক করে হিরো ব্যানার, প্রোডাক্ট ফিচার বা কাস্টমার রিভিউ যোগ করুন।</p>
            </div>
        @endif

        @foreach($sections as $sIdx => $section)
            @php
                $content = $section->content;
            @endphp

            <!-- Hero Section -->
            @if($section->block_type === 'hero')
                <section class="relative py-16 lg:py-24 overflow-hidden border-b border-gray-100 bg-white">
                    <div class="max-w-6xl mx-auto px-6 grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
                        <div class="space-y-6">
                            <h1 id="live-sections_builder-{{ $sIdx }}-headline" class="text-3xl lg:text-5xl font-bold leading-tight text-gray-900">
                                {{ $content['headline'] ?? 'আকর্ষণীয় শিরোনাম এখানে' }}
                            </h1>
                            <p id="live-sections_builder-{{ $sIdx }}-subheadline" class="text-base lg:text-lg text-gray-600 leading-relaxed">
                                {{ $content['subheadline'] ?? 'উপ-শিরোনামের বিবরণ এখানে দিন।' }}
                            </p>
                            <div>
                                <a href="#checkout-section" id="live-sections_builder-{{ $sIdx }}-cta_text" class="inline-block px-8 py-4 rounded-xl font-bold text-lg shadow-lg btn-theme">
                                    {{ $content['cta_text'] ?? 'অর্ডার করুন' }}
                                </a>
                            </div>
                        </div>
                        <div class="flex justify-center relative">
                            <div class="absolute -inset-1 rounded-2xl bg-gradient-to-r from-indigo-500 to-cyan-500 opacity-20 blur-xl"></div>
                            @php
                                $heroImageUrl = resolve_preview_image_url($content['image_path'] ?? null);
                            @endphp
                            @if($heroImageUrl)
                                <img id="live-hero-image" class="relative max-h-[400px] object-contain rounded-2xl shadow-xl border border-gray-150" src="{{ $heroImageUrl }}" alt="Product Image">
                            @else
                                <div id="live-hero-image" class="relative w-full h-[300px] bg-gray-100 rounded-2xl flex items-center justify-center text-gray-400">
                                    Product Image Placeholder
                                </div>
                            @endif
                        </div>
                    </div>
                </section>
            @endif

            <!-- Features Section -->
            @if($section->block_type === 'features')
                <section class="py-16 bg-gray-50 border-b border-gray-100">
                    <div class="max-w-6xl mx-auto px-6">
                        <h2 id="live-sections_builder-{{ $sIdx }}-title" class="text-2xl lg:text-4xl font-bold text-center mb-12 text-gray-900">
                            {{ $content['title'] ?? 'প্রোডাক্টের বিশেষ সুবিধাসমূহ' }}
                        </h2>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                            @if(isset($content['features_list']))
                                @foreach($content['features_list'] as $idx => $feat)
                                    <div class="p-6 bg-white rounded-2xl border border-gray-200/60 shadow-sm hover:shadow-md transition-all duration-300">
                                        <div class="w-12 h-12 rounded-xl theme-bg flex items-center justify-center text-white text-xl font-bold mb-4">
                                            {{ $loop->iteration }}
                                        </div>
                                        <h3 id="live-sections_builder-{{ $sIdx }}-features_list-{{ $idx }}-title" class="text-lg font-bold text-gray-900 mb-2">{{ $feat['title'] }}</h3>
                                        <p id="live-sections_builder-{{ $sIdx }}-features_list-{{ $idx }}-description" class="text-sm text-gray-600 leading-relaxed">{{ $feat['description'] }}</p>
                                    </div>
                                @endforeach
                            @endif
                        </div>
                    </div>
                </section>
            @endif

            <!-- Testimonials -->
            @if($section->block_type === 'testimonials')
                <section class="py-16 bg-white border-b border-gray-100">
                    <div class="max-w-5xl mx-auto px-6">
                        <h2 id="live-sections_builder-{{ $sIdx }}-title" class="text-2xl lg:text-4xl font-bold text-center mb-12 text-gray-900">
                            {{ $content['title'] ?? 'আমাদের কাস্টমাররা কী বলছেন' }}
                        </h2>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                            @if(isset($content['testimonials_list']))
                                @foreach($content['testimonials_list'] as $idx => $testi)
                                    <div class="p-6 bg-gray-50 rounded-2xl border border-gray-200/60 relative">
                                        <div class="text-yellow-400 text-lg mb-3">
                                            @for($i = 0; $i < ($testi['rating'] ?? 5); $i++)
                                                ★
                                            @endfor
                                        </div>
                                        <p id="live-sections_builder-{{ $sIdx }}-testimonials_list-{{ $idx }}-feedback" class="text-sm text-gray-650 leading-relaxed mb-4 italic">"{{ $testi['feedback'] }}"</p>
                                        <div class="flex items-center gap-3">
                                            @php
                                                 $avatarImageUrl = resolve_preview_image_url($testi['avatar'] ?? null);
                                             @endphp
                                             @if($avatarImageUrl)
                                                 <img class="w-10 h-10 rounded-full object-cover" src="{{ $avatarImageUrl }}" alt="Avatar">
                                             @else
                                                <div class="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center text-xs text-gray-500 font-bold">
                                                    {{ substr($testi['name'], 0, 1) }}
                                                </div>
                                            @endif
                                            <div>
                                                <h4 id="live-sections_builder-{{ $sIdx }}-testimonials_list-{{ $idx }}-name" class="text-sm font-bold text-gray-900">{{ $testi['name'] }}</h4>
                                                <span class="text-xs text-gray-400">Verified Buyer</span>
                                            </div>
                                        </div>
                                    </div>
                                @endforeach
                            @endif
                        </div>
                    </div>
                </section>
            @endif

            <!-- Video Embed Section -->
            @if($section->block_type === 'video_embed')
                <section class="py-16 bg-gray-50 border-b border-gray-100">
                    <div class="max-w-4xl mx-auto px-6 text-center">
                        <h2 id="live-sections_builder-{{ $sIdx }}-title" class="text-2xl lg:text-4xl font-bold mb-8 text-gray-900">
                            {{ $content['title'] ?? 'ভিডিওতে আমাদের প্রোডাক্ট দেখুন' }}
                        </h2>
                        <div class="aspect-video bg-black rounded-2xl overflow-hidden shadow-lg border border-gray-200">
                            @if(isset($content['video_url']))
                                @php
                                    // Extract YouTube video ID
                                    preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $content['video_url'], $match);
                                    $videoId = $match[1] ?? null;
                                @endphp
                                @if($videoId)
                                    <iframe class="w-full h-full" src="https://www.youtube.com/embed/{{ $videoId }}" frameborder="0" allowfullscreen></iframe>
                                @else
                                    <div class="w-full h-full flex items-center justify-center text-white bg-gray-900">Invalid Video URL</div>
                                @endif
                            @else
                                <div class="w-full h-full flex items-center justify-center text-white bg-gray-900">No Video Specified</div>
                            @endif
                        </div>
                    </div>
                </section>
            @endif

            <!-- FAQ Section -->
            @if($section->block_type === 'faq')
                <section class="py-16 bg-white border-b border-gray-100">
                    <div class="max-w-3xl mx-auto px-6">
                        <h2 id="live-sections_builder-{{ $sIdx }}-title" class="text-2xl lg:text-4xl font-bold text-center mb-12 text-gray-900">
                            {{ $content['title'] ?? 'সাধারণ কিছু প্রশ্ন ও উত্তর (FAQ)' }}
                        </h2>
                        <div class="space-y-4">
                            @if(isset($content['faqs']))
                                @foreach($content['faqs'] as $idx => $faq)
                                    <div class="border border-gray-200/80 rounded-xl p-5 bg-gray-50">
                                        <h3 id="live-sections_builder-{{ $sIdx }}-faqs-{{ $idx }}-question" class="text-base font-bold text-gray-900 mb-2 flex items-center gap-2">
                                            <span class="text-theme">Q.</span> {{ $faq['question'] }}
                                        </h3>
                                        <p id="live-sections_builder-{{ $sIdx }}-faqs-{{ $idx }}-answer" class="text-sm text-gray-600 leading-relaxed pl-6">{{ $faq['answer'] }}</p>
                                    </div>
                                @endforeach
                            @endif
                        </div>
                    </div>
                </section>
            @endif

            <!-- Custom HTML Block -->
            @if($section->block_type === 'custom_html')
                <section class="py-8 bg-white">
                    <div class="max-w-6xl mx-auto px-6">
                        {!! $content['code'] ?? '' !!}
                    </div>
                </section>
            @endif

            <!-- Express Checkout Form -->
            @if($section->block_type === 'express_checkout')
                <section id="checkout-section" class="py-16 bg-gray-50">
                    <div class="max-w-xl mx-auto px-6">
                        <div class="bg-white p-8 rounded-2xl border border-gray-200 shadow-lg">
                            <h2 id="live-sections_builder-{{ $sIdx }}-form_title" class="text-xl lg:text-2xl font-bold text-center mb-6 text-gray-900">
                                {{ $content['form_title'] ?? 'অর্ডার কনফার্ম করতে ফর্মটি পূরণ করুন' }}
                            </h2>
                            
                            <form onsubmit="event.preventDefault(); alert('ডামি অর্ডার সফল হয়েছে!');" class="space-y-4">
                                <div>
                                    <label class="block text-xs font-bold uppercase text-gray-500 mb-1">আপনার নাম</label>
                                    <input type="text" placeholder="এখানে নাম লিখুন" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:outline-none focus:border-indigo-500 text-sm" required>
                                </div>
                                <div>
                                    <label class="block text-xs font-bold uppercase text-gray-500 mb-1">মোবাইল নম্বর</label>
                                    <input type="tel" placeholder="১১ ডিজিটের মোবাইল নম্বর" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:outline-none focus:border-indigo-500 text-sm" required>
                                </div>
                                <div>
                                    <label class="block text-xs font-bold uppercase text-gray-500 mb-1">পূর্ণ ঠিকানা</label>
                                    <textarea placeholder="গ্রাম, থানা, জেলা লিখুন" rows="3" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:outline-none focus:border-indigo-500 text-sm" required></textarea>
                                </div>
                                <div>
                                    <label class="block text-xs font-bold uppercase text-gray-500 mb-1">ডেলিভারি এরিয়া</label>
                                    <select class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:outline-none focus:border-indigo-500 text-sm" required>
                                        <option value="inside_dhaka">ঢাকার ভিতরে (৳৮০)</option>
                                        <option value="outside_dhaka">ঢাকার বাইরে (৳১৫০)</option>
                                    </select>
                                </div>

                                <div class="pt-4 border-t border-gray-100">
                                    <div class="flex justify-between font-bold text-gray-900 mb-2 text-sm">
                                        <span>প্রোডাক্টের মূল্য:</span>
                                        <span>৳{{ number_format($page->landing_price ?: ($product->sale_price ?? $product->price), 2) }}</span>
                                    </div>
                                    <div class="flex justify-between text-gray-500 text-xs mb-4">
                                        <span>ডেলিভারি চার্জ:</span>
                                        <span>৳৮০.০০</span>
                                    </div>
                                    <button type="submit" id="live-checkout-btn" class="w-full py-4 rounded-xl font-bold text-lg shadow-md btn-theme">
                                        {{ $content['button_text'] ?? 'অর্ডার সাবমিট করুন' }}
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </section>
            @endif

        @endforeach

    </div>

    <!-- Live Preview Script -->
    <script>
        window.addEventListener('message', function(event) {
            // Validate message origin source
            if (event.data && event.data.source === 'filament-visual-editor') {
                const data = event.data.data;
                console.log('Received postMessage update:', data);

                // Update Style Variables
                if (data.primary_color) {
                    document.documentElement.style.setProperty('--primary-color', data.primary_color);
                }
                if (data.secondary_color) {
                    document.documentElement.style.setProperty('--secondary-color', data.secondary_color);
                }
                if (data.gradient_angle) {
                    document.documentElement.style.setProperty('--gradient-angle', data.gradient_angle + 'deg');
                }
                if (data.font_family) {
                    document.documentElement.style.setProperty('--font-family', "'" + data.font_family + "', sans-serif");
                }

                // Update Template Theme classes
                if (data.template_style) {
                    const root = document.getElementById('landing-page-root');
                    root.className = '';
                    root.classList.add('theme-' + data.template_style, 'min-h-screen');
                }

                // Update Headings and Blocks dynamically in real-time
                for (let [dataKey, val] of Object.entries(data)) {
                    // Convert dots to dashes and remove '-data-' for unified matching
                    const normalizedKey = dataKey.replace(/\./g, '-').replace('-data-', '-');

                    const allLiveElements = document.querySelectorAll('[id^="live-"]');
                    allLiveElements.forEach(el => {
                        const elId = el.getAttribute('id').replace('live-', '');
                        if (normalizedKey.endsWith(elId)) {
                            if (el.tagName === 'A' || el.tagName === 'BUTTON') {
                                el.textContent = val;
                            } else {
                                el.innerHTML = val;
                            }
                        }
                    });
                }
            }
        });
    </script>
</body>
</html>
