<?php

if (session_status() !== PHP_SESSION_ACTIVE) {

    session_start();

}

// SET DEFAULT LANGUAGE & CURRENCY ON FIRST VISIT
if (!isset($_SESSION['selected_language'])) {
  $_SESSION['selected_language'] = 'eng';
}
if (!isset($_SESSION['selected_currency'])) {
  $_SESSION['selected_currency'] = 'usd';
}

// Load ImageHandler

require_once __DIR__ . '/config/image_config.php';

// Load Currency Converter
require_once __DIR__ . '/config/currency_converter.php';

// Load Translation Helper for language support
require_once __DIR__ . '/config/translation_helper.php';

// Load Google Translate API for full page translation
require_once __DIR__ . '/config/google_translate_api.php';

// Start buffering for translation
// Temporarily disabled - was causing issues
// startTranslationBuffer();



// Load Meta Manager for proper titles

require_once __DIR__ . '/helpers/meta_manager.php';



// Load Phase 3 helpers early for meta tag optimization

require_once __DIR__ . '/helpers/keyword_optimizer.php';

require_once __DIR__ . '/helpers/faq_helper.php';

require_once __DIR__ . '/helpers/content_optimizer.php';




// Load marquee settings

$marqueeFile = __DIR__ . '/data/marquee.json';

$marquee = [];

if (file_exists($marqueeFile)) {

    $marquee = json_decode(file_get_contents($marqueeFile), true) ?: [];

}



// Load carousel settings

$carouselFile = __DIR__ . '/data/carousel.json';

$carousel = [];

if (file_exists($carouselFile)) {

    $carousel = json_decode(file_get_contents($carouselFile), true) ?: [];

}



// Load latest products settings

$latestProductsFile = __DIR__ . '/data/latest_products.json';

$latestProducts = [];

if (file_exists($latestProductsFile)) {

    $latestProducts = json_decode(file_get_contents($latestProductsFile), true) ?: [];

}



// Load video section settings

$videoSectionFile = __DIR__ . '/data/video_section.json';

$videoSection = [];

if (file_exists($videoSectionFile)) {

    $videoSection = json_decode(file_get_contents($videoSectionFile), true) ?: [];

}

?>

<!DOCTYPE html>

<html lang="<?php echo defined('HTML_LANG') ? HTML_LANG : 'en'; ?>">

<head>

        <meta charset="UTF-8">

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <meta http-equiv="X-UA-Compatible" content="ie=edge">

        

        <!-- Meta Tags - Using Meta Manager for consistency -->

        <?php echo renderMetaTags('home'); ?>

        

        <!-- Robots Meta -->

        <meta name="robots" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1">

        

        <link rel="stylesheet" href="styles.css">
       <link rel="stylesheet" href="responsive.css">
    
    <!-- Viewport meta tag (essential!) -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="icon" href="sport-pics/logo-1.png?v=<?php echo time(); ?>" type="image/png">

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css" integrity="sha512-2SwdPD6INVrV/lHTZbO2nodKhrnDdJK9/kg2XD1r9uGqPo1cUbujc+IYdlYdEErWNu69gVcYgdxlmVmzTWnetw==" crossorigin="anonymous" referrerpolicy="no-referrer" />

        <meta name="theme-color" content="#ffffff">

        <style>

            @keyframes scroll-left-marquee {

              0% { transform: translateX(0); }

              100% { transform: translateX(-100%); }

            }

            

            /* Featured Category Card Hover Effects */

            .featured-category-card {

                position: relative;

                overflow: hidden;

            }

            

            .featured-category-card:hover .featured-category-arrow {

                opacity: 1 !important;

            }

            

            .featured-category-card:hover .featured-category-overlay {

                background: rgba(0, 0, 0, 0.2) !important;

            }

            

            .featured-category-arrow {

                transition: opacity 0.3s ease, transform 0.3s ease, background 0.3s ease !important;

                width: 80px !important;

                height: 80px !important;

                background: #ffffff !important;

                border-radius: 50% !important;

                display: flex !important;

                align-items: center !important;

                justify-content: center !important;

                box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15) !important;

            }

            

            .featured-category-arrow i {

                color: #333 !important;

                font-size: 32px !important;

                text-shadow: none !important;

            }

            

            .featured-category-arrow:hover {

                transform: translate(-50%, -50%) scale(1.1) !important;

                box-shadow: 0 6px 24px rgba(0, 0, 0, 0.2) !important;

            }

        </style>

</head>

<body>



<script>

// Switch product image on quick color swatch click - DEFINED EARLY FOR HOME PAGE

function switchQuickProductImage(event, colorImage, mainImage) {

  if (event) {

    event.preventDefault();

    event.stopPropagation();

  }

  

  const btn = event.target;

  console.log('Button clicked:', btn, 'colorImage:', colorImage, 'mainImage:', mainImage);

  

  const productWrapper = btn.closest('.product-display-wrapper');

  console.log('Found wrapper:', productWrapper ? 'YES' : 'NO');

  

  if (!productWrapper) {

    console.log('ERROR: Could not find product wrapper');

    return;

  }

  

  const productImage = productWrapper.querySelector('.product-card-with-actions img');

  console.log('Found image:', productImage ? 'YES' : 'NO');

  

  if (!productImage) {

    console.log('ERROR: Could not find product image');

    return;

  }

  

  // Get image from data attributes if available (more reliable)

  if (!colorImage && btn.dataset && btn.dataset.colorImage) {

    colorImage = btn.dataset.colorImage;

  }

  if (!mainImage && btn.dataset && btn.dataset.mainImage) {

    mainImage = btn.dataset.mainImage;

  }

  

  let imageToShow = (colorImage && colorImage.trim() && colorImage !== 'undefined' && colorImage !== 'null' && colorImage !== '') ? colorImage : mainImage;

  console.log('Changing image to:', imageToShow);

  

  if (imageToShow) {

    productImage.src = imageToShow;

    productImage.alt = productImage.alt || 'Product';

    

    const allSwatches = productWrapper.querySelectorAll('.quick-color-swatch');

    allSwatches.forEach(swatch => {

      swatch.style.borderColor = '#ddd';

      swatch.style.borderWidth = '2px';

    });

    btn.style.borderColor = '#F07E2D';

    btn.style.borderWidth = '3px';

    

    console.log('Image switched successfully');

  } else {

    console.error('No valid image to show');

  }

}

</script>



<?php include __DIR__ . '/header.php'; ?>



<!-- Full-width hero/slider placed outside the centered container so it spans the viewport -->

<!-- <section class="hero">

    <div class="slider">

        <div class="slide active">

            <img src="pics_ecom/p1.png" alt="Slide 1" />

        </div>

        <div class="slide">

            <img src="pics_ecom/p2.png" alt="Slide 2" />

        </div>

        <div class="slide">

            <img src="pics_ecom/p3.png" alt="Slide 3" />

        </div>

        <button class="slider-arrow prev" onclick="changeSlide(-1)">&#10094;</button>

        <button class="slider-arrow next" onclick="changeSlide(1)">&#10095;</button>

    </div>

    <div class="hero-content">

        <h1>Modern Women Fashion</h1>

        <p>Fresh seasonal arrivals — curated styles for every moment.</p>

        <a class="btn" href="shop.php">Shop Collection</a>

    </div>

