<?php
/**
 * Template Retail (E-Commerce) - Tema Claro Elegante
 * Template para lojas de varejo/e-commerce
 */

// Verificar se foi chamado corretamente
if (!defined('BARBERFLOW')) {
    die('Acesso negado');
}

// Variáveis esperadas: $store, $pdo, $currentStoreId, $storeName, $logo, $banner, $whatsapp, $address, $city

// Buscar produtos para o e-commerce
try {
    $productsStmt = $pdo->prepare("
        SELECT p.*, 
               COALESCE(r.avg_rating, 0) as avg_rating,
               COALESCE(r.total_reviews, 0) as total_reviews
        FROM products p
        LEFT JOIN (
            SELECT product_id, AVG(rating) as avg_rating, COUNT(*) as total_reviews 
            FROM product_reviews 
            WHERE is_approved = 1 
            GROUP BY product_id
        ) r ON p.id = r.product_id
        WHERE p.store_id = ? AND p.is_active = 1 
        ORDER BY p.id DESC LIMIT 16
    ");
    $productsStmt->execute([$currentStoreId]);
    $products = $productsStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $products = [];
}

// Buscar categorias
try {
    $categoriesStmt = $pdo->prepare("SELECT DISTINCT category FROM products WHERE store_id = ? AND is_active = 1 AND category IS NOT NULL AND category != '' LIMIT 6");
    $categoriesStmt->execute([$currentStoreId]);
    $categories = $categoriesStmt->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
    $categories = [];
}

// SEO & Social Settings
$templateSettings = !empty($store['template_settings']) ? json_decode($store['template_settings'], true) : [];
$seoSettings = $templateSettings['seo'] ?? [];

$seoTitle = !empty($seoSettings['meta_title']) ? $seoSettings['meta_title'] : $storeName . ' - Loja Online';
$seoDesc = !empty($seoSettings['meta_description']) ? $seoSettings['meta_description'] : $storeName . ' - Loja online em ' . $city;

$ogTitle = !empty($seoSettings['social_title']) ? $seoSettings['social_title'] : $seoTitle;
$ogDesc = !empty($seoSettings['social_description']) ? $seoSettings['social_description'] : $seoDesc;
$ogImage = !empty($seoSettings['social_image']) ? $seoSettings['social_image'] : ($logo ?? '');
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo htmlspecialchars($seoTitle); ?></title>
<meta name="description" content="<?php echo htmlspecialchars($seoDesc); ?>">
<meta name="keywords" content="<?php echo htmlspecialchars($seoSettings['keywords'] ?? ''); ?>">

<!-- Open Graph / Social -->
<meta property="og:type" content="website">
<meta property="og:title" content="<?php echo htmlspecialchars($ogTitle); ?>">
<meta property="og:description" content="<?php echo htmlspecialchars($ogDesc); ?>">
<meta property="og:image" content="<?php echo htmlspecialchars($ogImage); ?>">
<meta property="og:site_name" content="<?php echo htmlspecialchars($storeName); ?>">

<meta name="theme-color" content="#ffffff">
<?php if (!empty($faviconUrl)): ?>
<link rel="icon" type="image/png" href="<?php echo htmlspecialchars($faviconUrl); ?>?v=<?php echo time(); ?>">
<link rel="shortcut icon" type="image/png" href="<?php echo htmlspecialchars($faviconUrl); ?>?v=<?php echo time(); ?>">
<link rel="apple-touch-icon" href="<?php echo htmlspecialchars($faviconUrl); ?>">
<?php endif; ?>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.7/dist/iconify-icon.min.js"></script>
<link rel="stylesheet" href="/pages/storefront/templates/retail/modern/includes/styles.css?v=1.0.9">
<?php include __DIR__ . "/includes/dynamic-styles.php"; ?>
<!-- Dynamic Theme Colors -->
<?php
// Detectar se é tema escuro baseado na cor de fundo
$bgHex = $bgColor ?? '#FAFBFC';
$bgR = hexdec(substr($bgHex, 1, 2));
$bgG = hexdec(substr($bgHex, 3, 2));
$bgB = hexdec(substr($bgHex, 5, 2));
$bgLuminance = ($bgR * 0.299 + $bgG * 0.587 + $bgB * 0.114);
$isDarkTheme = $bgLuminance < 128;

// Variáveis calculadas para tema claro/escuro
if ($isDarkTheme) {
    $borderColor = 'rgba(255,255,255,0.12)';
    $borderLight = 'rgba(255,255,255,0.08)';
    $mutedColor = '#808080';
    $shadowSm = '0 1px 2px rgba(0,0,0,0.3)';
    $shadowMd = '0 4px 12px rgba(0,0,0,0.4)';
    $shadowLg = '0 12px 40px rgba(0,0,0,0.5)';
    $surfaceHover = 'rgba(255,255,255,0.05)';
} else {
    $borderColor = '#E5E7EB';
    $borderLight = '#F3F4F6';
    $mutedColor = '#9CA3AF';
    $shadowSm = '0 1px 2px rgba(0,0,0,0.04)';
    $shadowMd = '0 4px 12px rgba(0,0,0,0.05)';
    $shadowLg = '0 12px 40px rgba(0,0,0,0.08)';
    $surfaceHover = '#F8F9FA';
}
?>
</head>
<body>

<?php
    // Configurações do cabeçalho
    $headerSettings = $headerSettings ?? [
        'logo_type' => 'text',
        'logo_text' => $storeName,
        'logo_image' => $logo,
        'show_search' => true,
        'show_cart' => true,
        'show_wishlist' => true,
        'sticky' => true
    ];
    $stickyClass = ($headerSettings['sticky'] ?? true) ? ' sticky-header' : '';

    // Variáveis para o header.php
    $logoType = $headerSettings['logo_type'] ?? 'text';
    $logoImage = $headerSettings['logo_image'] ?? $logo;
    $logoText = $headerSettings['logo_text'] ?? $storeName;
    $storeSlug = $store['slug'] ?? '';

    // Detectar se estamos acessando via subdomínio ou via /loja/{slug}
    $currentHost = $_SERVER['HTTP_HOST'] ?? '';
    $isLojaPathAccess = strpos($_SERVER['REQUEST_URI'] ?? '', '/loja/') !== false;

    // Montar URL base da loja baseado em COMO o usuário está acessando
    if (!isset($baseUrl) || empty($baseUrl)) {
        if (function_exists('get_store_url') && !empty($store)) {
            $baseUrl = get_store_url($store);
        } elseif ($isLojaPathAccess) {
            $baseUrl = '/loja/' . ($store['slug'] ?? '');
        } else {
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
            $baseUrl = $protocol . $currentHost;
        }
    }

    // Menu dinâmico - Itens fixos SEMPRE aparecem primeiro
    // Itens fixos que SEMPRE aparecem (Início e Produtos)
    $fixedMenuItems = [
        ['id' => 1, 'name' => 'Início', 'link' => $baseUrl, 'icon' => 'solar:home-2-bold'],
        ['id' => 2, 'name' => 'Produtos', 'link' => $baseUrl . '/produtos', 'icon' => 'solar:bag-3-bold'],
    ];
    
    // Itens customizáveis - filtrar Início e Produtos
    $savedMenuItems = $customSettings['menu'] ?? [];
    $customMenuItems = [];
    if (!empty($savedMenuItems)) {
        foreach ($savedMenuItems as $item) {
            $itemName = strtolower(trim($item['name'] ?? ''));
            if (!in_array($itemName, ['início', 'inicio', 'produtos', 'home', 'products'])) {
                $customMenuItems[] = $item;
            }
        }
    }
    if (empty($customMenuItems)) {
        $customMenuItems = [
            ['id' => 3, 'name' => 'Categorias', 'link' => $baseUrl . '#categorias', 'icon' => 'solar:widget-4-bold'],
            ['id' => 4, 'name' => 'Contato', 'link' => $baseUrl . '#contato', 'icon' => 'solar:phone-bold']
        ];
    }
    $menuItems = array_merge($fixedMenuItems, $customMenuItems);
    // Corrigir links relativos do menu
    foreach ($menuItems as &$item) {
        $link = $item['link'] ?? '';
        if (strpos($link, '#') === 0) {
            $item['link'] = $baseUrl . $link;
        }
    }
    unset($item);
?>

<?php include __DIR__ . '/../../../includes/cart.php'; ?>

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

<!-- HERO BANNER -->
<?php
    // Usar heroSettings se disponível, senão usar valores padrão
    $heroSettings = $heroSettings ?? [
        'type' => 'gradient',
        'title' => 'Descubra produtos incríveis para você',
        'subtitle' => 'Qualidade premium, preços especiais e entrega rápida.',
        'button_text' => 'Ver Produtos',
        'button_link' => '#produtos',
        'show_button' => true,
        'background_image' => $banner ?? '',
        'background_images' => [],
        'background_video' => '',
        'overlay_opacity' => 50,
        'text_align' => 'left',
        'height' => 'medium',
        'slider_autoplay' => true,
        'slider_interval' => 5000
    ];
    
    // Prepare hero images array
    $heroImages = $heroSettings['background_images'] ?? [];
    if (empty($heroImages) && !empty($heroSettings['background_image'])) {
        $heroImages = [$heroSettings['background_image']];
    }
    $hasSlider = count($heroImages) > 1;
    
    // DEBUG - remover após testar
    echo "<!-- DEBUG HERO: type=" . ($heroSettings['type'] ?? 'null') . " | images_count=" . count($heroImages) . " | hasSlider=" . ($hasSlider ? 'true' : 'false') . " | images=" . implode(',', $heroImages) . " -->";
    
    // Classes do hero
    $heroClasses = ['hero-banner'];
    if ($heroSettings['type'] === 'image' && !empty($heroImages)) {
        $heroClasses[] = 'has-image';
        if ($hasSlider) {
            $heroClasses[] = 'has-slider';
        }
    }
    if ($heroSettings['type'] === 'video' && !empty($heroSettings['background_video'])) {
        $heroClasses[] = 'has-video';
    }
    $heroClasses[] = 'hero-align-' . ($heroSettings['text_align'] ?? 'left');
    $heroClasses[] = 'hero-height-' . ($heroSettings['height'] ?? 'medium');
    
    $overlayStyle = 'opacity: ' . (($heroSettings['overlay_opacity'] ?? 50) / 100) . ';';
    $sliderAutoplay = $heroSettings['slider_autoplay'] ?? true;
    $sliderInterval = $heroSettings['slider_interval'] ?? 5000;
?>
<section class="<?php echo implode(' ', $heroClasses); ?>" data-slider-autoplay="<?php echo $sliderAutoplay ? 'true' : 'false'; ?>" data-slider-interval="<?php echo $sliderInterval; ?>">
    <?php if ($heroSettings['type'] === 'image' && !empty($heroImages)): ?>
        <?php if ($hasSlider): ?>
            <!-- Hero Slider -->
            <div class="hero-slider">
                <?php foreach ($heroImages as $idx => $imgUrl): ?>
                <div class="hero-slide <?php echo $idx === 0 ? 'active' : ''; ?>">
                    <img src="<?php echo htmlspecialchars($imgUrl); ?>" alt="Banner <?php echo $idx + 1; ?>" class="banner-image">
                </div>
                <?php endforeach; ?>
            </div>
            <div class="hero-slider-dots">
                <?php foreach ($heroImages as $idx => $imgUrl): ?>
                <button class="hero-dot <?php echo $idx === 0 ? 'active' : ''; ?>" onclick="goToSlide(<?php echo $idx; ?>)"></button>
                <?php endforeach; ?>
            </div>
            <button class="hero-slider-arrow prev" onclick="prevSlide()"><iconify-icon icon="solar:alt-arrow-left-bold"></iconify-icon></button>
            <button class="hero-slider-arrow next" onclick="nextSlide()"><iconify-icon icon="solar:alt-arrow-right-bold"></iconify-icon></button>
        <?php else: ?>
            <img src="<?php echo htmlspecialchars($heroImages[0]); ?>" alt="Banner" class="banner-image">
        <?php endif; ?>
    <?php elseif ($heroSettings['type'] === 'video' && !empty($heroSettings['background_video'])): ?>
        <video class="banner-video" autoplay muted loop playsinline>
            <source src="<?php echo htmlspecialchars($heroSettings['background_video']); ?>" type="video/mp4">
        </video>
    <?php endif; ?>
    <div class="hero-overlay" style="<?php echo $overlayStyle; ?>"></div>
    <div class="hero-container">
        <div class="hero-content">
            <?php if ($heroSettings['show_text'] ?? true): ?>
            <div class="hero-tag">
                <iconify-icon icon="solar:star-bold"></iconify-icon>
                Novidades da Semana
            </div>
            <h1 class="hero-title"><?php echo htmlspecialchars($heroSettings['title'] ?? 'Bem-vindo à nossa loja'); ?></h1>
            <p class="hero-subtitle"><?php echo htmlspecialchars($heroSettings['subtitle'] ?? ''); ?></p>
            <?php endif; ?>
            <?php if ($heroSettings['show_button'] ?? true): ?>
            <a href="<?php echo htmlspecialchars($heroSettings['button_link'] ?? '#produtos'); ?>" class="hero-cta">
                <iconify-icon icon="solar:bag-3-bold"></iconify-icon>
                <?php echo htmlspecialchars($heroSettings['button_text'] ?? 'Ver Produtos'); ?>
            </a>
            <?php endif; ?>
        </div>
    </div>
</section>
<main class="main-content" id="produtos">
    <!-- Categorias -->
    <div class="categories-row">
        <button class="category-chip active">Todos</button>
        <?php if (!empty($categories)): ?>
            <?php foreach ($categories as $cat): ?>
                <button class="category-chip"><?php echo htmlspecialchars($cat); ?></button>
            <?php endforeach; ?>
        <?php else: ?>
            <button class="category-chip">Novidades</button>
            <button class="category-chip">Mais Vendidos</button>
            <button class="category-chip">Promoções</button>
        <?php endif; ?>
    </div>

    <!-- Section header -->
    <div class="section-header">
        <h2 class="section-title">Nossos Produtos</h2>
        <a href="#" class="section-link">
            Ver todos
            <iconify-icon icon="solar:arrow-right-linear"></iconify-icon>
        </a>
    </div>

    <!-- Products Grid -->
    <div id="products-skeleton" class="products-grid"></div>
    <div id="products-container" class="products-grid" style="display:none;">
        <?php if (!empty($products)): ?>
            <?php foreach ($products as $p): ?>
            <article class="product-card" onclick="window.location.href='<?php echo storeUrl('produto/' . $p['id']); ?>'" style="cursor:pointer">
                <div class="product-image">
                    <?php if (!empty($p['image_url'])): ?>
                        <img src="<?php echo htmlspecialchars($p['image_url']); ?>" alt="<?php echo htmlspecialchars($p['name']); ?>">
                    <?php else: ?>
                        <div class="product-placeholder"></div>
                    <?php endif; ?>
                    <span class="product-badge">Novo</span>
                    <button class="product-wishlist" 
                            data-product-id="<?php echo $p['id']; ?>"
                            data-product-name="<?php echo htmlspecialchars($p['name'], ENT_QUOTES); ?>"
                            data-product-price="<?php echo $p['price'] ?? 0; ?>"
                            data-product-image="<?php echo htmlspecialchars($p['image_url'] ?? '', ENT_QUOTES); ?>"
                            onclick="event.stopPropagation(); toggleFavorite(this)"
                            title="Adicionar aos favoritos">
                        <iconify-icon icon="solar:heart-outline" style="font-size: 1.1rem;"></iconify-icon>
                    </button>
                </div>
                <div class="product-info">
                    <div class="product-category"><?php echo htmlspecialchars($p['category'] ?? 'Produto'); ?></div>
                    <h3 class="product-name"><?php echo htmlspecialchars($p['name']); ?></h3>
                    <div class="product-rating">
                        <?php 
                        $avgR = floatval($p['avg_rating'] ?? 0);
                        $totalR = intval($p['total_reviews'] ?? 0);
                        for ($star = 1; $star <= 5; $star++): 
                        ?>
                        <iconify-icon icon="<?php echo $star <= round($avgR) ? 'solar:star-bold' : 'solar:star-outline'; ?>"></iconify-icon>
                        <?php endfor; ?>
                        <span>(<?php echo number_format($avgR, 1); ?>)</span>
                    </div>
                    <div class="product-footer">
                        <div class="product-price">
                            <span class="price-current">R$ <?php echo number_format($p['price'] ?? 0, 2, ',', '.'); ?></span>
                        </div>
                        <button class="btn-add-cart" onclick="event.stopPropagation(); addToCart(<?php echo $p['id']; ?>, '<?php echo htmlspecialchars($p['name'], ENT_QUOTES); ?>', <?php echo $p['price'] ?? 0; ?>, '<?php echo htmlspecialchars($p['image_url'] ?? '', ENT_QUOTES); ?>')" title="Adicionar ao carrinho">
                            <iconify-icon icon="solar:cart-plus-bold" style="font-size: 1.2rem;"></iconify-icon>
                        </button>
                    </div>
                </div>
            </article>
            <?php endforeach; ?>
        <?php else: ?>
            <?php for ($i = 0; $i < 8; $i++): ?>
            <article class="product-card">
                <div class="product-image">
                    <div class="product-placeholder"></div>
                    <span class="product-badge">Novo</span>
                    <button class="product-wishlist" title="Adicionar aos favoritos">
                        <iconify-icon icon="solar:heart-outline" style="font-size: 1.1rem;"></iconify-icon>
                    </button>
                </div>
                <div class="product-info">
                    <div class="product-category">Categoria</div>
                    <h3 class="product-name">Produto de Exemplo</h3>
                    <div class="product-rating">
                        <?php 
                        $avgR = floatval($p['avg_rating'] ?? 0);
                        $totalR = intval($p['total_reviews'] ?? 0);
                        for ($star = 1; $star <= 5; $star++): 
                        ?>
                        <iconify-icon icon="<?php echo $star <= round($avgR) ? 'solar:star-bold' : 'solar:star-outline'; ?>"></iconify-icon>
                        <?php endfor; ?>
                        <span>(<?php echo number_format($avgR, 1); ?>)</span>
                    </div>
                    <div class="product-footer">
                        <div class="product-price">
                            <span class="price-current">R$ 99,90</span>
                        </div>
                        <button class="btn-add-cart" title="Adicionar ao carrinho">
                            <iconify-icon icon="solar:cart-plus-bold" style="font-size: 1.2rem;"></iconify-icon>
                        </button>
                    </div>
                </div>
            </article>
            <?php endfor; ?>
        <?php endif; ?>
    </div>

<?php
// Renderizar seções customizadas
$customSections = $customSettings['custom_sections'] ?? [];
if (!empty($customSections)):
    foreach ($customSections as $sectionIdx => $section):
        if (!($section['enabled'] ?? true)) continue;
        if (empty($section['products'])) continue;
        
        // Buscar produtos desta seção
        $productIds = implode(',', array_map('intval', $section['products']));
        $sectionProductsStmt = $pdo->prepare("SELECT p.*, COALESCE(rv.avg_rating, 0) as avg_rating, COALESCE(rv.total_reviews, 0) as total_reviews FROM products p LEFT JOIN (SELECT product_id, AVG(rating) as avg_rating, COUNT(*) as total_reviews FROM product_reviews WHERE is_approved = 1 GROUP BY product_id) rv ON p.id = rv.product_id WHERE p.id IN ($productIds) AND p.store_id = ? AND p.is_active = 1");
        $sectionProductsStmt->execute([$currentStoreId]);
        $sectionProducts = $sectionProductsStmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($sectionProducts)) continue;
