<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <title><?php echo e($salesPage->name); ?></title>
    <meta name="description" content="<?php echo e($salesPage->meta_description ?? 'Complete your order for ' . $salesPage->name); ?>">

    <?php
        // Favicon fallback logic: sales page > user company logo > system default
        $faviconPath = $salesPage->getFaviconPath()
            ?? $salesPage->user->company_logo
            ?? asset('favicon.ico');
    ?>
    <link rel="icon" type="image/x-icon" href="<?php echo e(asset($faviconPath)); ?>">
    <link rel="shortcut icon" type="image/x-icon" href="<?php echo e(asset($faviconPath)); ?>">

    <?php echo app('Illuminate\Foundation\Vite')(['resources/css/app.css', 'resources/js/app.js']); ?>

    <?php if($salesPage->facebook_pixel_id): ?>
    <!-- Facebook Pixel Code -->
    <script>
        !function(f,b,e,v,n,t,s)
        {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
        n.callMethod.apply(n,arguments):n.queue.push(arguments)};
        if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
        n.queue=[];t=b.createElement(e);t.async=!0;
        t.src=v;s=b.getElementsByTagName(e)[0];
        s.parentNode.insertBefore(t,s)}(window, document,'script',
        'https://connect.facebook.net/en_US/fbevents.js');
        fbq('init', '<?php echo e($salesPage->facebook_pixel_id); ?>');
        fbq('track', 'PageView');
    </script>
    <noscript>
        <img height="1" width="1" style="display:none"
             src="https://www.facebook.com/tr?id=<?php echo e($salesPage->facebook_pixel_id); ?>&ev=PageView&noscript=1"/>
    </noscript>
    <?php endif; ?>

    <?php if($salesPage->google_analytics_id): ?>
    <!-- Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo e($salesPage->google_analytics_id); ?>"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '<?php echo e($salesPage->google_analytics_id); ?>');
    </script>
    <?php endif; ?>

    <?php if($salesPage->tiktok_pixel_id): ?>
    <!-- TikTok Pixel Code -->
    <script>
        !function (w, d, t) {
            w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"],ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e},ttq.load=function(e,n){var i="https://analytics.tiktok.com/i18n/pixel/events.js";ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=i,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src=i+"?sdkid="+e+"&lib="+t;var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(o,a)};
            ttq.load('<?php echo e($salesPage->tiktok_pixel_id); ?>');
            ttq.page();
        }(window, document, 'ttq');
    </script>
    <?php endif; ?>

    <style>
        :root {
            --primary-color: <?php echo e($salesPage->primary_color); ?>;
        }
        .btn-primary {
            background-color: var(--primary-color);
        }
        .btn-primary:hover {
            filter: brightness(0.9);
        }

        /* Custom checkbox styling */
        input[type="checkbox"]:checked {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        /* Smooth transitions for all interactive elements */
        input, select, textarea {
            transition: all 0.3s ease;
        }

        input:focus, select:focus, textarea:focus {
            outline: none;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        /* Mobile-first optimization */
        .content-wrapper img {
            max-width: 100%;
            height: auto;
            display: block;
            margin: 0;
            padding: 0;
            border: none;
            vertical-align: top;
        }
        .content-wrapper {
            font-size: 15px;
            line-height: 1.6;
        }
        .content-wrapper > div {
            line-height: 0;
        }
        /* Legal content styling */
        .legal-content h2 {
            font-size: 1rem;
            font-weight: bold;
            color: #1f2937;
            margin-bottom: 0.75rem;
            margin-top: 1rem;
        }
        .legal-content h3 {
            font-size: 0.875rem;
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
            margin-top: 0.75rem;
        }
        .legal-content p {
            margin-bottom: 0.5rem;
            line-height: 1.5;
        }
        .legal-content ul, .legal-content ol {
            margin-left: 1.25rem;
            margin-bottom: 0.75rem;
            line-height: 1.5;
        }
        .legal-content li {
            margin-bottom: 0.25rem;
        }
        .legal-content a {
            color: #3b82f6;
            text-decoration: underline;
        }
        .legal-content a:hover {
            color: #2563eb;
        }
        .legal-content strong {
            font-weight: 600;
            color: #374151;
        }

        /* ========================================
           LITE YOUTUBE EMBED - Fast Loading Videos
           Portrait Format (9:16) - Phone View Style
           ======================================== */

        /* YouTube video title styling */
        .lite-youtube-title {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1f2937;
            margin-top: 0.75rem;
            margin-bottom: 0.75rem;
            padding: 0 0.5rem;
            line-height: 1.4;
            text-align: center;
        }

        /* YouTube video wrapper (contains title + video) */
        .lite-youtube-wrapper {
            margin-bottom: 1rem;
        }

        /* YouTube video container - 9:16 aspect ratio (Portrait/Shorts) */
        .lite-youtube {
            position: relative;
            display: block;
            width: 100%;
            padding-bottom: 177.78%; /* 9:16 aspect ratio */
            background-color: #000;
            cursor: pointer;
            margin: 0 auto;
            overflow: hidden;
        }

        /* Thumbnail background image */
        .lite-youtube::before {
            content: '';
            display: block;
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-position: center center;
            background-size: cover; /* Fill container and show center portion */
            background-repeat: no-repeat;
            transition: opacity 0.3s ease;
        }

        /* Hover effect on thumbnail */
        .lite-youtube:hover::before {
            opacity: 0.85;
        }

        /* Play button overlay */
        .lite-youtube-play {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 68px;
            height: 48px;
            background-color: rgba(255, 0, 0, 0.9);
            border-radius: 14px;
            transition: all 0.3s ease;
            z-index: 1;
        }

        /* Play button triangle */
        .lite-youtube-play::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-35%, -50%);
            width: 0;
            height: 0;
            border-style: solid;
            border-width: 11px 0 11px 19px;
            border-color: transparent transparent transparent #fff;
        }

        /* Hover effect on play button */
        .lite-youtube:hover .lite-youtube-play {
            background-color: rgba(255, 0, 0, 1);
            transform: translate(-50%, -50%) scale(1.1);
        }

        /* Actual iframe (loaded after click) */
        .lite-youtube > iframe {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border: 0;
        }

        /* Mobile optimization */
        @media (max-width: 640px) {
            .lite-youtube-play {
                width: 60px;
                height: 42px;
            }
            .lite-youtube-play::before {
                border-width: 9px 0 9px 16px;
            }
        }
    </style>