</section> -->

<?php

$sliderFile = __DIR__ . '/data/slider.json';

$slider = file_exists($sliderFile) ? json_decode(file_get_contents($sliderFile), true) : [];

?>



<section class="hero">

    <div class="slider">

        <?php foreach ($slider['slides'] as $i => $s): ?>

            <div class="slide <?php echo $i === 0 ? 'active' : ''; ?>">

                <img src="<?php echo htmlspecialchars($s['image']); ?>" alt="<?php echo htmlspecialchars($s['alt']); ?>" />

                <div class="hero-content" style="<?php 

                    $position = $slider['hero']['position'] ?? 'left';

                    $left = $position === 'left' ? '30%' : 'auto';

                    $right = $position === 'right' ? '%' : 'auto';

                    echo "left:$left; right:$right;";

                ?>">

                    <h1 style="<?php echo ($slider['hero']['bold_title'] ?? true) ? 'font-weight:700;' : 'font-weight:400;'; ?>"><?php echo htmlspecialchars($slider['hero']['title']); ?></h1>

                    <p><?php echo htmlspecialchars($slider['hero']['subtitle']); ?></p>

                    <a class="btn" href="<?php echo htmlspecialchars($slider['hero']['button_link']); ?>">

                        <?php echo htmlspecialchars($slider['hero']['button_text']); ?>

                    </a>

                </div>

            </div>

        <?php endforeach; ?>

        <button class="slider-arrow prev" onclick="changeSlide(-1)">&#10094;</button>

        <button class="slider-arrow next" onclick="changeSlide(1)">&#10095;</button>

        

        <!-- Optional Dot Indicators -->

        <div class="slider-dots" id="sliderDots">

            <?php foreach ($slider['slides'] as $i => $s): ?>

                <div class="slider-dot <?php echo $i === 0 ? 'active' : ''; ?>" onclick="goToSlide(<?php echo $i; ?>)" title="Slide <?php echo $i + 1; ?>"></div>

            <?php endforeach; ?>

        </div>

    </div>

</section>



<?php 

// Display marquee if enabled (below the slider)

if (!empty($marquee['enabled']) && !empty($marquee['text'])): 

    $speed = isset($marquee['speed']) ? $marquee['speed'] : '30s';

?>

<div style="background:<?php echo htmlspecialchars($marquee['background_color']); ?>; width:100%; height:5% overflow:hidden; padding:16px 0;">

    <div style="font-size:<?php echo htmlspecialchars($marquee['font_size']); ?>; color:<?php echo htmlspecialchars($marquee['text_color']); ?>; font-weight:600; white-space:nowrap; animation: scroll-left-marquee <?php echo htmlspecialchars($speed); ?> linear infinite; padding:0 20px; display:inline-block; min-width:100%;">

        <?php echo htmlspecialchars($marquee['text']); ?>

    </div>

</div>

<?php endif; ?>



<!-- Info Cards Section -->

<?php

$homepageSections = [];

$homepageSectionsFile = __DIR__ . '/data/homepage_sections.json';

if (file_exists($homepageSectionsFile)) {

    $homepageSections = json_decode(file_get_contents($homepageSectionsFile), true) ?: [];

}

$infoCards = $homepageSections['info_cards'] ?? [];

?>

<div style="max-width:1320px; margin:60px auto 0; padding:0 20px;">

    <div style="display:grid; grid-template-columns:repeat(3, 1fr); gap:60px; padding:60px 0;">

        <?php foreach ($infoCards as $card): ?>

        <div class="info-card" style="display:flex; gap:24px; align-items:flex-start;">

            <div class="info-icon" style="font-size:56px; flex-shrink:0; color:#333; transition:all 0.3s ease; width:56px; height:56px; display:flex; align-items:center; justify-content:center;">

                <?php 

                // Map icon text to SVG icons

                $iconMap = [

                    '🚚' => '<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="1" y1="1" x2="1" y2="15"></line><polyline points="1 15 1 23 3 21 21 21 23 23 23 15"></polyline><polyline points="23 1 23 15 1 15"></polyline><line x1="10" y1="5" x2="10" y2="12"></line><line x1="15" y1="5" x2="15" y2="12"></line><circle cx="4.5" cy="17.5" r="2.5"></circle><circle cx="19.5" cy="17.5" r="2.5"></circle></svg>',

                    '📞' => '<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path></svg>',

                    '🔒' => '<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path><circle cx="12" cy="16" r="1"></circle></svg>',

                ];

                

                // Get icon from map or use emoji

                $icon = $card['icon'] ?? '🚚';

                if (isset($iconMap[$icon])) {

                    echo $iconMap[$icon];

                } else {

                    echo htmlspecialchars($icon);

                }

                ?>

            </div>

            <div style="flex:1;">

                <h3 style="font-size:18px; margin:0 0 8px 0; color:#333; font-weight:600; line-height:1.3;">

                    <?php echo htmlspecialchars($card['title']); ?>

                </h3>

                <p style="color:#666; font-size:14px; margin:0; line-height:1.6;">

                    <?php echo htmlspecialchars($card['description']); ?>

                </p>

            </div>

        </div>

        <?php endforeach; ?>

    </div>

</div>



<!-- Featured Categories Section -->

<?php

$featuredCategories = $homepageSections['featured_categories'] ?? [];

?>

<div  class= "mfc" style="max-width:1100px; margin:30px; padding:0 30px; text-align:center;">

    <!-- SEO: Main Page Heading -->

    <?php echo h1('Welcome to Esa\'s Fashion', 'homepage-title'); ?>

    

    <p style="text-align:center; margin-bottom:20px; font-size:16px; color:#666;">Shops the latest trends and timeless classics</p>

    

    <!-- Secondary Section Heading -->

    <?php echo h2('Discover Our Collections'); ?>

    <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(467px, 1fr)); column-gap:100px; justify-items:center;">

        <?php foreach (array_slice($featuredCategories, 0, 2) as $cat): 

            $categorySlug = !empty($cat['category_id']) ? 'category.php?id=' . $cat['category_id'] : 'shop.php';

            $categoryUrl = $categorySlug;

            $imageUrl = getImageForSection($cat['image'], 'featured_category');

        ?>

        <div style="display:flex; flex-direction:column; width:100%; max-width:550px;">

            <div class="featured-category-card" style="position:relative; border-radius:0px; overflow:hidden; width:550px; height:700px; background:#f0f0f0; margin-bottom:20px;">

                <!-- SEO: Image with proper alt text -->

                <img src="<?php echo htmlspecialchars($imageUrl); ?>" alt="<?php echo ImageAltHelper::generateCategoryAlt($cat['name']); ?>" style="width:100%; height:100%; object-fit:cover; transition:all 0.3s ease;">

                

                <!-- Arrow Button Overlay -->

                <a href="<?php echo htmlspecialchars($categoryUrl); ?>" class="featured-category-arrow" style="position:absolute; top:50%; left:50%; transform:translate(-50%, -50%); opacity:0; z-index:10;">

                    <i class="fa-solid fa-arrow-right"></i>

                </a>

                

                <!-- Overlay Background on Hover -->

                <div class="featured-category-overlay" style="position:absolute; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0); transition:background 0.3s ease; z-index:5;"></div>

            </div>

           

            <div style="padding:0px; text-align:center;">

                <h3 style="font-size:20px; margin:0 0 10px 0; text-align:center; color:#333; font-weight:600;">

                    <?php echo htmlspecialchars($cat['name']); ?>

                </h3>

                <p style="font-size:14px; margin:0 0 16px 0; text-align:center; color:#666; line-height:1.5;">

                    <?php echo htmlspecialchars($cat['description']); ?>

                </p>

                <a href="<?php echo htmlspecialchars($categoryUrl); ?>" class="btn" style="background:#F07E2D; align-item:center; color:#fff; padding:10px 20px; text-decoration:none; border-radius:4px; display:inline-block;">Shop Now</a>

            </div>

        </div>

        <?php endforeach; ?>

    </div>