?>
<!-- Seção: <?php echo htmlspecialchars($section['title']); ?> -->
<section class="custom-section" style="padding: 3rem 0; background: transparent;">
    <div class="container" style="max-width: 1280px; margin: 0 auto; padding: 0 1.5rem;">
        <div class="section-header" style="text-align: center; margin-bottom: 2rem;">
            <h2 style="font-size: 1.75rem; font-weight: 700; color: var(--text); margin-bottom: 0.5rem;"><?php echo htmlspecialchars($section['title']); ?></h2>
            <?php if (!empty($section['subtitle'])): ?>
            <p style="color: var(--text-secondary); font-size: 1rem;"><?php echo htmlspecialchars($section['subtitle']); ?></p>
            <?php endif; ?>
        </div>
        <div id="custom-section-skeleton-<?php echo $sectionIdx; ?>" class="products-grid" data-product-count="<?php echo count($sectionProducts); ?>"></div>
        <div id="custom-section-products-<?php echo $sectionIdx; ?>" class="products-grid" style="display:none;">
            <?php foreach ($sectionProducts as $product):
                $productImage = !empty($product['image_url']) ? $product['image_url'] : '/assets/images/no-image.jpg';
                $productPrice = floatval($product['price']);
                $productOriginalPrice = floatval($product['original_price'] ?? 0);
                $hasDiscount = $productOriginalPrice > $productPrice;
                $discountPercent = $hasDiscount ? round((1 - $productPrice / $productOriginalPrice) * 100) : 0;
            ?>
            <article class="product-card" onclick="window.location.href='<?php echo storeUrl('produto/' . $product['id']); ?>'" style="cursor:pointer">
                <div class="product-image">
                    <?php if (!empty($product['image_url'])): ?>
                        <img src="<?php echo htmlspecialchars($product['image_url']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>" loading="lazy">
                    <?php else: ?>
                        <div class="product-placeholder"></div>
                    <?php endif; ?>
                    <?php if ($hasDiscount): ?>
                    <span class="product-badge">-<?php echo $discountPercent; ?>%</span>
                    <?php else: ?>
                    <span class="product-badge">Novo</span>
                    <?php endif; ?>
                    <button class="product-wishlist"
                            data-product-id="<?php echo $product['id']; ?>"
                            data-product-name="<?php echo htmlspecialchars($product['name'], ENT_QUOTES); ?>"
                            data-product-price="<?php echo $productPrice; ?>"
                            data-product-image="<?php echo htmlspecialchars($productImage, ENT_QUOTES); ?>"
                            onclick="event.stopPropagation(); toggleFavorite(this)"
                            title="Adicionar aos favoritos">
                        <iconify-icon icon="solar:heart-outline" style="font-size: 1.1rem;"></iconify-icon>
                    </button>
                </div>
                <div class="product-info">
                    <div class="product-category"><?php echo htmlspecialchars($product['category'] ?? 'Produto'); ?></div>
                    <h3 class="product-name"><?php echo htmlspecialchars($product['name']); ?></h3>
                    <div class="product-rating">
                        <?php 
                        $avgR = floatval($product['avg_rating'] ?? 0);
                        $totalR = intval($product['total_reviews'] ?? 0);
                        for ($star = 1; $star <= 5; $star++): 
                        ?>
                        <iconify-icon icon="<?php echo $star <= round($avgR) ? 'solar:star-bold' : 'solar:star-outline'; ?>"></iconify-icon>
                        <?php endfor; ?>
                        <span>(<?php echo number_format($avgR, 1); ?>)</span>
                    </div>
                    <div class="product-footer">
                        <div class="product-price">
                            <?php if ($hasDiscount): ?>
                            <span class="price-old">R$ <?php echo number_format($productOriginalPrice, 2, ',', '.'); ?></span>
                            <?php endif; ?>
                            <span class="price-current">R$ <?php echo number_format($productPrice, 2, ',', '.'); ?></span>
                        </div>
                        <button class="btn-add-cart" onclick="event.stopPropagation(); addToCart(<?php echo $product['id']; ?>, '<?php echo htmlspecialchars($product['name'], ENT_QUOTES); ?>', <?php echo $productPrice; ?>, '<?php echo htmlspecialchars($productImage, ENT_QUOTES); ?>')" title="Adicionar ao carrinho">
                            <iconify-icon icon="solar:cart-plus-bold" style="font-size: 1.2rem;"></iconify-icon>
                        </button>
                    </div>
                </div>
            </article>
            <?php endforeach; ?>
        </div>
    </div>