</head>
<body class="bg-gray-100">
    <!-- Mobile-optimized container: 600px max width with spacing -->
    <div class="max-w-[600px] mx-4 sm:mx-auto my-4 bg-white shadow-lg rounded-xl overflow-hidden">

        <!-- Logo section -->
        <?php if($salesPage->logo_path && $salesPage->show_logo): ?>
        <div class="text-center py-4 px-3 bg-white rounded-t-xl border-b">
            <img src="<?php echo e(asset($salesPage->logo_path)); ?>" alt="<?php echo e($salesPage->name); ?>" class="h-12 mx-auto">
        </div>
        <?php endif; ?>

        <!-- HTML Content Area -->
        <div class="bg-white <?php echo e(!($salesPage->logo_path && $salesPage->show_logo) ? 'rounded-t-xl' : ''); ?>">
            <div class="content-wrapper px-3 py-4">
                <?php echo $salesPage->html_content; ?>

            </div>
        </div>

        <!-- FAQ Section -->
        <?php if(!empty($salesPage->faq_items) && count($salesPage->faq_items) > 0): ?>
        <div class="bg-white px-4 py-6">
            <div class="max-w-4xl mx-auto">
                <div class="space-y-3">
                    <?php $__currentLoopData = $salesPage->faq_items; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $faq): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <?php if(!empty($faq['question'])): ?>
                        <div class="faq-accordion border border-gray-200 rounded-lg overflow-hidden">
                            <button type="button" class="faq-question w-full text-left px-4 py-4 bg-white hover:bg-gray-50 flex justify-between items-center transition-colors"
                                    onclick="toggleFaq(<?php echo e($index); ?>)">
                                <span class="font-medium text-gray-900 pr-4"><?php echo e($faq['question']); ?></span>
                                <svg class="faq-icon w-5 h-5 text-gray-600 flex-shrink-0 transition-transform duration-200"
                                     id="faq-icon-<?php echo e($index); ?>"
                                     fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                                </svg>
                            </button>
                            <div class="faq-answer hidden bg-gray-50 px-4 py-4 border-t border-gray-200"
                                 id="faq-answer-<?php echo e($index); ?>">
                                <div class="text-gray-700 text-sm leading-relaxed">
                                    <?php echo $faq['answer'] ?? ''; ?>

                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Spacer for visual separation -->
        <div class="py-2 bg-gray-100"></div>

        <!-- Order Form -->
        <div class="px-4 py-6 bg-gradient-to-b from-gray-50 to-white" id="order-form-section">
            <div class="mx-auto">
                <div class="text-center mb-6">
                    <h2 class="text-2xl font-bold mb-2" style="color: var(--primary-color)">Complete Your Order</h2>
                    <p class="text-sm text-gray-600">Fill in your details below to place your order</p>
                </div>

                <form id="order-form" class="space-y-4">

                    <!-- Product Selection -->
                    <?php if($products->count() > 0): ?>
                    <div class="bg-white p-4 rounded border border-gray-200">
                        <h3 class="font-semibold text-base mb-3 text-gray-900">Select Products</h3>

                        <div class="space-y-2.5">
                            <?php $__currentLoopData = $products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <label class="flex items-start gap-3 p-3 border border-gray-200 rounded cursor-pointer transition-all duration-200 hover:border-blue-300 product-item">
                                <input type="checkbox" name="products[]" value="<?php echo e($product->id); ?>"
                                       data-price="<?php echo e($product->price); ?>"
                                       data-name="<?php echo e($product->name); ?>"
                                       class="product-checkbox mt-0.5 w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:ring-offset-0 transition-all"
                                       onchange="updateTotal()">
                                <div class="flex-1 min-w-0">
                                    <div class="font-medium text-sm text-gray-900 mb-1"><?php echo e($product->name); ?></div>
                                    <?php if($product->description): ?>
                                    <div class="text-xs text-gray-600 mb-2 leading-relaxed"><?php echo e($product->description); ?></div>
                                    <?php endif; ?>
                                    <div class="flex items-center justify-between gap-3">
                                        <div class="font-semibold text-base text-blue-600">
                                            RM <?php echo e(number_format($product->price, 2)); ?>

                                        </div>
                                        <div class="flex items-center gap-2">
                                            <span class="text-xs font-medium text-gray-600">Qty:</span>
                                            <select name="quantities[<?php echo e($product->id); ?>]"
                                                    id="qty-<?php echo e($product->id); ?>"
                                                    class="product-quantity border border-gray-300 rounded px-2 py-1 text-sm font-medium w-14 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all"
                                                    onchange="updateTotal()"
                                                    disabled>
                                                <?php for($i = 1; $i <= 10; $i++): ?>
                                                    <option value="<?php echo e($i); ?>"><?php echo e($i); ?></option>
                                                <?php endfor; ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </label>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>

                        <!-- Order Bump / Upsell -->
                        <?php if($salesPage->order_bump_enabled && $salesPage->order_bump_product_id && $salesPage->orderBumpProduct): ?>
                        <div id="order-bump-offer" class="mt-4 hidden">
                            <div class="p-4 rounded-lg"
                                 style="background-color: <?php echo e($salesPage->order_bump_bg_color); ?>;
                                        color: <?php echo e($salesPage->order_bump_text_color); ?>;
                                        border: 2px <?php echo e($salesPage->order_bump_border_style); ?> <?php echo e($salesPage->order_bump_border_color); ?>;">
                                <label class="flex items-start gap-3 cursor-pointer">
                                    <input type="checkbox" name="order_bump" id="order-bump-checkbox"
                                           value="<?php echo e($salesPage->orderBumpProduct->id); ?>"
                                           data-price="<?php echo e($salesPage->orderBumpProduct->price); ?>"
                                           data-name="<?php echo e($salesPage->orderBumpProduct->name); ?>"
                                           class="mt-1 w-5 h-5 rounded"
                                           onchange="updateTotal()">
                                    <div class="flex-1">
                                        <div class="font-bold text-base mb-1">
                                            <?php echo e($salesPage->order_bump_text ?: 'Special Offer!'); ?>

                                        </div>
                                        <div class="text-sm opacity-90">
                                            <?php echo e($salesPage->orderBumpProduct->name); ?> - RM <?php echo e(number_format($salesPage->orderBumpProduct->price, 2)); ?>

                                        </div>
                                    </div>
                                </label>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- Total Display -->
                        <div class="mt-3 pt-3 border-t border-gray-200">
                            <div class="flex justify-between items-center p-3 bg-gray-50 rounded">
                                <span class="text-sm font-semibold text-gray-800">Total Amount</span>
                                <span class="text-xl font-bold text-blue-600">RM <span id="total-amount">0.00</span></span>
                            </div>
                        </div>
                    </div>

                    <style>
                        .product-item:has(.product-checkbox:checked) {
                            border-color: #3b82f6;
                            background-color: #eff6ff;
                        }
                    </style>
                    <?php endif; ?>

                    <!-- Customer Information -->
                    <div class="bg-white p-5 rounded-lg shadow-sm border border-gray-200">
                        <div class="mb-4 pb-3 border-b border-gray-100">
                            <h3 class="font-bold text-lg" style="color: var(--primary-color)">Customer Information</h3>
                        </div>

                        <div class="space-y-3">
                            <!-- Phone Number - First for Auto-fill -->
                            <div>
                                <input type="tel" id="customer_phone" name="customer_phone" required
                                       placeholder="Phone Number (e.g. 012-3456789)"
                                       class="w-full rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-base py-3 px-4 placeholder:text-gray-400 transition-all">
                                <p id="customer-autofill-status" class="text-xs mt-1.5 hidden font-medium"></p>
                            </div>

                            <input type="text" id="customer_name" name="customer_name" required
                                   placeholder="Full Name"
                                   class="w-full rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-base py-3 px-4 placeholder:text-gray-400 transition-all">

                            <input type="email" id="customer_email" name="customer_email"
                                   placeholder="Email (Optional)"
                                   class="w-full rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-base py-3 px-4 placeholder:text-gray-400 transition-all">

                            <textarea id="customer_address" name="customer_address" rows="3" required
                                      placeholder="Full Address"
                                      class="w-full rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-base py-3 px-4 leading-relaxed placeholder:text-gray-400 transition-all"></textarea>

                            <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                                <div class="space-y-3">
                                    <div>
                                        <label class="block text-xs font-medium text-gray-600 mb-1">Postcode</label>
                                        <input type="text" name="customer_postcode" id="customer_postcode" required
                                               pattern="[0-9]{5}"
                                               placeholder="e.g. 50000"
                                               maxlength="5"
                                               class="w-full rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-base py-3 px-4 font-medium placeholder:text-gray-400 transition-all">
                                        <p id="postcode-status" class="text-xs mt-1.5 hidden font-medium"></p>
                                    </div>

                                    <div>
                                        <label class="block text-xs font-medium text-gray-600 mb-1">City</label>
                                        <input type="text" name="customer_city" id="customer_city" required readonly
                                               placeholder="Auto-filled"
                                               class="w-full rounded-lg border border-gray-200 bg-gray-100 text-base py-3 px-4 font-medium text-gray-700 placeholder:text-gray-400">
                                    </div>

                                    <div>
                                        <label class="block text-xs font-medium text-gray-600 mb-1">State</label>
                                        <input type="text" name="customer_state" id="customer_state" required readonly
                                               placeholder="Auto-filled"
                                               class="w-full rounded-lg border border-gray-200 bg-gray-100 text-base py-3 px-4 font-medium text-gray-700 placeholder:text-gray-400">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Payment Method Selection -->
                    <div class="bg-white p-4 rounded border border-gray-200">
                        <h3 class="font-semibold text-base mb-3 text-gray-900">Payment Method</h3>

                        <div class="space-y-2.5">
                            <!-- FPX / Online Banking -->
                            <label class="flex items-center gap-3 p-3 border border-gray-200 rounded cursor-pointer transition-all duration-200 hover:border-blue-300 payment-method-option">
                                <input type="radio" name="payment_method" value="fpx" required
                                       class="w-4 h-4 text-blue-600 border-gray-300 focus:ring-2 focus:ring-blue-500 focus:ring-offset-0 transition-all"
                                       onchange="updatePaymentMethod()">
                                <div class="flex-1">
                                    <div class="font-medium text-sm text-gray-900">Online Banking (FPX)</div>
                                    <div class="text-xs text-gray-600 mt-0.5">Pay via bank transfer</div>
                                    <div class="text-xs text-blue-600 font-medium mt-1" id="fpx-fee-info"></div>
                                </div>
                                <img src="<?php echo e(asset('images/payment-methods/fpx-logo.png')); ?>" alt="FPX" class="h-6 w-auto object-contain ml-2">
                            </label>

                            <!-- DuitNow QR -->
                            <label class="flex items-center gap-3 p-3 border border-gray-200 rounded cursor-pointer transition-all duration-200 hover:border-blue-300 payment-method-option">
                                <input type="radio" name="payment_method" value="duitnow" required
                                       class="w-4 h-4 text-blue-600 border-gray-300 focus:ring-2 focus:ring-blue-500 focus:ring-offset-0 transition-all"
                                       onchange="updatePaymentMethod()">
                                <div class="flex-1">
                                    <div class="font-medium text-sm text-gray-900">DuitNow QR</div>
                                    <div class="text-xs text-gray-600 mt-0.5">Scan QR code to pay</div>
                                    <div class="text-xs text-blue-600 font-medium mt-1" id="duitnow-fee-info"></div>
                                </div>
                                <img src="<?php echo e(asset('images/payment-methods/duitnow-logo.png')); ?>" alt="DuitNow QR" class="h-10 w-auto object-contain ml-2">
                            </label>

                            <!-- Cash on Delivery -->
                            <label class="flex items-center gap-3 p-3 border border-gray-200 rounded cursor-pointer transition-all duration-200 hover:border-blue-300 payment-method-option">
                                <input type="radio" name="payment_method" value="cod" required
                                       class="w-4 h-4 text-blue-600 border-gray-300 focus:ring-2 focus:ring-blue-500 focus:ring-offset-0 transition-all"
                                       onchange="updatePaymentMethod()">
                                <div class="flex-1">
                                    <div class="font-medium text-sm text-gray-900">Cash on Delivery (COD)</div>
                                    <div class="text-xs text-gray-600 mt-0.5">Pay when you receive</div>
                                    <div class="text-xs text-blue-600 font-medium mt-1" id="cod-fee-info"></div>
                                </div>
                            </label>
                        </div>

                        <!-- Updated Total with Fees -->
                        <div class="mt-3 pt-3 border-t border-gray-200">
                            <div id="payment-fee-row" class="flex justify-between text-xs text-gray-600 mb-2 hidden">
                                <span id="payment-fee-label">Fee</span>
                                <span class="font-semibold" id="payment-fee-display">RM 0.00</span>
                            </div>
                            <div class="flex justify-between items-center p-3 bg-gray-50 rounded">
                                <span class="text-sm font-semibold text-gray-800">Grand Total</span>
                                <span class="text-xl font-bold text-blue-600">RM <span id="grand-total">0.00</span></span>
                            </div>
                        </div>
                    </div>

                    <style>
                        .payment-method-option:has(input:checked) {
                            border-color: #3b82f6;
                            background-color: #eff6ff;
                        }
                    </style>

                    <!-- Submit Button -->
                    <div class="pt-2 pb-3">
                        <button type="submit"
                                class="btn-primary text-white w-full py-4 rounded-lg text-lg font-bold hover:shadow-xl transition-all duration-300 transform hover:scale-[1.01] flex items-center justify-center gap-2">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                            </svg>
                            <span>Complete Order</span>
                        </button>
                        <p class="text-sm text-center text-gray-600 mt-3 leading-relaxed">
                            Secure payment processing
                        </p>
                    </div>

                </form>
            </div>
        </div>

        <!-- Legal / Marketing / Permission Section -->
        <?php if($salesPage->legal_content): ?>
        <div class="bg-white px-4 py-4 border-t border-gray-200">
            <div class="mx-auto px-2">
                <div class="legal-content text-xs text-gray-600 leading-relaxed">
                    <?php echo $salesPage->legal_content; ?>

                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Footer -->
        <div class="bg-gray-50 py-4 px-4 text-center border-t border-gray-200">
            <p class="text-xs text-gray-500">© <?php echo e(date('Y')); ?> <?php echo e($salesPage->name); ?></p>
        </div>

    </div>

    <!-- Loading Overlay -->
    <div id="loading-overlay" class="hidden fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-50">
        <div class="bg-white rounded-2xl p-8 text-center shadow-2xl max-w-sm mx-4">
            <div class="animate-spin rounded-full h-16 w-16 border-4 border-blue-200 border-t-blue-600 mx-auto mb-4"></div>
            <p class="text-lg font-semibold text-gray-800 mb-2">Submitting order...</p>
            <p class="text-sm text-gray-600">Please wait a moment</p>
        </div>
    </div>

    <script>
        // Debug Mode: Log tracking events to console (set to false in production)
        const DEBUG_TRACKING = true;

        function logTrackingEvent(platform, eventName, data) {
            if (DEBUG_TRACKING) {
                console.log('🎯 TRACKING EVENT:', {
                    platform: platform,
                    event: eventName,
                    data: data,
                    timestamp: new Date().toISOString()
                });
            }
        }

        // Show tracking configuration status on page load
        console.log('%c📊 SALES PAGE TRACKING STATUS', 'font-weight: bold; font-size: 14px; color: #4F46E5;');
        console.log('Sales Page:', '<?php echo e($salesPage->name); ?>');
        console.log('Facebook Pixel:', '<?php echo e($salesPage->facebook_pixel_id ? "✅ Configured (" . $salesPage->facebook_pixel_id . ")" : "❌ Not configured"); ?>');
        console.log('TikTok Pixel:', '<?php echo e($salesPage->tiktok_pixel_id ? "✅ Configured (" . $salesPage->tiktok_pixel_id . ")" : "❌ Not configured"); ?>');
        console.log('Google Analytics:', '<?php echo e($salesPage->google_analytics_id ? "✅ Configured (" . $salesPage->google_analytics_id . ")" : "❌ Not configured"); ?>');
        console.log('%c━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', 'color: #E5E7EB;');

        // Customer auto-fill functionality
        const phoneInput = document.getElementById('customer_phone');
        const nameInput = document.getElementById('customer_name');
        const emailInput = document.getElementById('customer_email');
        const addressInput = document.getElementById('customer_address');
        const customerStatus = document.getElementById('customer-autofill-status');

        let customerLookupTimer;

        if (phoneInput) {
            phoneInput.addEventListener('input', function() {
                const phone = this.value.trim();

                // Clear previous timer
                clearTimeout(customerLookupTimer);

                // Remove non-numeric characters except +
                const cleanPhone = phone.replace(/[^0-9+]/g, '');
                const digitCount = cleanPhone.replace(/[^0-9]/g, '').length;

                // Only lookup if we have at least 10 digits
                if (digitCount >= 10) {
                    customerLookupTimer = setTimeout(() => {
                        lookupCustomer(phone);
                    }, 500); // 500ms debounce
                }
            });
        }

        async function lookupCustomer(phone) {
            try {
                customerStatus.textContent = 'Looking up customer...';
                customerStatus.className = 'text-xs mt-1.5 font-medium text-blue-500';
                customerStatus.classList.remove('hidden');

                const csrfToken = document.querySelector('meta[name="csrf-token"]');
                if (!csrfToken) {
                    console.error('CSRF token not found!');
                    return;
                }

                const response = await fetch('/api/customer/lookup', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken.content
                    },
                    body: JSON.stringify({ phone: phone })
                });

                const result = await response.json();

                if (result.found && result.customer) {
                    // Auto-fill customer data
                    if (nameInput) nameInput.value = result.customer.name || '';
                    if (emailInput) emailInput.value = result.customer.email || '';
                    if (addressInput) addressInput.value = result.customer.address || '';
                    if (cityInput) cityInput.value = result.customer.city || '';
                    if (stateInput) stateInput.value = result.customer.state || '';
                    if (postcodeInput) postcodeInput.value = result.customer.postcode || '';

                    // Visual feedback
                    customerStatus.textContent = '✓ Customer found! Information auto-filled';
                    customerStatus.className = 'text-xs mt-1.5 font-medium text-green-600';

                    setTimeout(() => {
                        customerStatus.classList.add('hidden');
                    }, 3000);
                } else {
                    // Customer not found - hide status
                    customerStatus.classList.add('hidden');
                }
            } catch (error) {
                console.error('Error looking up customer:', error);
                customerStatus.classList.add('hidden');
            }
        }

        // Postcode auto-fill functionality
        const postcodeInput = document.getElementById('customer_postcode');
        const cityInput = document.getElementById('customer_city');
        const stateInput = document.getElementById('customer_state');
        const postcodeStatus = document.getElementById('postcode-status');

        let debounceTimer;

        postcodeInput.addEventListener('input', function() {
            const postcode = this.value.trim();

            // Clear previous results
            cityInput.value = '';
            stateInput.value = '';
            postcodeStatus.classList.add('hidden');

            // Only search when 5 digits entered
            if (postcode.length !== 5 || !/^\d{5}$/.test(postcode)) {
                return;
            }

            // Debounce the API call
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => {
                // Show loading
                postcodeStatus.textContent = 'Searching...';
                postcodeStatus.className = 'text-xs mt-1 text-blue-600';
                postcodeStatus.classList.remove('hidden');

                // Fetch postcode data
                fetch(`/api/postcode/${postcode}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            cityInput.value = data.city;
                            stateInput.value = data.state;
                            postcodeStatus.textContent = data.city + ', ' + data.state;
                            postcodeStatus.className = 'text-xs mt-1.5 text-green-600 font-medium';
                        } else {
                            postcodeStatus.textContent = data.message;
                            postcodeStatus.className = 'text-xs mt-1.5 text-red-600 font-medium';
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        postcodeStatus.textContent = 'Error searching postcode';
                        postcodeStatus.className = 'text-xs mt-1.5 text-red-600 font-medium';
                    });
            }, 500); // 500ms debounce
        });

        // Track page view on load
        window.addEventListener('load', function() {
            fetch('<?php echo e(route("sales-page.track-view", $salesPage->slug)); ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: JSON.stringify({
                    referrer: document.referrer,
                    utm_source: new URLSearchParams(window.location.search).get('utm_source'),
                    utm_medium: new URLSearchParams(window.location.search).get('utm_medium'),
                    utm_campaign: new URLSearchParams(window.location.search).get('utm_campaign'),
                    utm_content: new URLSearchParams(window.location.search).get('utm_content'),
                })
            });
        });

        // Product selection and quantity management
        document.querySelectorAll('.product-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const productId = this.value;
                const qtySelect = document.getElementById('qty-' + productId);
                qtySelect.disabled = !this.checked;
                if (!this.checked) {
                    qtySelect.value = 1;
                } else {
                    // Track AddToCart event when product is selected
                    const productName = this.dataset.name;
                    const productPrice = parseFloat(this.dataset.price);
                    const quantity = parseInt(qtySelect.value);

                    // Always log when product is added (even without pixels configured)
                    console.log('✅ PRODUCT SELECTED:', {
                        product_id: productId,
                        product_name: productName,
                        price: productPrice,
                        quantity: quantity,
                        total: productPrice * quantity
                    });

                    <?php if($salesPage->facebook_pixel_id): ?>
                    if (typeof fbq !== 'undefined') {
                        const fbData = {
                            content_name: productName,
                            content_ids: [productId],
                            content_type: 'product',
                            value: productPrice * quantity,
                            currency: 'MYR'
                        };
                        fbq('track', 'AddToCart', fbData);
                        logTrackingEvent('Facebook Pixel', 'AddToCart', fbData);
                    } else {
                        console.warn('⚠️ Facebook Pixel (fbq) not loaded');
                    }
                    <?php endif; ?>

                    <?php if($salesPage->tiktok_pixel_id): ?>
                    if (typeof ttq !== 'undefined') {
                        const ttqData = {
                            content_id: productId,
                            content_name: productName,
                            content_type: 'product',
                            quantity: quantity,
                            price: productPrice,
                            value: productPrice * quantity,
                            currency: 'MYR'
                        };
                        ttq.track('AddToCart', ttqData);
                        logTrackingEvent('TikTok Pixel', 'AddToCart', ttqData);
                    } else {
                        console.warn('⚠️ TikTok Pixel (ttq) not loaded');
                    }
                    <?php endif; ?>

                    <?php if($salesPage->google_analytics_id): ?>
                    if (typeof gtag !== 'undefined') {
                        const gaData = {
                            currency: 'MYR',
                            value: productPrice * quantity,
                            items: [{
                                item_id: productId,
                                item_name: productName,
                                price: productPrice,
                                quantity: quantity
                            }]
                        };
                        gtag('event', 'add_to_cart', gaData);
                        logTrackingEvent('Google Analytics', 'add_to_cart', gaData);
                    } else {
                        console.warn('⚠️ Google Analytics (gtag) not loaded');
                    }
                    <?php endif; ?>

                    <?php if(!$salesPage->facebook_pixel_id && !$salesPage->tiktok_pixel_id && !$salesPage->google_analytics_id): ?>
                    console.warn('⚠️ No tracking pixels configured for this sales page. Configure Facebook Pixel, TikTok Pixel, or Google Analytics in sales page settings.');
                    <?php endif; ?>
                }
            });
        });

        // COD fee rates
        const codRateEast = <?php echo e(\App\Models\SystemSetting::get('cod_rate_east_malaysia', 20.00)); ?>;
        const codRatePeninsular = <?php echo e(\App\Models\SystemSetting::get('cod_rate_peninsular', 10.00)); ?>;
        const eastMalaysiaStates = ['Sabah', 'Sarawak', 'Wp Labuan'];

        // FPX fee settings
        const fpxFeeSettings = <?php echo json_encode($fpxFeeSettings, 15, 512) ?>;

        // DuitNow fee settings
        const duitnowFeeSettings = <?php echo json_encode($duitnowFeeSettings, 15, 512) ?>;

        // Calculate payment gateway fee
        function calculateGatewayFee(amount, settings) {
            if (settings.fee_type === 'none' || settings.bearer !== 'customer') {
                return 0;
            }

            let fee = 0;
            if (settings.fee_type === 'fixed' || settings.fee_type === 'both') {
                fee += parseFloat(settings.fixed_fee);
            }
            if (settings.fee_type === 'percentage' || settings.fee_type === 'both') {
                fee += amount * (parseFloat(settings.percentage_fee) / 100);
            }

            return fee;
        }

        // Calculate total amount
        function updateTotal() {
            let total = 0;
            const checkedProducts = document.querySelectorAll('.product-checkbox:checked');

            checkedProducts.forEach(checkbox => {
                const price = parseFloat(checkbox.dataset.price);
                const productId = checkbox.value;
                const qty = parseInt(document.getElementById('qty-' + productId).value);
                total += price * qty;
            });

            // Show/hide order bump based on whether products are selected
            const orderBumpOffer = document.getElementById('order-bump-offer');
            if (orderBumpOffer) {
                if (checkedProducts.length > 0) {
                    orderBumpOffer.classList.remove('hidden');
                } else {
                    orderBumpOffer.classList.add('hidden');
                    // Uncheck order bump if no products selected
                    const orderBumpCheckbox = document.getElementById('order-bump-checkbox');
                    if (orderBumpCheckbox) {
                        orderBumpCheckbox.checked = false;
                    }
                }

                // Add order bump to total if checked
                const orderBumpCheckbox = document.getElementById('order-bump-checkbox');
                if (orderBumpCheckbox && orderBumpCheckbox.checked) {
                    total += parseFloat(orderBumpCheckbox.dataset.price);
                }
            }

            document.getElementById('total-amount').textContent = total.toFixed(2);
            updateGrandTotal(total);
        }

        // Update grand total based on payment method
        function updateGrandTotal(subtotal) {
            const selectedPayment = document.querySelector('input[name="payment_method"]:checked');
            let grandTotal = subtotal;
            let fee = 0;
            let feeLabel = '';

            if (selectedPayment) {
                if (selectedPayment.value === 'cod') {
                    const state = document.getElementById('customer_state').value;
                    fee = eastMalaysiaStates.includes(state) ? codRateEast : codRatePeninsular;
                    feeLabel = 'COD Shipping Fee';
                } else if (selectedPayment.value === 'fpx') {
                    fee = calculateGatewayFee(subtotal, fpxFeeSettings);
                    feeLabel = 'Payment Processing Fee';
                } else if (selectedPayment.value === 'duitnow') {
                    fee = calculateGatewayFee(subtotal, duitnowFeeSettings);
                    feeLabel = 'Payment Processing Fee';
                }

                grandTotal = subtotal + fee;

                // Show/hide fee row
                if (fee > 0) {
                    document.getElementById('payment-fee-row').classList.remove('hidden');
                    document.getElementById('payment-fee-label').textContent = feeLabel;
                    document.getElementById('payment-fee-display').textContent = 'RM ' + fee.toFixed(2);
                } else {
                    document.getElementById('payment-fee-row').classList.add('hidden');
                }
            } else {
                document.getElementById('payment-fee-row').classList.add('hidden');
            }

            document.getElementById('grand-total').textContent = grandTotal.toFixed(2);
        }

        // Update payment method and recalculate total
        function updatePaymentMethod() {
            const selectedPayment = document.querySelector('input[name="payment_method"]:checked');
            const state = document.getElementById('customer_state').value;
            const subtotal = parseFloat(document.getElementById('total-amount').textContent);

            // Clear all fee info displays
            document.getElementById('fpx-fee-info').textContent = '';
            document.getElementById('duitnow-fee-info').textContent = '';
            document.getElementById('cod-fee-info').textContent = '';

            // Show fee info for selected payment method
            if (selectedPayment) {
                if (selectedPayment.value === 'cod') {
                    const codFee = eastMalaysiaStates.includes(state) ? codRateEast : codRatePeninsular;
                    document.getElementById('cod-fee-info').textContent = '+RM ' + codFee.toFixed(2) + ' shipping fee';
                } else if (selectedPayment.value === 'fpx') {
                    const fpxFee = calculateGatewayFee(subtotal, fpxFeeSettings);
                    if (fpxFee > 0) {
                        document.getElementById('fpx-fee-info').textContent = '+RM ' + fpxFee.toFixed(2) + ' processing fee';
                    }
                } else if (selectedPayment.value === 'duitnow') {
                    const duitnowFee = calculateGatewayFee(subtotal, duitnowFeeSettings);
                    if (duitnowFee > 0) {
                        document.getElementById('duitnow-fee-info').textContent = '+RM ' + duitnowFee.toFixed(2) + ' processing fee';
                    }
                }
            }

            // Recalculate grand total
            updateGrandTotal(subtotal);
        }

        // Form submission
        document.getElementById('order-form').addEventListener('submit', function(e) {
            e.preventDefault();

            // Validate at least one product selected
            const selectedProducts = document.querySelectorAll('.product-checkbox:checked');
            if (selectedProducts.length === 0) {
                alert('Please select at least one product');
                return;
            }

            // Validate payment method selected
            const selectedPayment = document.querySelector('input[name="payment_method"]:checked');
            if (!selectedPayment) {
                alert('Please select a payment method');
                return;
            }

            // Collect form data
            const formData = new FormData(this);
            const items = [];

            selectedProducts.forEach(checkbox => {
                const productId = checkbox.value;
                const qty = parseInt(document.getElementById('qty-' + productId).value);
                const price = parseFloat(checkbox.dataset.price);
                const name = checkbox.dataset.name;

                items.push({
                    product_id: productId,
                    quantity: qty,
                    price: price,
                    name: name
                });
            });

            // Add order bump if selected
            const orderBumpCheckbox = document.getElementById('order-bump-checkbox');
            if (orderBumpCheckbox && orderBumpCheckbox.checked) {
                items.push({
                    product_id: orderBumpCheckbox.value,
                    quantity: 1,
                    price: parseFloat(orderBumpCheckbox.dataset.price),
                    name: orderBumpCheckbox.dataset.name
                });
            }

            // Track InitiateCheckout event
            const checkoutValue = parseFloat(document.getElementById('grand-total').textContent);
            const totalItems = items.reduce((sum, item) => sum + item.quantity, 0);

            // Always log when checkout is initiated (even without pixels configured)
            console.log('✅ CHECKOUT INITIATED:', {
                total_value: checkoutValue,
                total_items: totalItems,
                items: items,
                payment_method: selectedPayment.value
            });

            <?php if($salesPage->facebook_pixel_id): ?>
            if (typeof fbq !== 'undefined') {
                const contentIds = items.map(item => item.product_id);
                const contents = items.map(item => ({
                    id: item.product_id,
                    quantity: item.quantity,
                    item_price: item.price
                }));

                const fbCheckoutData = {
                    content_ids: contentIds,
                    content_type: 'product',
                    contents: contents,
                    value: checkoutValue,
                    currency: 'MYR',
                    num_items: totalItems
                };
                fbq('track', 'InitiateCheckout', fbCheckoutData);
                logTrackingEvent('Facebook Pixel', 'InitiateCheckout', fbCheckoutData);
            } else {
                console.warn('⚠️ Facebook Pixel (fbq) not loaded');
            }
            <?php endif; ?>

            <?php if($salesPage->tiktok_pixel_id): ?>
            if (typeof ttq !== 'undefined') {
                const ttqContents = items.map(item => ({
                    content_id: item.product_id,
                    content_name: item.name,
                    quantity: item.quantity,
                    price: item.price
                }));

                const ttqCheckoutData = {
                    contents: ttqContents,
                    value: checkoutValue,
                    currency: 'MYR',
                    content_type: 'product'
                };
                ttq.track('InitiateCheckout', ttqCheckoutData);
                logTrackingEvent('TikTok Pixel', 'InitiateCheckout', ttqCheckoutData);
            } else {
                console.warn('⚠️ TikTok Pixel (ttq) not loaded');
            }
            <?php endif; ?>

            <?php if($salesPage->google_analytics_id): ?>
            if (typeof gtag !== 'undefined') {
                const gaItems = items.map(item => ({
                    item_id: item.product_id,
                    item_name: item.name,
                    price: item.price,
                    quantity: item.quantity
                }));

                const gaCheckoutData = {
                    currency: 'MYR',
                    value: checkoutValue,
                    items: gaItems
                };
                gtag('event', 'begin_checkout', gaCheckoutData);
                logTrackingEvent('Google Analytics', 'begin_checkout', gaCheckoutData);
            } else {
                console.warn('⚠️ Google Analytics (gtag) not loaded');
            }
            <?php endif; ?>

            <?php if(!$salesPage->facebook_pixel_id && !$salesPage->tiktok_pixel_id && !$salesPage->google_analytics_id): ?>
            console.warn('⚠️ No tracking pixels configured. To track conversions, add Facebook Pixel ID in sales page settings.');
            <?php endif; ?>

            const orderData = {
                customer_name: formData.get('customer_name'),
                customer_phone: formData.get('customer_phone'),
                customer_email: formData.get('customer_email'),
                customer_address: formData.get('customer_address'),
                customer_city: formData.get('customer_city'),
                customer_state: formData.get('customer_state'),
                customer_postcode: formData.get('customer_postcode'),
                items: items,
                payment_method: selectedPayment.value,
                utm_source: new URLSearchParams(window.location.search).get('utm_source'),
                utm_medium: new URLSearchParams(window.location.search).get('utm_medium'),
                utm_campaign: new URLSearchParams(window.location.search).get('utm_campaign'),
                utm_content: new URLSearchParams(window.location.search).get('utm_content'),
            };

            // Show loading
            document.getElementById('loading-overlay').classList.remove('hidden');

            // Submit order
            fetch('<?php echo e(route("sales-page.submit-order", $salesPage->slug)); ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: JSON.stringify(orderData)
            })
            .then(response => {
                if (!response.ok) {
                    // Try to parse error message from response
                    return response.json().then(data => {
                        throw new Error(data.message || 'Server error occurred');
                    }).catch(() => {
                        throw new Error('Server error occurred. Please try again.');
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    if (data.redirect_url) {
                        // For FPX/DuitNow - redirect to payment gateway
                        window.location.href = data.redirect_url;
                    } else if (data.order_id) {
                        // For COD - redirect to thank you page
                        window.location.href = '<?php echo e(route("sales-page.thank-you")); ?>?order=' + data.order_id;
                    }
                } else {
                    document.getElementById('loading-overlay').classList.add('hidden');
                    alert('Error: ' + (data.message || 'An error occurred'));
                }
            })
            .catch(error => {
                document.getElementById('loading-overlay').classList.add('hidden');
                console.error('Error:', error);
                alert('Error: ' + error.message);
            });
        });

        // Hide loading overlay when user navigates back from payment gateway
        window.addEventListener('pageshow', function(event) {
            // Hide loading overlay if page is loaded from cache (back button)
            if (event.persisted || (window.performance && window.performance.navigation.type === 2)) {
                document.getElementById('loading-overlay').classList.add('hidden');
            }
        });

        // Also hide on page load
        window.addEventListener('load', function() {
            document.getElementById('loading-overlay').classList.add('hidden');
        });

        // Image optimization on page load
        document.addEventListener('DOMContentLoaded', function() {
            const contentImages = document.querySelectorAll('.content-wrapper img');

            contentImages.forEach((img, index) => {
                // Add alt attribute if missing
                if (!img.hasAttribute('alt')) {
                    img.setAttribute('alt', '<?php echo e($salesPage->name); ?>');
                }

                // Set loading attribute
                if (index === 0) {
                    // First image: high priority, no lazy load
                    img.setAttribute('fetchpriority', 'high');
                    img.setAttribute('loading', 'eager');
                } else {
                    // Other images: lazy load
                    img.setAttribute('loading', 'lazy');
                }

                // Add width and height attributes to prevent layout shift
                if (img.naturalWidth && img.naturalHeight) {
                    if (!img.hasAttribute('width')) {
                        img.setAttribute('width', img.naturalWidth);
                    }
                    if (!img.hasAttribute('height')) {
                        img.setAttribute('height', img.naturalHeight);
                    }
                } else {
                    // Wait for image to load then set dimensions
                    img.addEventListener('load', function() {
                        if (!this.hasAttribute('width')) {
                            this.setAttribute('width', this.naturalWidth);
                        }
                        if (!this.hasAttribute('height')) {
                            this.setAttribute('height', this.naturalHeight);
                        }
                    });
                }
            });
        });

        // FAQ Accordion Toggle
        function toggleFaq(index) {
            const answer = document.getElementById('faq-answer-' + index);
            const icon = document.getElementById('faq-icon-' + index);

            if (answer.classList.contains('hidden')) {
                // Open this FAQ
                answer.classList.remove('hidden');
                icon.style.transform = 'rotate(45deg)'; // Plus to X
            } else {
                // Close this FAQ
                answer.classList.add('hidden');
                icon.style.transform = 'rotate(0deg)'; // X to Plus
            }
        }

        // ========================================
        // LITE YOUTUBE EMBED - Lazy Load Videos
        // ========================================

        /**
         * Fetch YouTube video title using oEmbed API
         */
        async function fetchYouTubeTitle(videoId) {
            try {
                const response = await fetch(`https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${videoId}&format=json`);
                if (!response.ok) throw new Error('Failed to fetch title');
                const data = await response.json();
                return data.title || null;
            } catch (error) {
                console.warn(`Could not fetch title for video ${videoId}:`, error);
                return null;
            }
        }

        /**
         * Initialize all YouTube embeds on the page
         * This replaces heavy iframes with lightweight thumbnails
         * Videos load only when clicked (saves ~500KB per video!)
         */
        async function initLiteYouTube() {
            // Find all lite-youtube elements
            const liteYoutubeElements = document.querySelectorAll('.lite-youtube');

            for (const element of liteYoutubeElements) {
                const videoId = element.dataset.id;

                if (!videoId) {
                    console.warn('Lite YouTube element missing data-id attribute:', element);
                    continue;
                }

                // Wrap the video element if not already wrapped
                let wrapper = element.parentElement;
                if (!wrapper.classList.contains('lite-youtube-wrapper')) {
                    wrapper = document.createElement('div');
                    wrapper.className = 'lite-youtube-wrapper';
                    element.parentNode.insertBefore(wrapper, element);
                    wrapper.appendChild(element);
                }

                // Fetch and add video title (unless disabled via data-no-title attribute)
                if (!element.dataset.noTitle) {
                    const title = await fetchYouTubeTitle(videoId);
                    if (title) {
                        // Check if title already exists
                        let titleElement = wrapper.querySelector('.lite-youtube-title');
                        if (!titleElement) {
                            titleElement = document.createElement('h2');
                            titleElement.className = 'lite-youtube-title';
                            titleElement.textContent = title;
                            wrapper.insertBefore(titleElement, element);
                        }
                    }
                }

                // Set thumbnail as background
                // Use custom thumbnail if provided, otherwise use YouTube default
                const customThumbnail = element.dataset.thumbnail;

                if (customThumbnail) {
                    // Custom thumbnail provided - use it
                    element.style.backgroundImage = `url(${customThumbnail})`;
                } else {
                    // No custom thumbnail - fallback to YouTube default thumbnails
                    // Try multiple thumbnail qualities for best result with Shorts
                    element.style.backgroundImage = `url(https://i.ytimg.com/vi/${videoId}/maxresdefault.jpg), url(https://i.ytimg.com/vi/${videoId}/sddefault.jpg), url(https://i.ytimg.com/vi/${videoId}/hqdefault.jpg)`;
                }

                // Add click handler to load actual video
                element.addEventListener('click', function() {
                    // Create iframe
                    const iframe = document.createElement('iframe');
                    iframe.setAttribute('src', `https://www.youtube.com/embed/${videoId}?autoplay=1&rel=0`);
                    iframe.setAttribute('frameborder', '0');
                    iframe.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture');
                    iframe.setAttribute('allowfullscreen', '');
                    iframe.setAttribute('title', 'YouTube video player');

                    // Replace thumbnail with iframe
                    element.innerHTML = '';
                    element.appendChild(iframe);

                    // Track video click event
                    logTrackingEvent('Video', 'Play', { videoId: videoId });

                    // Facebook Pixel tracking
                    <?php if($salesPage->facebook_pixel_id): ?>
                    if (typeof fbq !== 'undefined') {
                        fbq('track', 'ViewContent', {
                            content_name: 'Video Play',
                            content_type: 'video',
                            content_ids: [videoId]
                        });
                    }
                    <?php endif; ?>

                    // TikTok Pixel tracking
                    <?php if($salesPage->tiktok_pixel_id): ?>
                    if (typeof ttq !== 'undefined') {
                        ttq.track('ViewContent', {
                            content_type: 'video',
                            content_id: videoId
                        });
                    }
                    <?php endif; ?>

                    // Google Analytics tracking
                    <?php if($salesPage->google_analytics_id): ?>
                    if (typeof gtag !== 'undefined') {
                        gtag('event', 'video_play', {
                            'video_id': videoId,
                            'video_title': 'Sales Page Video'
                        });
                    }
                    <?php endif; ?>
                }, { once: true }); // Only fire once per element
            }

            console.log(`🎬 Lite YouTube: Initialized ${liteYoutubeElements.length} video(s)`);
        }

        // Initialize on page load
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initLiteYouTube);
        } else {
            initLiteYouTube();
        }
    </script>
</body>
</html>
<?php /**PATH C:\laragon\www\multistore\resources\views/sales-pages/public/show.blade.php ENDPATH**/ ?>