</div>
<!-- Admin Add banner Section -->
<?php 
if (file_exists("news_slider.php")) {
    include("news_slider.php");
} 
?>


<!-- Featured Products Section -->

<section class="featured" style="text-align:center; max-width:1320px; margin-top:20px; padding:0 20px;">
<!-- margin:0 auto 80px;  -->
 

    <?php echo h2('Featured Products'); ?>

    <p style="text-align:center; font-size:14px; color:#666; margin-bottom:40px;">Discover our handpicked selection of best-selling items</p>

        <div class="product-grid">

            <?php

            // Load and display featured products

            $productsFile = __DIR__ . '/data/products.json';

            $products = [];

            if (file_exists($productsFile)) {

                $prods = @json_decode(file_get_contents($productsFile), true);

                if (is_array($prods)) {

                    // Filter for featured products only

                    $featuredProducts = array_filter($prods, function($p) {

                        return !empty($p['featured']);

                    });

                    // Show all featured products (no limit)

                    $products = array_values($featuredProducts);

                    

                    // If no featured products marked, show first 4 as fallback

                    if (empty($products)) {

                        $products = array_slice($prods, 0, 4);

                    }

                }

            }



            if (!empty($products)) {

                foreach ($products as $prod) {

                    $productTitle = htmlspecialchars($prod['title'] ?? 'Product');

                    $productPrice = htmlspecialchars($prod['price'] ?? '0');

                    $productId = $prod['id'] ?? '';

                    echo '<div class="product-display-wrapper">';

                    

                    // Product Card (Image Only)

                    echo '<div class="featured-product-card product-card-with-actions">';

                    echo '<div class="product-card-image-wrapper">';

                    echo '<a href="product.php?id=' . $productId . '" class="product-image-link">';

                    if (!empty($prod['image'])) {

                        $imageUrl = getImageForSection($prod['image'], 'featured_home');

                        // SEO: Generate alt text with product info

                        $altText = ImageAltHelper::generateProductAlt(

                            $productTitle,

                            $prod['color'] ?? 'Various colors',

                            'Featured'

                        );

                        echo '<img src="' . htmlspecialchars($imageUrl) . '" alt="' . $altText . '">';

                    } else {

                        echo '<img src="pics_ecom/placeholder.png" alt="' . $productTitle . '">';

                    }

                    echo '</a>';

                    echo '<div class="product-quick-actions">';

                    echo '<button type="button" class="quick-action-btn wishlist" onclick="toggleWishlistQuick(' . $productId . ', event)" title="Add to Wishlist"><i class="fa-regular fa-heart"></i></button>';

                    echo '<button type="button" class="quick-action-btn cart" onclick="addToCartQuick(' . $productId . ', event)" title="Add to Cart"><i class="fa-solid fa-basket-shopping"></i></button>';

                    echo '</div>';

                    echo '</div>';

                    echo '</div>';

                    

                    // Product Info Section (Outside Card, Inside Wrapper)

                    echo '<div class="product-info-outside">';

                    

                    // Color swatches

                    if (!empty($prod['colors']) && is_array($prod['colors'])) {

                        echo '<div class="color-swatches-grid" style="gap:6px; margin-bottom:8px;">';

                        foreach (array_slice($prod['colors'], 0, 4) as $idx => $color) {

                            $colorCode = htmlspecialchars($color['code'] ?? '#cccccc');

                            $colorImage = isset($color['image']) ? htmlspecialchars($color['image']) : htmlspecialchars($prod['image']);

                            echo '<button type="button" class="color-swatch quick-color-swatch" style="width: 28px; height: 28px; background-color: ' . $colorCode . '; border:2px solid #ddd; cursor:pointer;" title="' . htmlspecialchars($color['name']) . '" onclick="switchQuickProductImage(event, \'' . $colorImage . '\', \'' . htmlspecialchars($prod['image']) . '\')"></button>';

                        }

                        if (count($prod['colors']) > 4) {

                            echo '<div style="display:flex; align-items:center; font-size:12px; color:#666;">+' . (count($prod['colors']) - 4) . '</div>';

                        }

                        echo '</div>';

                    }

                  

                    echo '<h3 style="margin:12px 0 6px 0; font-size:15px; font-weight:600; color:#333; line-height:1.4;">' . $productTitle . '</h3>';

                    $salePrice = isset($prod['sale_price']) ? (float)$prod['sale_price'] : null;

                    $regularPrice = (float)$productPrice;

                    if ($salePrice !== null && $salePrice < $regularPrice) {

                        echo '<p style="margin:0; font-size:16px; font-weight:700; color:#F07E2D;">' . getPriceDisplay($salePrice) . ' <span style="text-decoration:line-through; color:#999; font-size:14px; font-weight:400; margin-left:8px;">' . getPriceDisplay($regularPrice) . '</span></p>';

                    } else {

                        echo '<p style="margin:0; font-size:16px; font-weight:700; color:#F07E2D;">' . getPriceDisplay($regularPrice) . '</p>';

                    }

                    echo '</div>';

                    

                    echo '</div>';

                }

            } else {

                // Fallback if no products

                echo '<p>No products available</p>';

            }

            ?>

        </div>

    </section>

<!-- Categories Carousel Section -->

<?php

$carouselCategories = $carousel['categories'] ?? [];

$autoplayInterval = $carousel['autoplay_interval'] ?? 3000;

?>

<!-- Category Carousel Section - Admin Managed -->

<?php if ($carousel['enabled'] ?? true): ?>