</section>

<?php
    endforeach;
endif;
?>
</main>

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

<!-- Toast Notification -->
<div class="toast" id="toast"></div>

<?php include __DIR__ . '/../../../includes/scripts.php'; ?>

<!-- Skeleton Loader -->
<script src="/assets/js/skeleton-loader.js?v=1.2.0"></script>

<script>
// ============================================
// SISTEMA DE FAVORITOS
// ============================================
const storeSlug = '<?php echo $store['slug'] ?? ''; ?>';
const baseUrl = '<?php echo storeUrl(); ?>';
const favoritesKey = `montaloja_favorites_${storeSlug}`;

// Carregar favoritos do localStorage
function getFavorites() {
    try {
        return JSON.parse(localStorage.getItem(favoritesKey)) || [];
    } catch (e) {
        return [];
    }
}

// Salvar favoritos no localStorage
function saveFavorites(favorites) {
    localStorage.setItem(favoritesKey, JSON.stringify(favorites));
}

// Verificar se produto está nos favoritos
function isFavorite(productId) {
    const favorites = getFavorites();
    return favorites.some(f => f.id == productId);
}

// Toggle favorito
function toggleFavorite(button) {
    const productId = button.dataset.productId;
    const productName = button.dataset.productName;
    const productPrice = parseFloat(button.dataset.productPrice);
    const productImage = button.dataset.productImage;
    
    let favorites = getFavorites();
    const existingIndex = favorites.findIndex(f => f.id == productId);
    const icon = button.querySelector('iconify-icon');
        if (!icon) return;
    
    if (existingIndex > -1) {
        // Remover dos favoritos
        favorites.splice(existingIndex, 1);
        icon.setAttribute('icon', 'solar:heart-outline');
        button.classList.remove('active');
        showToast('Removido dos favoritos', 'info');
    } else {
        // Adicionar aos favoritos
        favorites.push({
            id: productId,
            name: productName,
            price: productPrice,
            image: productImage,
            addedAt: new Date().toISOString()
        });
        icon.setAttribute('icon', 'solar:heart-bold');
        button.classList.add('active');
        showToast('Adicionado aos favoritos! ❤️', 'success');
    }
    
    saveFavorites(favorites);
    updateFavoritesCount();
}