<section style="margin:0px 0;  background:#ffffff;">

    <div style=" margin:0;">

        <!-- <h2 style="text-align:center; margin-bottom:50px; font-size:28px; font-weight:700;">Browse Categories</h2> -->

        

        <div class="category-carousel-container">

            <button class="category-carousel-btn category-carousel-btn-prev" onclick="categoryCarouselPrev()" type="button">‹</button>

            <div class="category-carousel-wrapper">

                <div class="category-carousel-track" id="categoryCarouselTrack">

                    <?php foreach ($carouselCategories as $cat): ?>

                    <a href="category.php?cat=<?php echo urlencode($cat['name']); ?>" class="category-carousel-card">

                        <div class="category-carousel-image" style="background-image: url('<?php echo htmlspecialchars(getCarouselImageUrl($cat['image'])); ?>'); background-size:cover; background-position:center;">

                            <div class="category-carousel-label" style="background:transparent;">

                                <h3 ><?php echo htmlspecialchars($cat['name']); ?></h3>

                                <span class="category-carousel-arrow">→</span>

                            </div>

                        </div>

                    </a>

                    <?php endforeach; ?>

                </div>

            </div>

            <button class="category-carousel-btn category-carousel-btn-next" onclick="categoryCarouselNext()" type="button">›</button>

        </div>

    </div>

</section>

<?php endif; ?>

<!-- 