// Atualizar contador de favoritos no header
function updateFavoritesCount() {
    const favorites = getFavorites();
    const countBadge = document.querySelector('.wishlist-btn .badge');
    if (countBadge) {
        if (favorites.length > 0) {
            countBadge.textContent = favorites.length;
            countBadge.style.display = 'flex';
        } else {
            countBadge.style.display = 'none';
        }
    }
}

// Atualizar ícones de favoritos na página
function updateFavoriteIcons() {
    const favorites = getFavorites();
    document.querySelectorAll('.product-wishlist').forEach(button => {
        const productId = button.dataset.productId;
        const icon = button.querySelector('iconify-icon');
        if (!icon) return;
        if (isFavorite(productId)) {
            icon.setAttribute('icon', 'solar:heart-bold');
            button.classList.add('active');
        } else {
            icon.setAttribute('icon', 'solar:heart-outline');
            button.classList.remove('active');
        }
    });
}

// Toast notification
function showToast(message, type = 'success') {
    const toast = document.getElementById('toast');
    if (!toast) return;
    
    toast.textContent = message;
    toast.className = 'toast show ' + type;
    
    setTimeout(() => {
        toast.classList.remove('show');
    }, 3000);
}

// ===== HERO SLIDER =====
let heroSliderInterval = null;
let currentSlide = 0;