<main class="container"  style = "margin: 0px;"> -->



    <!-- <section class="categories">

        <h2>Shop by Category</h2>

        <div class="cat-grid">

            ?php

            // Load categories dynamically from JSON

            $categories = [];

            $categoriesFile = __DIR__ . '/data/categories.json';

            if (file_exists($categoriesFile)) {

                $cats = @json_decode(file_get_contents($categoriesFile), true);

                if (is_array($cats)) $categories = $cats;

            }

            

            foreach ($categories as $cat) {

                echo '<a class="cat-card" href="category.php?cat=' . htmlspecialchars($cat['name']) . '">' . htmlspecialchars($cat['name']) . '</a>';

            }

            ?>

        </div>

    </section> -->



    <!-- <section class="featured">

        <h2>Featured</h2>

        <div class="product-grid">

            ?php

            // Load and display featured products

            $productsFile = __DIR__ . '/data/products.json';

            $products = [];

            if (file_exists($productsFile)) {

                $prods = @json_decode(file_get_contents($productsFile), true);

                if (is_array($prods)) {

                    // Filter for featured products only

                    $featuredProducts = array_filter($prods, function($p) {

                        return !empty($p['featured']);

                    });

                    // Show all featured products (no limit)

                    $products = array_values($featuredProducts);

                    

                    // If no featured products marked, show first 4 as fallback

                    if (empty($products)) {

                        $products = array_slice($prods, 0, 4);

                    }

                }

            }

            

            if (!empty($products)) {

                foreach ($products as $prod) {

                    $productImage = !empty($prod['image']) ? htmlspecialchars($prod['image']) : 'pics_ecom/placeholder.png';

                    $productTitle = htmlspecialchars($prod['title'] ?? 'Product');

                    $productPrice = htmlspecialchars($prod['price'] ?? '0');

                    $productId = $prod['id'] ?? '';

                    echo '<a href="product.php?id=' . $productId . '" class="product">';

                    echo '<img src="' . $productImage . '" alt="' . $productTitle . '">';

                    echo '<h3>' . $productTitle . '</h3>';

                    echo '<p class="price">' . getPriceDisplay((float)$productPrice) . '</p>';

                    echo '</a>';

                }

            } else {

                // Fallback if no products

                echo '<p>No products available</p>';

            }

            ?>

        </div>

    </section> -->



    <!-- Latest Products Section -->

    <?php if ($latestProducts['enabled'] ?? true): ?>

    <section class="latest-products" style="margin:25px; width:100%; text-align:center; max-width:1320px; padding:0 20px;">

        <div class="section-header" style="margin-bottom:60px;">

            <p style="text-transform:uppercase; font-size:14px; letter-spacing:3px; color:#999; margin-bottom:16px; font-weight:500;">NEW ARRIVALS</p>

            <h2 style="text-align:center; font-size:42px; font-weight:700; margin:0; color:#333; line-height:1.2;">Latest Products</h2>

        </div>



        <div class="product-grid">

            <?php

            $productsFile = __DIR__ . '/data/products.json';

            $latestProds = [];

            if (file_exists($productsFile)) {

                $allProds = @json_decode(file_get_contents($productsFile), true);

                if (is_array($allProds)) {

                    $prodIds = $latestProducts['product_ids'] ?? [1, 2, 3, 4, 5, 6];

                    $displayCount = min($latestProducts['display_count'] ?? 6, count($prodIds));

                    

                    // Get products by specified IDs

                    foreach ($prodIds as $id) {

                        foreach ($allProds as $prod) {

                            if ($prod['id'] == $id) {

                                $latestProds[] = $prod;

                                break;

                            }

                        }

                        if (count($latestProds) >= $displayCount) break;

                    }

                }

            }

            

            if (!empty($latestProds)) {

                foreach ($latestProds as $prod) {

                    $productTitle = htmlspecialchars($prod['title'] ?? 'Product');

                    $productPrice = htmlspecialchars($prod['price'] ?? '0');

                    $productId = $prod['id'] ?? '';

                    

                    echo '<div class="product-display-wrapper">';

                    

                    // Product Card (Image Only)

                    echo '<div class="latest-product-card product-card-with-actions">';

                    echo '<div class="product-card-image-wrapper">';

                    echo '<a href="product.php?id=' . $productId . '" class="product-image-link">';

                    if (!empty($prod['image'])) {

                        $imageUrl = getImageForSection($prod['image'], 'latest_home');

                        echo '<img src="' . htmlspecialchars($imageUrl) . '" alt="' . $productTitle . '">';

                    } else {

                        echo '<img src="pics_ecom/placeholder.png" alt="' . $productTitle . '">';

                    }

                    echo '</a>';

                    echo '<div class="product-quick-actions">';

                    echo '<button type="button" class="quick-action-btn wishlist" onclick="toggleWishlistQuick(' . $productId . ', event)" title="Add to Wishlist"><i class="fa-regular fa-heart"></i></button>';

                    echo '<button type="button" class="quick-action-btn cart" onclick="addToCartQuick(' . $productId . ', event)" title="Add to Cart"><i class="fa-solid fa-basket-shopping"></i></button>';

                    echo '</div>';

                    echo '</div>';

                    echo '</div>';

                    

                    // Product Info  Section (Outside Card, Inside Wrapper)

                    echo '<div class="product-info-outside" >';

                    // style="justify-content:center;"

                    

                    // Color swatches

                    if (!empty($prod['colors']) && is_array($prod['colors'])) {

                        echo '<div class="color-swatches-grid" style="gap:6px; margin-bottom:8px;">';

                        foreach (array_slice($prod['colors'], 0, 4) as $idx => $color) {

                            $colorCode = htmlspecialchars($color['code'] ?? '#cccccc');

                            $colorImage = isset($color['image']) ? htmlspecialchars($color['image']) : htmlspecialchars($prod['image']);

                            echo '<button type="button" class="color-swatch quick-color-swatch" style="width: 28px; height: 28px; background-color: ' 

                            . $colorCode . '; border:2px solid #ddd; cursor:pointer;" 

                            title="' . htmlspecialchars($color['name'])

                            . '" onclick="switchQuickProductImage(event, \'' 

                            . $colorImage . '\', \'' . htmlspecialchars($prod['image']) . '\')"></button>';

                        }

                        if (count($prod['colors']) > 4) {

                            echo '<div style="display:flex; align-items:center; font-size:12px; color:#666;">+' . (count($prod['colors']) - 4) . '</div>';

                        }

                        echo '</div>';

                    }

                    

                    echo '<h3 style="margin:12px 0 6px 0; font-size:15px; font-weight:600; color:#333; line-height:1.4;">' . $productTitle . '</h3>';

                    $salePrice = isset($prod['sale_price']) ? (float)$prod['sale_price'] : null;

                    $regularPrice = (float)$productPrice;

                    if ($salePrice !== null && $salePrice < $regularPrice) {

                        echo '<p style="margin:0; font-size:16px; font-weight:700; color:#F07E2D;">' . getPriceDisplay($salePrice) . ' <span style="text-decoration:line-through; color:#999; font-size:14px; font-weight:400; margin-left:8px;">' . getPriceDisplay($regularPrice) . '</span></p>';

                    } else {

                        echo '<p style="margin:0; font-size:16px; font-weight:700; color:#F07E2D;">' . getPriceDisplay($regularPrice) . '</p>';

                    }

                    echo '</div>';

                    

                    echo '</div>';

                }

            }

            ?>

        </div>

    </section>

    <?php endif; ?>



    <!-- Video Section -->

    <?php if ($videoSection['enabled'] ?? true): ?>

    <section class="video-section"

     style="margin:0px auto; padding:0; width:100%;">

      <!-- max-width:1100px;  -->

        </div>


        <!-- Home News Section (admin-managed) -->
        <!-- <?php
        // Load products early so sales item can reference an existing product
        $productsFile = __DIR__ . '/data/products.json';
        $products = [];
        if (file_exists($productsFile)) {
          $tmp = @json_decode(file_get_contents($productsFile), true);
          if (is_array($tmp)) $products = $tmp;
        }

        $newsFile = __DIR__ . '/data/news.json';
        $news = [];
        if (file_exists($newsFile)) {
          $news = @json_decode(file_get_contents($newsFile), true) ?: [];
        }
        // Prefer DB-backed model when available (db_config + lib/news_model.php)
        $modelPath = __DIR__ . '/lib/news_model.php';
        if (file_exists($modelPath)) {
          include_once $modelPath;
          if (class_exists('NewsModel')) {
            try { $nm = new NewsModel(); $mnews = $nm->all(); if (is_array($mnews)) $news = $mnews; } catch (Exception $e) { /* ignore */ }
          }
        }
        // Normalize arrays
        if (!isset($news['items']) || !is_array($news['items'])) $news['items'] = [];
        if (!isset($news['sales_item']) || !is_array($news['sales_item'])) $news['sales_item'] = [];
        // Ensure at least 4 slides for visual appearance by repeating items if necessary
        if (!empty($news['items']) && count($news['items']) < 4) {
          $orig = $news['items']; $i = 0;
          while (count($news['items']) < 4) { $news['items'][] = $orig[$i % count($orig)]; $i++; }
        }
        // Show news section when there are news items or a sales item configured
        $hasNewsItems = !empty($news['items']);
        $hasSalesItem = !empty($news['sales_item']);
        if ($hasNewsItems || $hasSalesItem):
        ?>
        <section class="home-news"  style="max-width:1320px; color: #F07E2D; margin:40px; padding:0 20px;">
          <div style="display:grid; grid-template-columns:1fr 1fr; gap:24px; align-items:start;">
            <div class="sales-item">
              <?php if ($hasSalesItem):
                $s = $news['sales_item'];
                // If sales_item references a product id, resolve it
                if (!empty($s['product_id'])) {
                    $found = null;
                    foreach ($products as $pp) {
                        if ((string)($pp['id'] ?? '') === (string)$s['product_id']) { $found = $pp; break; }
                    }
                    if ($found) {
                        $s['title'] = $found['title'] ?? ($s['title'] ?? '');
                        $s['image'] = $found['image'] ?? ($s['image'] ?? '');
                        $s['link'] = 'product.php?id=' . urlencode($found['id']);
                        $s['price'] = $found['price'] ?? ($s['price'] ?? '');
                        $s['description'] = $found['description'] ?? ($s['description'] ?? '');
                    }
                }
              ?>
                <a href="<?php echo htmlspecialchars($s['link'] ?? '#'); ?>" style="display:block; text-decoration:none; color:inherit;">
                  <div style="background:#fff; border:1px solid #eee; padding:16px;">
                    <?php if (!empty($s['image'])): ?><img src="<?php echo htmlspecialchars($s['image']); ?>" alt="<?php echo htmlspecialchars($s['title'] ?? 'Sale'); ?>" style="width:100%; height:auto; object-fit:cover;"><?php endif; ?>
                    <h3 style="margin:12px 0 6px;"><?php echo htmlspecialchars($s['title'] ?? 'Sale'); ?></h3>
                    <?php if (!empty($s['price'])): ?><p style="color:#F07E2D; font-weight:700;"><?php echo htmlspecialchars($s['price']); ?></p><?php endif; ?>
                    <p style="color:#666;"><?php echo htmlspecialchars($s['description'] ?? ''); ?></p>
                  </div>
                </a>
              <?php else:
                if (!empty($products) && !empty($products[0])) {
                  $p = $products[0];
                  $img = !empty($p['image']) ? $p['image'] : 'pics_ecom/placeholder.png';
              ?>
                  <a href="product.php?id=<?php echo urlencode($p['id']); ?>">
                    <div style="background:#fff; border:1px solid #eee; padding:16px;">
                      <img src="<?php echo htmlspecialchars($img); ?>" alt="<?php echo htmlspecialchars($p['title'] ?? 'Product'); ?>" style="width:100%; height:auto; object-fit:cover;">
                      <h3 style="margin:12px 0 6px;"><?php echo htmlspecialchars($p['title'] ?? 'Product'); ?></h3>
                      <p style="color:#F07E2D; font-weight:700;"><?php echo getPriceDisplay((float)($p['price'] ?? 0)); ?></p>
                    </div>
                  </a>
              <?php }
              endif; ?>
            </div>

            <div class="news-list">
              <?php if (!empty($news['items'])): ?>
                <link rel="stylesheet" href="css/news.css">
                <div class="news-slider" id="newsSlider">
                  <div class="news-track" id="newsTrack">
                    <?php foreach ($news['items'] as $item): ?>
                      <div class="news-slide">
                        <div class="news-card">
                          <?php if (!empty($item['image'])): ?><img src="<?php echo htmlspecialchars($item['image']); ?>" alt="">
                          <?php endif; ?>
                          <div class="meta">
                            <div style="display:flex;align-items:center;">
                              <h4 style="margin:0; font-size:16px;"><?php echo htmlspecialchars($item['title']); ?></h4>
                              <?php if (!empty($item['highlight'])): ?><span class="news-badge">Sales Highlight</span><?php endif; ?>
                            </div>
                            <p style="color:#666; margin:8px 0;"><?php echo nl2br(htmlspecialchars($item['content'])); ?></p>
                            <?php if (!empty($item['link'])): ?><a href="<?php echo htmlspecialchars($item['link']); ?>">Read more</a><?php endif; ?>
                            <div style="color:#999;font-size:12px;margin-top:8px;"><?php echo !empty($item['date']) ? date('F j, Y', (int)$item['date']) : ''; ?></div>
                          </div>
                        </div>
                      </div>
                    <?php endforeach; ?>
                  </div>
                  <div class="news-controls">
                    <button id="newsPrev" aria-label="Previous">◀</button>
                    <button id="newsNext" aria-label="Next">▶</button>
                  </div>
                </div>
                <script>
                (function(){
                  var track = document.getElementById('newsTrack');
                  var slides = track ? track.children : [];
                  var idx = 0; var total = slides.length;
                  var prev = document.getElementById('newsPrev');
                  var next = document.getElementById('newsNext');
                  function show(i){ if(!track) return; idx = (i+total)%total; track.style.transform = 'translateX(' + (-idx*100) + '%)'; }
                  if(prev) prev.addEventListener('click', function(){ show(idx-1); resetAuto(); });
                  if(next) next.addEventListener('click', function(){ show(idx+1); resetAuto(); });
                  var auto = setInterval(function(){ show(idx+1); }, 5000);
                  function resetAuto(){ clearInterval(auto); auto = setInterval(function(){ show(idx+1); }, 5000); }
                  // pause on hover
                  var slider = document.getElementById('newsSlider');
                  if(slider){ slider.addEventListener('mouseenter', function(){ clearInterval(auto); }); slider.addEventListener('mouseleave', function(){ resetAuto(); }); }
                  // accessibility: keyboard
                  document.addEventListener('keydown', function(e){ if(e.key==='ArrowLeft') show(idx-1); if(e.key==='ArrowRight') show(idx+1); });
                  // initial
                  show(0);
                })();
                </script>
              <?php else: ?>
                <p>No news items yet.</p>
              <?php endif; ?>
            </div>
          </div>
        </section>
        <?php endif; ?>
 -->

        <!-- Featured Products Section -->

        <section class="featured" style="text-align:center; max-width:1320px; margin:0 auto 80px; padding:0 20px;">
        

            <div style="text-align:center; margin-bottom:40px;">

                <h2 style="font-size:28px; margin-bottom:12px; color:#333;">

                    <?php echo htmlspecialchars($videoSection['title'] ?? 'Our Story'); ?>

                </h2>

                <p style="font-size:14px; color:#666; margin-bottom:12px;">

                    <?php echo htmlspecialchars($videoSection['subtitle'] ?? ''); ?>

                </p>

                <p style="font-size:13px; color:#999; margin:0;">

                    <?php echo htmlspecialchars($videoSection['description'] ?? ''); ?>

                </p>

            </div>



            <div class="video-container" style="position:relative;  margin:0 auto;">

                <div class="video-thumbnail" style="position:relative; cursor:pointer; background:#000; border-radius:12px; overflow:hidden; box-shadow:0 8px 32px rgba(0,0,0,0.15); width:98%; height:450px; margin:0 auto;">

                    <img src="<?php echo htmlspecialchars($videoSection['poster_image'] ?? 'https://via.placeholder.com/800x450'); ?>" alt="Video Thumbnail" style="width:100%; height:100%; object-fit:cover; display:block;">

                </div>

                    <div class="video-play-button" style="position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); width:80px; height:80px; background:rgba(239, 136, 39, 0.9); border-radius:50%; display:flex; align-items:center; justify-content:center; cursor:pointer; transition:all 0.3s ease;">

                        <svg width="32" height="32" viewBox="0 0 24 24" fill="white" style="margin-left:4px;">

                            <polygon points="5 3 19 12 5 21"></polygon>

                        </svg>

                    </div>

                </div>

            </div>

        </div>

    </section>



    <!-- Video Modal Popup -->

    <div id="videoModal" class="video-modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.8); z-index:1000; align-items:center; justify-content:center;">

        <div class="video-modal-content" style="position:relative; width:90%; max-width:900px; max-height:90vh; background:#000; border-radius:12px; overflow:hidden;">

            <button class="video-modal-close" style="position:absolute; top:15px; right:15px; background:none; border:none; color:#fff; font-size:28px; cursor:pointer; z-index:10; width:40px; height:40px; display:flex; align-items:center; justify-content:center; background:rgba(0,0,0,0.5); border-radius:50%; transition:all 0.3s ease;" onclick="closeVideoModal()">×</button>

            <div style="position:relative; padding-bottom:56.25%; height:0; overflow:hidden; background:#000;">

                <iframe 

                    id="videoPlayerModal"

                    style="position:absolute; top:0; left:0; width:100%; height:100%; border:none; display:none;"

                    src=""

                    title="Video"

                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"

                    allowfullscreen>

                </iframe>

                <video 

                    id="videoPlayerModalVideo"

                    style="position:absolute; top:0; left:0; width:100%; height:100%; border:none; display:none; background:#000;"

                    controls

                    autoplay>

                </video>

            </div>

        </div>

    </div>

    <?php endif; ?>



    <!-- <section class="newsletter">

        <h2>Join our newsletter</h2>

        <p>Get early access to new arrivals and exclusive offers.</p>

        <form class="nl-form" action="#" method="post">

            <input type="email" name="email" placeholder="Enter your email" autocomplete="email" required>

            <button class="btn" type="submit">Subscribe</button>

        </form>

    </section> -->



    <?php require_once 'home_blog_section.php'; ?>

<!-- <div class="newsletter-banner" style="background: linear-gradient(135deg, #F07E2D 0%, #e06815 100%); padding: 20px 16px; text-align: center; border-bottom: 3px solid #d45f0a;">
    <div style="max-width: 800px; margin: 0 auto;">
        <h3 style="color: #ffffff; font-size: 20px; font-weight: 700; margin: 0 0 8px 0; letter-spacing: 0.5px;">
            Subscribe to Our Newsletter
        </h3>
        <p style="color: #ffffff; font-size: 14px; margin: 0 0 16px 0; opacity: 0.95;">
            Get exclusive deals, new arrivals, and special offers delivered to your inbox!
        </p>
        
        <form class="newsletter-form" method="POST" action="api_newsletter_subscribe.php" style="display: flex; gap: 8px; max-width: 500px; margin: 0 auto; flex-wrap: wrap; justify-content: center;">
            <input type="email" name="email" placeholder="Enter your email address" required="" style="flex: 1; min-width: 200px; padding: 12px 16px; border: none; border-radius: 4px; font-size: 14px; font-family: inherit;">
            <button type="submit" style="padding: 12px 24px; background: rgb(26, 26, 26); color: rgb(255, 255, 255); border: none; border-radius: 4px; font-size: 14px; font-weight: 600; cursor: pointer; white-space: nowrap; transition: 0.3s; transform: scale(1);" onmouseover="this.style.background='#000000'; this.style.transform='scale(1.02)';" onmouseout="this.style.background='#1a1a1a'; this.style.transform='scale(1)';">
                Subscribe
            </button>
        </form>
        
        <p style="color: #ffffff; font-size: 12px; margin: 12px 0 0 0; opacity: 0.8;">
            We respect your privacy. Unsubscribe at any time.
        </p>
    </div>