function initHeroSlider() {
    const hero = document.querySelector('.hero-banner.has-slider');
    if (!hero) return;
    
    const slides = hero.querySelectorAll('.hero-slide');
    const dots = hero.querySelectorAll('.hero-dot');
    if (slides.length <= 1) return;
    
    const autoplay = hero.dataset.sliderAutoplay === 'true';
    const interval = parseInt(hero.dataset.sliderInterval) || 5000;
    
    if (autoplay) {
        startSliderAutoplay(interval);
        
        // Pause on hover
        hero.addEventListener('mouseenter', stopSliderAutoplay);
        hero.addEventListener('mouseleave', () => startSliderAutoplay(interval));
    }
}

function goToSlide(index) {
    const hero = document.querySelector('.hero-banner.has-slider');
    if (!hero) return;
    
    const slides = hero.querySelectorAll('.hero-slide');
    const dots = hero.querySelectorAll('.hero-dot');
    
    if (index < 0) index = slides.length - 1;
    if (index >= slides.length) index = 0;
    
    slides.forEach((slide, i) => {
        slide.classList.toggle('active', i === index);
    });
    dots.forEach((dot, i) => {
        dot.classList.toggle('active', i === index);
    });
    
    currentSlide = index;
}

function nextSlide() {
    goToSlide(currentSlide + 1);
}

function prevSlide() {
    goToSlide(currentSlide - 1);
}

function startSliderAutoplay(interval) {
    stopSliderAutoplay();
    heroSliderInterval = setInterval(nextSlide, interval);
}

function stopSliderAutoplay() {
    if (heroSliderInterval) {
        clearInterval(heroSliderInterval);
        heroSliderInterval = null;
    }
}

// Inicializar ao carregar a página
document.addEventListener('DOMContentLoaded', function() {
    // Inicializar slider do hero
    initHeroSlider();
    
    // Mostrar skeleton de produtos enquanto carrega
    if (typeof SkeletonLoader !== 'undefined') {
        SkeletonLoader.showSkeleton('products-skeleton', 'products', {count: <?php echo count($products) > 0 ? count($products) : 8; ?>});
    }
    
    // Revelar produtos após carregamento
    setTimeout(function() {
        var skeleton = document.getElementById('products-skeleton');
        var products = document.getElementById('products-container');
        
        if (skeleton) skeleton.style.display = 'none';
        
        if (products) {
            products.style.display = '';
            products.style.opacity = '0';
            products.style.transition = 'opacity 0.4s ease';
            setTimeout(function() { products.style.opacity = '1'; }, 50);
        }
    }, 800);
    
    // Skeleton para seções customizadas
    document.querySelectorAll('[id^="custom-section-skeleton-"]').forEach(function(skeletonEl) {
        var idx = skeletonEl.id.replace('custom-section-skeleton-', '');
        var productCount = parseInt(skeletonEl.dataset.productCount) || 4;
        if (typeof SkeletonLoader !== 'undefined') {
            SkeletonLoader.showSkeleton(skeletonEl.id, 'products', {count: productCount});
        }
        setTimeout(function() {
            var productsEl = document.getElementById('custom-section-products-' + idx);
            skeletonEl.style.display = 'none';
            if (productsEl) {
                productsEl.style.display = '';
                productsEl.style.opacity = '0';
                productsEl.style.transition = 'opacity 0.4s ease';
                setTimeout(function() { productsEl.style.opacity = '1'; }, 50);
            }
        }, 600);
    });

    updateFavoriteIcons();
    updateFavoritesCount();
});
</script>

</body>
</html>