</div> -->

    <!---- logo icon section ---->

    <div class="logo-block" >

        <div class=" icon" >

  <div class="logo-icon"><i class="fa-solid fa-building"></i></div> 

  <div class="logo-label" >COMPANY</div>

    </div>

<div class=" icon" >

  <div class="logo-icon"><i class="fa-brands fa-angular"></i></div> 

  <div class="logo-label">BRAND</div>

  </div>

<div class=" icon" >

  <div class="logo-icon"><i class="fa-brands fa-atlassian"></i></div> 

  <div class="logo-label">COMPANY</div>

  

</div>



<div class=" icon" >

  <div class="logo-icon"><i class="fa-solid fa-bandage"></i></div> 

  <div class="logo-label">BRAND</div>

  </div>



<div class=" icon" >

  <div class="logo-icon"><i class="fa-solid fa-biohazard"></i></div> 

  <div class="logo-label">COMPANY</div>

  </div>

</div>



</main>



<?php include __DIR__ . '/footer.php'; ?>

<script>

let slideIndex = 0;

let slideDirection = 'next'; // Track direction for animation

let sliderAutoplayInterval = null;

const SLIDER_AUTOPLAY_INTERVAL = 5000; // 5 seconds



function changeSlide(n) {

  const slides = document.querySelectorAll('.slide');

  if (slides.length === 0) return;

  

  const prevIndex = slideIndex;

  slideIndex = (slideIndex + n + slides.length) % slides.length;

  slideDirection = n > 0 ? 'next' : 'prev';

  

  updateSlider();

  resetSliderAutoplay();

}



function goToSlide(index) {

  const slides = document.querySelectorAll('.slide');

  if (index >= 0 && index < slides.length) {

    slideDirection = index > slideIndex ? 'next' : 'prev';

    slideIndex = index;

    updateSlider();

    resetSliderAutoplay();

  }

}



function updateSlider() {

  const slides = document.querySelectorAll('.slide');

  const dots = document.querySelectorAll('.slider-dot');

  

  if (slides.length === 0) return;

  

  const prevIndex = (slideIndex - 1 + slides.length) % slides.length;

  const prevSlide = slides[prevIndex];

  const currentSlide = slides[slideIndex];

  

  // Remove all active/animation classes from all slides

  slides.forEach(slide => {

    slide.classList.remove('active', 'prev-active', 'prev-direction');

  });

  

  // Add direction class if going previous

  if (slideDirection === 'prev') {

    currentSlide.classList.add('prev-direction');

  }

  

  // Mark previous slide for exit animation

  prevSlide.classList.add('prev-active');

  

  // Mark current slide as active (will trigger enter animation)

  currentSlide.classList.add('active');

  

  // Update dot indicators

  dots.forEach((dot, idx) => {

    if (idx === slideIndex) {

      dot.classList.add('active');

    } else {

      dot.classList.remove('active');

    }

  });

  

  // Reset text animations by forcing a reflow

  // This ensures text animations run every time a slide becomes active

  currentSlide.offsetHeight; // Trigger reflow

}



// Auto-play functionality

function autoPlaySlider() {

  changeSlide(1); // Go to next slide

}



function startSliderAutoplay() {

  sliderAutoplayInterval = setInterval(autoPlaySlider, SLIDER_AUTOPLAY_INTERVAL);

}



function resetSliderAutoplay() {

  if (sliderAutoplayInterval) {

    clearInterval(sliderAutoplayInterval);

  }

  startSliderAutoplay();

}



// Initialize slider auto-play when page loads

document.addEventListener('DOMContentLoaded', function() {

  const sliderElement = document.querySelector('.hero .slider');

  if (sliderElement) {

    // Trigger initial animation on first slide

    const firstSlide = document.querySelector('.slide.active');

    if (firstSlide) {

      // Force animation by removing and re-adding active class

      setTimeout(function() {

        firstSlide.classList.remove('active');

        setTimeout(function() {

          firstSlide.classList.add('active');

          startSliderAutoplay();

        }, 10);

      }, 50);

    } else {

      startSliderAutoplay();

    }

    

    // Pause autoplay on mouse enter, resume on mouse leave

    sliderElement.addEventListener('mouseenter', function() {

      if (sliderAutoplayInterval) {

        clearInterval(sliderAutoplayInterval);

      }

    });

    

    sliderElement.addEventListener('mouseleave', function() {

      startSliderAutoplay();

    });

  }

});



// Category Carousel Functions

let categoryCarouselIndex = 0;

const categoryCarouselItemsPerView = 4;

let categoryCarouselAutoplayInterval = null;



function categoryCarouselNext() {

  const track = document.getElementById('categoryCarouselTrack');

  if (!track) return;

  

  const cards = track.querySelectorAll('.category-carousel-card');

  

  // Move to next item, but don't go past the last visible set

  const maxIndex = cards.length - categoryCarouselItemsPerView;

  if (categoryCarouselIndex < maxIndex) {

    categoryCarouselIndex++;

  } else {

    categoryCarouselIndex = 0; // Loop to start

  }

  updateCategoryCarousel();

  resetCategoryCarouselAutoplay();

}



function categoryCarouselPrev() {

  // Move to previous item, but don't go below 0

  if (categoryCarouselIndex > 0) {

    categoryCarouselIndex--;

  } else {

    const track = document.getElementById('categoryCarouselTrack');

    const cards = track.querySelectorAll('.category-carousel-card');

    categoryCarouselIndex = cards.length - categoryCarouselItemsPerView; // Loop to end

  }

  updateCategoryCarousel();

  resetCategoryCarouselAutoplay();

}



function updateCategoryCarousel() {

  const track = document.getElementById('categoryCarouselTrack');

  if (!track) return;

  

  const cards = track.querySelectorAll('.category-carousel-card');

  if (cards.length === 0) return;

  

  // Each card is 25% (for 4 items) with no gaps

  const cardPercentWidth = 25; // 100% / 4 items

  

  // Translate: each card moves by its width

  const offset = -categoryCarouselIndex * cardPercentWidth;

  

  track.style.transform = `translateX(${offset}%)`;

}



function startCategoryCarouselAutoplay() {

  // Get autoplay interval from PHP

  const interval = <?php echo $autoplayInterval; ?>;

  if (interval > 0) {

    categoryCarouselAutoplayInterval = setInterval(() => {

      categoryCarouselNext();

    }, interval);

  }

}



function resetCategoryCarouselAutoplay() {

  if (categoryCarouselAutoplayInterval) {

    clearInterval(categoryCarouselAutoplayInterval);

  }

  startCategoryCarouselAutoplay();

}



// Start carousel autoplay on page load

document.addEventListener('DOMContentLoaded', function() {

  startCategoryCarouselAutoplay();

  

  // Initialize video modal functionality

  const videoThumbnail = document.querySelector('.video-thumbnail');

  if (videoThumbnail) {

    videoThumbnail.addEventListener('click', openVideoModal);

  }
  
  // Also attach to the visible play button overlay so clicks there open the modal
  const videoPlayBtn = document.querySelector('.video-play-button');
  if (videoPlayBtn) {
    videoPlayBtn.addEventListener('click', function(e) { e.stopPropagation(); openVideoModal(); });
  }

  

  // Close modal when clicking outside the video

  const modal = document.getElementById('videoModal');

  if (modal) {

    modal.addEventListener('click', function(e) {

      if (e.target === modal) {

        closeVideoModal();

      }

    });

  }

  

  // Close modal on Escape key

  document.addEventListener('keydown', function(e) {

    if (e.key === 'Escape') {

      closeVideoModal();

    }

  });

});



// Video Modal Functions

function openVideoModal() {

  const modal = document.getElementById('videoModal');

  const videoPlayerModal = document.getElementById('videoPlayerModal');

  const videoPlayerModalVideo = document.getElementById('videoPlayerModalVideo');

  const uploadedVideo = '<?php echo !empty($videoSection['uploaded_video']) && file_exists(__DIR__ . '/' . $videoSection['uploaded_video']) ? htmlspecialchars('/emporio/' . ltrim($videoSection['uploaded_video'], '/')) : ''; ?>';

  const videoUrl = '<?php echo htmlspecialchars($videoSection['video_url'] ?? 'https://www.youtube.com/embed/dQw4w9WgXcQ'); ?>';

  

  if (modal) {

    if (uploadedVideo) {

      videoPlayerModal.style.display = 'none';

      videoPlayerModalVideo.style.display = 'block';

      // Use <source> element and load() to ensure the browser picks up the new file
      try {
        videoPlayerModalVideo.pause();
        videoPlayerModalVideo.removeAttribute('src');
        while (videoPlayerModalVideo.firstChild) videoPlayerModalVideo.removeChild(videoPlayerModalVideo.firstChild);
        const srcEl = document.createElement('source');
        srcEl.src = uploadedVideo;
        srcEl.type = 'video/' + (uploadedVideo.split('.').pop().toLowerCase());
        videoPlayerModalVideo.appendChild(srcEl);
        videoPlayerModalVideo.load();
        videoPlayerModalVideo.play().catch(err => console.log('Video play prevented:', err));
      } catch (e) {
        console.error('Error playing uploaded video:', e);
      }

    } else {

      videoPlayerModalVideo.style.display = 'none';

      videoPlayerModal.style.display = 'block';

      // Add mute to increase chance autoplay is allowed by the browser
      const sep = videoUrl.indexOf('?') === -1 ? '?' : '&';
      videoPlayerModal.src = videoUrl + sep + 'autoplay=1&mute=1';

    }

    modal.classList.add('active');

    document.body.style.overflow = 'hidden';

  }

}



function closeVideoModal() {

  const modal = document.getElementById('videoModal');

  const videoPlayerModal = document.getElementById('videoPlayerModal');

  const videoPlayerModalVideo = document.getElementById('videoPlayerModalVideo');

  

  if (modal) {

    modal.classList.remove('active');

    if (videoPlayerModal) videoPlayerModal.src = '';

    if (videoPlayerModalVideo) {

      videoPlayerModalVideo.pause();

      videoPlayerModalVideo.src = '';

    }

    document.body.style.overflow = 'auto';

  }

}



// Toggle wishlist for quick actions

function toggleWishlistQuick(productId, event) {

  event.preventDefault();

  const btn = event.target.closest('.quick-action-btn, .action-icon-btn');

  

  const formData = new FormData();

  formData.append('action', 'wishlist');

  formData.append('product_id', productId);

  

  fetch('wishlist_handler.php', {

    method: 'POST',

    body: formData

  })

  .then(response => response.json())

  .then(data => {

    if (data.success) {

      btn.classList.toggle('active');

      if (data.action === 'added') {

        btn.textContent = '♥';

        btn.title = 'Remove from Wishlist';

      } else {

        btn.textContent = '♡';

        btn.title = 'Add to Wishlist';

      }

    }

  })

  .catch(error => console.error('Error:', error));

}



// Add to cart quick function

function addToCartQuick(productId, event) {

  event.preventDefault();

  const form = new FormData();

  form.append('action', 'add');

  form.append('id', productId);

  form.append('qty', 1);

  

  fetch('cart.php', {

    method: 'POST',

    body: form

  })

  .then(() => {

    alert('Product added to cart!');

    window.location.href = 'cart.php';

  })

  .catch(error => console.error('Error:', error));

}



// Switch product image on quick color swatch click

function switchQuickProductImage(event, colorImage, mainImage) {

  // Stop default button behavior

  if (event) {

    event.preventDefault();

    event.stopPropagation();

  }

  

  // Find the button that was clicked

  const btn = event.target;

  console.log('Button clicked:', btn, 'colorImage:', colorImage, 'mainImage:', mainImage);

  

  // Find the product display wrapper (goes up from the button)

  const productWrapper = btn.closest('.product-display-wrapper');

  console.log('Found wrapper:', productWrapper ? 'YES' : 'NO');

  

  if (!productWrapper) {

    console.log('ERROR: Could not find product wrapper');

    return;

  }

  

  // Find the product image in the card within this wrapper

  const productImage = productWrapper.querySelector('.product-card-with-actions img');

  console.log('Found image:', productImage ? 'YES' : 'NO');

  

  if (!productImage) {

    console.log('ERROR: Could not find product image');

    return;

  }

  

  // Use color image if provided, otherwise use main image

  let imageToShow = (colorImage && colorImage.trim() && colorImage !== 'undefined') ? colorImage : mainImage;

  console.log('Changing image to:', imageToShow);

  

  // Change the image

  productImage.src = imageToShow;

  

  // Update button styles

  const allSwatches = productWrapper.querySelectorAll('.quick-color-swatch');

  allSwatches.forEach(swatch => swatch.style.borderColor = '#ddd');

  btn.style.borderColor = '#F07E2D';

  

  console.log('Image switched successfully');

}
</script>

<?php
// End translation buffering and translate content
// Temporarily disabled - was causing issues
// endTranslationBuffer(getTargetLanguage());
?>

</body>

</html>
