<?php
/**
 * Página de Detalhes do Produto - MontaLoja
 * Usa os mesmos componentes da home.php
 */

if (!defined('BARBERFLOW')) {
    define('BARBERFLOW', true);
}

// Caminho: /pages/storefront/templates/retail/modern/ → /includes/config.php (5 níveis)
require_once __DIR__ . '/../../../../../includes/config.php';

try {
    $pdo = getDB();
} catch (Exception $e) {
    die("Erro ao conectar ao banco de dados: " . $e->getMessage());
}

// ============================================
// IDENTIFICAR LOJA PELA URL
// ============================================

$requestUri = $_SERVER['REQUEST_URI'];
// ============================================
// IDENTIFICAR LOJA PELA URL
// ============================================

$requestUri = $_SERVER['REQUEST_URI'];
$pathParts = explode('/', trim(parse_url($requestUri, PHP_URL_PATH), '/'));
$host = $_SERVER['HTTP_HOST'];
$hostParts = explode('.', $host);

// Extrair subdomain corretamente (ignorando app, www, etc)
$subdomain = null;
if (count($hostParts) >= 3) {
    $potentialSubdomain = $hostParts[0];
    if (!in_array($potentialSubdomain, ['app', 'www', 'api', 'admin'])) {
        $subdomain = $potentialSubdomain;
    }
} elseif (count($hostParts) == 2 and !in_array($hostParts[0], ['montaloja', 'app', 'www'])) {
    $subdomain = $hostParts[0];
}

// Primeiro tentar obter da sessão (quando vem do router)
$store = $_SESSION['current_store'] ?? null;

// Se não tem na sessão, tentar identificar

// Tentar buscar por subdomain primeiro (se não veio da sessão)
if (!$store && $subdomain) {
    $stmt = $pdo->prepare("SELECT * FROM stores WHERE (slug = ? OR subdomain = ?) AND is_active = 1 AND deleted_at IS NULL");
    $stmt->execute([$subdomain, $subdomain]);
    $store = $stmt->fetch(PDO::FETCH_ASSOC);
}

// Se nao encontrou, tentar pela URL /loja/{slug}
if (!$store and isset($pathParts[0]) and $pathParts[0] === 'loja' and isset($pathParts[1])) {
    $slug = $pathParts[1];
    $stmt = $pdo->prepare("SELECT * FROM stores WHERE (slug = ? OR subdomain = ?) AND is_active = 1 AND deleted_at IS NULL");
    $stmt->execute([$slug, $slug]);
    $store = $stmt->fetch(PDO::FETCH_ASSOC);
}

// Configurar variáveis e função storeUrl
$storeSlug = $store['slug'] ?? $store['subdomain'] ?? '';

// Detectar URL base dinamicamente - sem domínio hardcoded
$currentHost = $_SERVER['HTTP_HOST'] ?? '';
$isLojaPathAccess = strpos($_SERVER['REQUEST_URI'] ?? '', '/loja/') !== false;
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';

if (function_exists('get_store_url') && !empty($store)) {
    $baseUrl = get_store_url($store);
} elseif ($isLojaPathAccess) {
    $baseUrl = '/loja/' . $storeSlug;
} else {
    $baseUrl = $protocol . $currentHost;
}

if (!function_exists('storeUrl')) {
    function storeUrl($path = '') {
        global $store, $storeSlug, $baseUrl;

        if (isset($baseUrl) && (strpos($baseUrl, 'http') === 0 || strpos($baseUrl, '/') === 0)) {
            $base = $baseUrl;
        } elseif (function_exists('get_store_url') && !empty($store)) {
            $base = get_store_url($store);
        } else {
            $proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
            $base = $proto . ($_SERVER['HTTP_HOST'] ?? '');
        }

        return $base . ($path ? '/' . ltrim($path, '/') : '');
    }
}

$productId = isset($_GET['id']) ? intval($_GET['id']) : 0;
if (!$productId  && isset($pathParts[2]) && $pathParts[2] === 'produto' && isset($pathParts[3])) {
    $productId = intval($pathParts[3]);
}

if (!$productId) {
    header('Location: ' . storeUrl());
    exit;
}

// ============================================
// CARREGAR PRODUTO
// ============================================

$currentStoreId = $store['id'];

$stmt = $pdo->prepare("
    SELECT p.*, c.name as category_name, c.color as category_color
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    WHERE p.id = ? AND p.store_id = ? AND p.is_active = 1
");
$stmt->execute([$productId, $currentStoreId]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$product) {
    header('Location: ' . storeUrl());
    exit;
}


// ============================================
// CARREGAR VARIAÇÕES DO PRODUTO (suporta novo e antigo sistema)
// ============================================
$variations = [];
$variationsByType = [];
$productVariants = []; // Novo sistema Shopify-style

// PRIMEIRO: Tentar carregar do novo sistema (product_variants)
try {
    $variantsStmt = $pdo->prepare("
        SELECT id, title, option_values, price, stock_quantity, sku
        FROM product_variants
        WHERE product_id = ? AND is_active = 1
        ORDER BY title
    ");
    $variantsStmt->execute([$productId]);
    $productVariants = $variantsStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // Tabela product_variants ainda não existe - usar sistema antigo
    $productVariants = [];
}

if (!empty($productVariants)) {
    // Novo sistema: extrair opções do JSON option_values
    foreach ($productVariants as $variant) {
        $optionValues = json_decode($variant['option_values'], true) ?: [];
        foreach ($optionValues as $optionName => $optionValue) {
            if (!isset($variationsByType[$optionName])) {
                $variationsByType[$optionName] = [];
            }
            // Verificar se já existe essa opção
            $exists = false;
            foreach ($variationsByType[$optionName] as $existing) {
                if ($existing['value'] === $optionValue) {
                    $exists = true;
                    break;
                }
            }
            if (!$exists) {
                $variationsByType[$optionName][] = [
                    'id' => $variant['id'],
                    'name' => $optionName,
                    'value' => $optionValue,
                    'price_adjustment' => 0,
                    'stock_quantity' => $variant['stock_quantity'],
                    'variant_id' => $variant['id'],
                    'variant_title' => $variant['title'],
                    'variant_price' => $variant['price']
                ];
            }
        }
    }
} else {
    // Sistema antigo: product_variations
    $varStmt = $pdo->prepare("
        SELECT id, name, value, price_adjustment, stock_quantity
        FROM product_variations
        WHERE product_id = ? AND is_active = 1
        ORDER BY name, value
    ");
    $varStmt->execute([$productId]);
    $variations = $varStmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($variations as $v) {
        $type = $v['name'];
        if (!isset($variationsByType[$type])) {
            $variationsByType[$type] = [];
        }
        $variationsByType[$type][] = $v;
    }
}

$hasVariations = !empty($variationsByType);

// Calcular preço mínimo e máximo das variantes
$minPrice = $product['price'];
$maxPrice = $product['price'];
$hasPriceRange = false;

if (!empty($productVariants)) {
    $variantPrices = array_map(function($v) { return floatval($v['price']); }, $productVariants);
    if (!empty($variantPrices)) {
        $minPrice = min($variantPrices);
        $maxPrice = max($variantPrices);
        $hasPriceRange = ($minPrice !== $maxPrice);
    }
}
$relatedProducts = [];
if ($product['category_id']) {
    $stmt = $pdo->prepare("
        SELECT * FROM products
        WHERE store_id = ? AND category_id = ? AND id != ? AND is_active = 1
        ORDER BY RAND() LIMIT 4
    ");
    $stmt->execute([$currentStoreId, $product['category_id'], $productId]);
    $relatedProducts = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Imagens do produto
$allImages = [];
if (!empty($product['image_url'])) {
    $allImages[] = $product['image_url'];
}
if (!empty($product['images'])) {
    $additionalImages = json_decode($product['images'], true) ?: [];
    $allImages = array_merge($allImages, $additionalImages);
}

// ============================================
// CARREGAR CONFIGURAÇÕES (igual ao home.php)
// ============================================

$storefrontTemplate = $store['storefront_template'] ?? 'retail-light';

$systemTemplateSettings = [
    'retail-light' => [
        'primary_color' => '#2563EB', 'bg_color' => '#FAFBFC', 'card_color' => '#FFFFFF',
        'text_color' => '#111827', 'accent_color' => '#10B981', 'border_color' => '#E5E7EB',
        'text_secondary' => '#6B7280', 'is_light' => true
    ],
    'retail-dark' => [
        'primary_color' => '#8B5CF6', 'bg_color' => '#0F172A', 'card_color' => '#1E293B',
        'text_color' => '#F1F5F9', 'accent_color' => '#F59E0B', 'border_color' => 'rgba(255,255,255,0.1)',
        'text_secondary' => '#94A3B8', 'is_light' => false
    ],
    'barber-classic' => [
        'primary_color' => '#CCA43B', 'bg_color' => '#0A0A0A', 'card_color' => '#151515',
        'text_color' => '#FFFFFF', 'accent_color' => '#D4AF37', 'border_color' => 'rgba(204,164,59,0.3)',
        'text_secondary' => '#B0B0B0', 'is_light' => false
    ]
];
$faviconUrl = $headerSettings['favicon'] ?? '';

$settings = $systemTemplateSettings[$storefrontTemplate] ?? $systemTemplateSettings['retail-light'];
$primaryColor = $settings['primary_color'];
$bgColor = $settings['bg_color'];
$cardColor = $settings['card_color'];
$textColor = $settings['text_color'];
$accentColor = $settings['accent_color'];
$borderColor = $settings['border_color'];
$textSecondary = $settings['text_secondary'];
$isLightTheme = $settings['is_light'];

// Configurações personalizadas
$customSettings = [];
if (!empty($store['template_settings'])) {
    $customSettings = json_decode($store['template_settings'], true) ?? [];
}

if (!empty($customSettings['colors'])) {
    $primaryColor = $customSettings['colors']['primary'] ?? $primaryColor;
    $bgColor = $customSettings['colors']['bg'] ?? $bgColor;
    $cardColor = $customSettings['colors']['card'] ?? $cardColor;
    $textColor = $customSettings['colors']['text'] ?? $textColor;
    $accentColor = $customSettings['colors']['accent'] ?? $accentColor;
}

// Configurações do Header (dinâmico do dashboard)
$headerSettings = $customSettings['header'] ?? [
    'logo_type' => 'text',
    'logo_text' => $store['name'] ?? 'Minha Loja',
    'logo_image' => $store['logo_url'] ?? '',
    'show_search' => true,
    'show_cart' => true,
    'show_wishlist' => true,
    'sticky' => true
];
$faviconUrl = $headerSettings['favicon'] ?? '';

// Menu dinâmico - Itens fixos SEMPRE aparecem primeiro
// Itens fixos que SEMPRE aparecem (Início e Produtos)
$fixedMenuItems = [
    ['id' => 1, 'name' => 'Início', 'link' => storeUrl(), 'icon' => 'solar:home-2-bold'],
    ['id' => 2, 'name' => 'Produtos', 'link' => storeUrl() . '/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' => storeUrl() . '#categorias', 'icon' => 'solar:widget-4-bold'],
        ['id' => 4, 'name' => 'Contato', 'link' => storeUrl() . '#contato', 'icon' => 'solar:phone-bold']
    ];
}
$menuItems = array_merge($fixedMenuItems, $customMenuItems);
$faviconUrl = $headerSettings['favicon'] ?? '';

// Corrigir links relativos - transformar âncoras em URLs absolutas
foreach ($menuItems as &$item) {
    // Se link começa com # (âncora), adicionar URL base da loja
    if (strpos($item['link'], '#') === 0) {
        $item['link'] = storeUrl() . $item['link'];
    }
    // Se link é vazio, # sozinho ou / , apontar para home
    elseif ($item['link'] === '' || $item['link'] === '#' || $item['link'] === '/' || $item['name'] === 'Início') {
        $item['link'] = storeUrl();
    }
}
unset($item);

// Variáveis para os componentes
$storeName = $store['name'] ?? 'Minha Loja';
$whatsapp = $store['whatsapp_number'] ?? $store['whatsapp'] ?? '';
$logo = $store['logo_url'] ?? $store['logo'] ?? '';
$address = $store['address'] ?? '';
$city = $store['city'] ?? '';
$storeSlug = $store['slug'] ?? '';

$logoType = $headerSettings['logo_type'] ?? 'text';
$logoImage = $headerSettings['logo_image'] ?? $logo;
$logoText = $headerSettings['logo_text'] ?? $storeName;
?>
<!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($product['name']); ?> - <?php echo htmlspecialchars($storeName); ?></title>
<meta name="description" content="<?php echo htmlspecialchars(substr($product['description'] ?? '', 0, 160)); ?>">
<meta property="og:title" content="<?php echo htmlspecialchars($product['name']); ?>">
<meta property="og:description" content="<?php echo htmlspecialchars(substr($product['description'] ?? '', 0, 160)); ?>">
<?php if (!empty($product['image_url'])): ?>
<meta property="og:image" content="<?php echo htmlspecialchars($product['image_url']); ?>">
<?php endif; ?>
<?php if (!empty($faviconUrl)): ?>
<link rel="icon" type="image/x-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.4">
<?php include __DIR__ . "/includes/dynamic-styles.php"; ?>
<style>
/* Dynamic Color Variables from Store Settings */
:root {
    --primary: <?php echo htmlspecialchars($primaryColor ?? '#2563EB'); ?>;
    --primary-soft: <?php echo htmlspecialchars($primaryColor ?? '#2563EB'); ?>14;
    --primary-hover: <?php echo htmlspecialchars($customSettings['colors']['secondary'] ?? $primaryColor ?? '#1D4ED8'); ?>;
    --accent: <?php echo htmlspecialchars($accentColor ?? '#10B981'); ?>;
    --accent-soft: <?php echo htmlspecialchars($accentColor ?? '#10B981'); ?>1A;
    --bg: <?php echo htmlspecialchars($bgColor ?? '#FAFBFC'); ?>;
    --bg-white: <?php echo htmlspecialchars($cardColor ?? '#FFFFFF'); ?>;
    --surface: <?php echo htmlspecialchars($cardColor ?? '#FFFFFF'); ?>;
    --text: <?php echo htmlspecialchars($textColor ?? '#111827'); ?>;
    --text-secondary: <?php echo htmlspecialchars($textSecondary ?? '#6B7280'); ?>;
}

:root {
    --bg: <?php echo $bgColor; ?>;
    --bg-white: <?php echo $cardColor; ?>;
    --surface: <?php echo $cardColor; ?>;
    --surface-hover: <?php echo $isLightTheme ? '#F8F9FA' : '#2D3748'; ?>;
    --border: <?php echo $borderColor; ?>;
    --border-light: <?php echo $isLightTheme ? '#F3F4F6' : 'rgba(255,255,255,0.05)'; ?>;
    --primary: <?php echo $primaryColor; ?>;
    --primary-soft: <?php echo $primaryColor; ?>15;
    --primary-hover: <?php echo $primaryColor; ?>;
    --accent: <?php echo $accentColor; ?>;
    --text: <?php echo $textColor; ?>;
    --text-secondary: <?php echo $textSecondary; ?>;
    --muted: <?php echo $isLightTheme ? '#9CA3AF' : '#707070'; ?>;
    --shadow: 0 4px 12px rgba(0,0,0,0.05);
    --shadow-lg: 0 12px 40px rgba(0,0,0,0.08);
    --radius: 12px;
    --radius-lg: 16px;
    --success: #10B981;
    --error: #EF4444;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
    font-family: 'Plus Jakarta Sans', sans-serif;
    background: var(--bg);
    color: var(--text);
    -webkit-font-smoothing: antialiased;
    min-height: 100vh;
}

/* ===== BREADCRUMB ===== */
.breadcrumb-container { background: var(--bg-white); border-bottom: 1px solid var(--border-light); }
.breadcrumb { max-width: 1280px; margin: 0 auto; padding: 12px 24px; display: flex; align-items: center; gap: 8px; font-size: 0.85rem; }
.breadcrumb a { color: var(--text-secondary); text-decoration: none; }
.breadcrumb a:hover { color: var(--primary); }
.breadcrumb span { color: var(--muted); }
.breadcrumb-current { color: var(--text); font-weight: 500; }

/* ===== PRODUCT PAGE ===== */
.product-container { max-width: 1280px; margin: 0 auto; padding: 32px 24px; }
.product-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 48px; margin-bottom: 48px; }
.product-gallery { display: flex; flex-direction: column; gap: 16px; }
.main-image { aspect-ratio: 1; background: var(--bg-white); border-radius: 16px; overflow: hidden; border: 1px solid var(--border-light); }
.main-image img { width: 100%; height: 100%; object-fit: cover; }
.main-image-placeholder { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background: var(--surface-hover); color: var(--muted); }
.thumbnails { display: flex; gap: 12px; overflow-x: auto; padding-bottom: 8px; }
.thumbnail { width: 80px; height: 80px; border-radius: 12px; overflow: hidden; border: 2px solid transparent; cursor: pointer; transition: all 0.2s; flex-shrink: 0; }
.thumbnail:hover, .thumbnail.active { border-color: var(--primary); }
.thumbnail img { width: 100%; height: 100%; object-fit: cover; }
.product-info { display: flex; flex-direction: column; gap: 20px; }
.product-category-badge { display: inline-flex; padding: 6px 12px; background: var(--primary-soft); color: var(--primary); font-size: 0.8rem; font-weight: 600; border-radius: 20px; width: fit-content; }
.product-title { font-size: 2rem; font-weight: 700; color: var(--text); line-height: 1.2; }
.product-price-container { display: flex; flex-direction: column; gap: 4px; }
.product-price { font-size: 2.25rem; font-weight: 800; color: var(--primary); }
.product-installments { font-size: 0.95rem; color: var(--text-secondary); }
.stock-status { display: flex; align-items: center; gap: 8px; font-size: 0.9rem; }
.stock-status.in-stock { color: var(--success); }
.stock-status.low-stock { color: #F59E0B; }
.stock-status.out-of-stock { color: var(--error); }
.product-description { font-size: 0.95rem; color: var(--text-secondary); line-height: 1.7; }
.quantity-selector { display: flex; align-items: center; gap: 16px; }
.quantity-selector label { font-weight: 600; color: var(--text); }
.quantity-controls { display: flex; align-items: center; border: 1px solid var(--border); border-radius: 10px; overflow: hidden; }
.qty-btn { width: 44px; height: 44px; border: none; background: var(--bg); color: var(--text); font-size: 1.2rem; cursor: pointer; display: flex; align-items: center; justify-content: center; }
.qty-btn:hover { background: var(--surface-hover); }
.qty-value { width: 60px; height: 44px; border: none; border-left: 1px solid var(--border); border-right: 1px solid var(--border); text-align: center; font-size: 1rem; font-weight: 600; color: var(--text); background: var(--bg-white); }
.action-buttons { display: flex; gap: 12px; }
.btn-cart { flex: 1; padding: 16px 24px; background: var(--primary); color: white; border: none; border-radius: 12px; font-size: 1rem; font-weight: 600; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 10px; transition: all 0.2s; }
.btn-cart:hover { opacity: 0.9; transform: translateY(-2px); }
.btn-whatsapp { flex: 1; padding: 16px 24px; background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); color: white; border: none; border-radius: 12px; font-size: 1rem; font-weight: 600; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 10px; text-decoration: none; transition: all 0.2s; box-shadow: 0 4px 12px rgba(37, 211, 102, 0.25); }
.btn-whatsapp:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(37, 211, 102, 0.35); }

/* ===== RELATED PRODUCTS ===== */
.related-section { margin-top: 48px; padding-top: 48px; border-top: 1px solid var(--border-light); }
.section-title { font-size: 1.5rem; font-weight: 700; color: var(--text); margin-bottom: 24px; }
.related-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 24px; }
.product-card { background: var(--bg-white); border-radius: 16px; overflow: hidden; border: 1px solid var(--border-light); transition: all 0.3s; cursor: pointer; }
.product-card:hover { transform: translateY(-4px); box-shadow: var(--shadow-lg); }
.product-card-image { aspect-ratio: 1; background: var(--surface-hover); overflow: hidden; }
.product-card-image img { width: 100%; height: 100%; object-fit: cover; }
.product-card-info { padding: 16px; }
.product-card-name { font-size: 0.95rem; font-weight: 600; color: var(--text); margin-bottom: 8px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.product-card-price { font-size: 1.1rem; font-weight: 700; color: var(--primary); }


/* ===== VARIATIONS SECTION ===== */
.variations-section {
    display: flex;
    flex-direction: column;
    gap: 20px;
    padding: 20px 0;
    border-top: 1px solid var(--border-light);
    border-bottom: 1px solid var(--border-light);
}
.variation-group {
    display: flex;
    flex-direction: column;
    gap: 12px;
}
.variation-label {
    font-weight: 600;
    font-size: 0.95rem;
    color: var(--text);
    display: flex;
    align-items: center;
    gap: 8px;
}
.variation-selected-value {
    font-weight: 400;
    color: var(--text-secondary);
}
.variation-options {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}
.variation-btn {
    position: relative;
    min-width: 50px;
    padding: 12px 20px;
    border: 2px solid var(--border);
    border-radius: 10px;
    background: var(--bg-white);
    color: var(--text);
    font-size: 0.9rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
}
.variation-btn:hover:not(.out-of-stock) {
    border-color: var(--primary);
    background: var(--primary-soft);
}
.variation-btn.selected {
    border-color: var(--primary);
    background: var(--primary);
    color: white;
}
.variation-btn.out-of-stock {
    opacity: 0.4;
    cursor: not-allowed;
    text-decoration: line-through;
}
.variation-btn .price-diff {
    font-size: 0.75rem;
    opacity: 0.8;
}
.variation-btn.selected .price-diff {
    color: rgba(255,255,255,0.9);
}
.variation-warning {
    display: none;
    padding: 12px 16px;
    background: #FEF3C7;
    border: 1px solid #F59E0B;
    border-radius: 8px;
    color: #92400E;
    font-size: 0.9rem;
    align-items: center;
    gap: 8px;
}
.variation-warning.show {
    display: flex;
}

/* ===== RESPONSIVE ===== */
@media (max-width: 1024px) {
    .product-grid { gap: 32px; }
    .related-grid { grid-template-columns: repeat(3, 1fr); }
}
@media (max-width: 768px) {
    .product-container { padding: 20px 16px; }
    .product-grid { grid-template-columns: 1fr; gap: 24px; }
    .product-title { font-size: 1.5rem; }
    .product-price { font-size: 1.75rem; }
    .action-buttons { flex-direction: column; }
    .related-grid { grid-template-columns: repeat(2, 1fr); gap: 16px; }
    .breadcrumb { padding: 12px 16px; font-size: 0.8rem; }
}
@media (max-width: 480px) {
    .thumbnails { gap: 8px; }
    .thumbnail { width: 60px; height: 60px; }
    .quantity-controls { flex: 1; }
    .quantity-selector { flex-direction: column; align-items: stretch; gap: 12px; }
}

/* Product Tabs */
.product-tabs { margin-top: 48px; margin-bottom: 48px; }
.product-tabs-nav { display: flex; gap: 0; border-bottom: 2px solid var(--border-color); margin-bottom: 24px; }
.product-tab-btn { padding: 16px 24px; background: none; border: none; font-size: 1rem; font-weight: 500; color: var(--text-secondary); cursor: pointer; position: relative; transition: all 0.3s ease; }
.product-tab-btn:hover { color: var(--primary); }
.product-tab-btn.active { color: var(--primary); }
.product-tab-btn.active::after { content: ""; position: absolute; bottom: -2px; left: 0; right: 0; height: 2px; background: var(--primary); }
.product-tab-content { display: none; animation: fadeIn 0.3s ease; }
.product-tab-content.active { display: block; }

/* Specifications */
.product-specifications { margin-top: 20px; }
.specifications-table { width: 100%; border-collapse: collapse; }
.specifications-table tr:nth-child(even) { background: rgba(0,0,0,0.03); }
.specifications-table td { padding: 12px 16px; border-bottom: 1px solid var(--border-color); font-size: 0.9rem; }
.specifications-table td:first-child { font-weight: 600; width: 40%; }

/* Reviews */
.reviews-container { max-width: 800px; }
.reviews-summary { display: flex; gap: 32px; padding: 24px; background: var(--bg-secondary); border-radius: 12px; margin-bottom: 32px; }
.reviews-average { text-align: center; padding-right: 32px; border-right: 1px solid var(--border-color); }
.reviews-average-number { font-size: 3rem; font-weight: 700; color: var(--primary); }
.reviews-average-stars { color: #fbbf24; font-size: 1.25rem; margin: 8px 0; }
.reviews-average-count { font-size: 0.875rem; color: var(--text-secondary); }
.reviews-bars { flex: 1; display: flex; flex-direction: column; gap: 8px; justify-content: center; }
.review-bar-row { display: flex; align-items: center; gap: 12px; font-size: 0.875rem; }
.review-bar-label { width: 60px; color: var(--text-secondary); }
.review-bar-track { flex: 1; height: 8px; background: var(--border-color); border-radius: 4px; }
.review-bar-fill { height: 100%; background: #fbbf24; border-radius: 4px; }
.reviews-list { display: flex; flex-direction: column; gap: 24px; }
.review-item { padding: 20px; background: var(--bg-secondary); border-radius: 12px; }
.review-header { display: flex; justify-content: space-between; margin-bottom: 12px; }
.review-author { display: flex; align-items: center; gap: 12px; }
.review-avatar { width: 40px; height: 40px; border-radius: 50%; background: var(--primary); color: white; display: flex; align-items: center; justify-content: center; font-weight: 600; }
.review-stars { color: #fbbf24; }
.review-content { color: var(--text-secondary); line-height: 1.6; }
.no-reviews { text-align: center; padding: 48px 24px; color: var(--text-secondary); }
.no-reviews iconify-icon { font-size: 3rem; opacity: 0.5; display: block; margin-bottom: 16px; }
.write-review-btn { display: inline-flex; align-items: center; gap: 8px; padding: 12px 24px; background: var(--primary); color: white; border: none; border-radius: 8px; cursor: pointer; margin-top: 24px; }

/* Review Modal */
/* Review Modal Styles */
.review-modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.6); z-index: 99999; display: none; align-items: center; justify-content: center; padding: 20px; }
.review-modal-overlay.active { display: flex; }
.review-modal { background: #fff; border-radius: 16px; width: 100%; max-width: 500px; max-height: 90vh; overflow-y: auto; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25); }
.review-modal-header { padding: 20px 24px; border-bottom: 1px solid #e5e7eb; display: flex; justify-content: space-between; align-items: center; }
.review-modal-header h3 { font-size: 1.25rem; font-weight: 600; margin: 0; color: #111827; }
.review-modal-close { background: none; border: none; font-size: 1.75rem; cursor: pointer; color: #6b7280; line-height: 1; padding: 0; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; border-radius: 8px; transition: all 0.2s; }
.review-modal-close:hover { background: #f3f4f6; color: #111827; }
#reviewForm { padding: 24px; }
.review-form-group { margin-bottom: 20px; }
.review-form-group label { display: block; font-size: 0.875rem; font-weight: 600; margin-bottom: 8px; color: #374151; }
.review-form-group input[type="text"],
.review-form-group input[type="email"],
.review-form-group textarea { width: 100%; padding: 12px 16px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 1rem; background: #fff; color: #111827; transition: all 0.2s; box-sizing: border-box; }
.review-form-group input:focus,
.review-form-group textarea:focus { outline: none; border-color: #4f46e5; box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1); }
.review-form-group textarea { min-height: 100px; resize: vertical; font-family: inherit; }
.review-form-group input::placeholder,
.review-form-group textarea::placeholder { color: #9ca3af; }

/* Star Rating */
.star-rating { display: flex; flex-direction: row-reverse; justify-content: flex-end; gap: 4px; }
.star-rating input[type="radio"] { display: none; }
.star-rating label { cursor: pointer; font-size: 2rem; color: #d1d5db; transition: color 0.15s; }
.star-rating label iconify-icon { display: block; }
.star-rating label:hover,
.star-rating label:hover ~ label,
.star-rating input:checked ~ label { color: #fbbf24; }
.star-rating-text { display: block; font-size: 0.8rem; color: #6b7280; margin-top: 6px; }

/* Submit Button */
.review-submit-btn { width: 100%; padding: 14px 24px; background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%); color: white; border: none; border-radius: 10px; font-size: 1rem; font-weight: 600; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; transition: all 0.2s; }
.review-submit-btn:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(79, 70, 229, 0.4); }
.review-submit-btn:disabled { opacity: 0.7; cursor: not-allowed; transform: none; }
.review-submit-btn iconify-icon { font-size: 1.1rem; }

@media (max-width: 768px) {
    .product-tab-btn { padding: 12px 16px; font-size: 0.9rem; }
    .reviews-summary { flex-direction: column; }
    .reviews-average { padding-right: 0; padding-bottom: 20px; border-right: none; border-bottom: 1px solid var(--border-color); }
}
</style>
</head>
<body>

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

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

<!-- Breadcrumb -->
<div class="breadcrumb-container">
    <nav class="breadcrumb">
        <a href="<?php echo storeUrl(); ?>">Início</a>
        <span>/</span>
        <a href="<?php echo storeUrl(); ?>#produtos">Produtos</a>
        <span>/</span>
        <span class="breadcrumb-current"><?php echo htmlspecialchars($product['name']); ?></span>
    </nav>
</div>

<!-- Conteúdo do Produto -->
<main class="product-container">
    <div class="product-grid">
        <!-- Galeria -->
        <div class="product-gallery">
            <div class="main-image" id="mainImage">
                <?php if (!empty($allImages)): ?>
                    <img src="<?php echo htmlspecialchars($allImages[0]); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>" id="mainImageSrc">
                <?php else: ?>
                    <div class="main-image-placeholder">
                        <iconify-icon icon="solar:gallery-bold" style="font-size: 4rem;"></iconify-icon>
                    </div>
                <?php endif; ?>
            </div>
            <?php if (count($allImages) > 1): ?>
            <div class="thumbnails">
                <?php foreach ($allImages as $index => $img): ?>
                <div class="thumbnail<?php echo $index === 0 ? ' active' : ''; ?>" onclick="changeImage('<?php echo htmlspecialchars($img); ?>', this)">
                    <img src="<?php echo htmlspecialchars($img); ?>" alt="Foto <?php echo $index + 1; ?>">
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>

        <!-- Informações -->
        <div class="product-info">
            <?php
            // Buscar avaliações para mostrar estrelas
            $ratingStmt = $pdo->prepare("SELECT COUNT(*) as total, AVG(rating) as average FROM product_reviews WHERE product_id = ? AND is_approved = 1");
            $ratingStmt->execute([$productId]);
            $ratingData = $ratingStmt->fetch(PDO::FETCH_ASSOC);
            $totalRatings = intval($ratingData['total'] ?? 0);
            $avgRating = floatval($ratingData['average'] ?? 0);
            ?>
            <div class="product-meta-header">
                <?php if (!empty($product['category_name'])): ?>
                <span class="product-category-badge"><?php echo htmlspecialchars($product['category_name']); ?></span>
                <?php endif; ?>
                <div class="product-rating-summary">
                    <div class="rating-stars-inline">
                        <?php for ($i = 1; $i <= 5; $i++): ?>
                        <iconify-icon icon="<?php echo $i <= round($avgRating) ? 'solar:star-bold' : 'solar:star-linear'; ?>" class="<?php echo $i <= round($avgRating) ? 'star-filled' : 'star-empty'; ?>"></iconify-icon>
                        <?php endfor; ?>
                    </div>
                    <span class="rating-count"><?php echo number_format($avgRating, 1); ?> (<?php echo $totalRatings; ?> avaliação<?php echo $totalRatings != 1 ? 'ões' : ''; ?>)</span>
                </div>
            </div>

            <h1 class="product-title"><?php echo htmlspecialchars($product['name']); ?></h1>

            <div class="product-price-container">
                <?php if ($hasPriceRange): ?>
                <span class="product-price" id="displayPrice">R$ <?php echo number_format($minPrice, 2, ',', '.'); ?> - R$ <?php echo number_format($maxPrice, 2, ',', '.'); ?></span>
                <?php else: ?>
                <span class="product-price" id="displayPrice">R$ <?php echo number_format($product['price'] ?? 0, 2, ',', '.'); ?></span>
                <?php endif; ?>
                <?php if ($hasPriceRange): ?>
                <span class="product-installments" id="displayInstallments">ou 10x de R$ <?php echo number_format($minPrice / 10, 2, ',', '.'); ?> - R$ <?php echo number_format($maxPrice / 10, 2, ',', '.'); ?> sem juros</span>
                <?php else: ?>
                <span class="product-installments" id="displayInstallments">ou 10x de R$ <?php echo number_format(($product['price'] ?? 0) / 10, 2, ',', '.'); ?> sem juros</span>
                <?php endif; ?>
            </div>

            <?php
            $stock = $product['stock_quantity'] ?? 0;
            $stockClass = 'in-stock';
            $stockText = 'Em estoque';
            $stockIcon = 'solar:check-circle-bold';
            if ($stock <= 0) {
                $stockClass = 'out-of-stock';
                $stockText = 'Fora de estoque';
                $stockIcon = 'solar:close-circle-bold';
            } elseif ($stock <= 5) {
                $stockClass = 'low-stock';
                $stockText = "Apenas $stock em estoque";
                $stockIcon = 'solar:danger-triangle-bold';
            }
            ?>
            <div class="stock-status <?php echo $stockClass; ?>" id="stockStatus">
                <iconify-icon icon="<?php echo $stockIcon; ?>"></iconify-icon>
                <?php echo $stockText; ?>
            </div>

            <?php if ($hasVariations): ?>
            <!-- Seção de Variações -->
            <div class="variations-section" id="variationsSection">
                <?php foreach ($variationsByType as $typeName => $options): ?>
                <div class="variation-group" data-variation-type="<?php echo htmlspecialchars($typeName); ?>">
                    <label class="variation-label">
                        <?php echo htmlspecialchars($typeName); ?>:
                        <span class="variation-selected-value" id="selected_<?php echo htmlspecialchars(preg_replace('/[^a-zA-Z0-9]/', '_', $typeName)); ?>">Selecione</span>
                    </label>
                    <div class="variation-options">
                        <?php foreach ($options as $option): ?>
                        <?php
                        $isOutOfStock = ($option['stock_quantity'] <= 0);
                        $priceAdj = floatval($option['price_adjustment']);
                        $priceDiffText = '';
                        if ($priceAdj > 0) {
                            $priceDiffText = '+R$ ' . number_format($priceAdj, 2, ',', '.');
                        } elseif ($priceAdj < 0) {
                            $priceDiffText = '-R$ ' . number_format(abs($priceAdj), 2, ',', '.');
                        }
                        ?>
                        <button type="button"
                                class="variation-btn <?php echo $isOutOfStock ? 'out-of-stock' : ''; ?>"
                                data-variation-id="<?php echo $option['id']; ?>"
                                data-variation-type="<?php echo htmlspecialchars($typeName); ?>"
                                data-variation-value="<?php echo htmlspecialchars($option['value']); ?>"
                                data-price-adjustment="<?php echo $priceAdj; ?>"
                                data-stock="<?php echo $option['stock_quantity']; ?>"
                                <?php echo $isOutOfStock ? 'disabled' : ''; ?>
                                onclick="selectVariation(this)">
                            <span class="variation-value"><?php echo htmlspecialchars($option['value']); ?></span>
                            <?php if ($priceDiffText): ?>
                            <span class="price-diff"><?php echo $priceDiffText; ?></span>
                            <?php endif; ?>
                        </button>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endforeach; ?>
                
                <!-- Aviso de seleção -->
                <div class="variation-warning" id="variationWarning">
                    <iconify-icon icon="solar:danger-triangle-bold"></iconify-icon>
                    <span>Por favor, selecione todas as opções antes de adicionar ao carrinho.</span>
                </div>
            </div>
            <?php endif; ?>

            <div class="quantity-selector">
                <label>Quantidade:</label>
                <div class="quantity-controls">
                    <button class="qty-btn" onclick="changeQty(-1)">-</button>
                    <input type="number" class="qty-value" id="quantity" value="1" min="1" max="<?php echo max(1, $stock); ?>">
                    <button class="qty-btn" onclick="changeQty(1)">+</button>
                </div>
            </div>

            <div class="action-buttons">
                <button class="btn-cart" id="btnAddToCart" onclick="handleAddToCart()" <?php echo $stock <= 0 ? 'disabled style="opacity:0.5;cursor:not-allowed"' : ''; ?>>
                    <iconify-icon icon="solar:cart-plus-bold" style="font-size: 1.2rem;"></iconify-icon>
                    Adicionar ao Carrinho
                </button>
                <button type="button" class="btn-whatsapp" onclick="buyNowViaWhatsApp()" <?php echo $stock <= 0 ? 'disabled style="opacity:0.5;cursor:not-allowed"' : ''; ?>>
                    <iconify-icon icon="solar:bag-check-bold" style="font-size: 1.2rem;"></iconify-icon>
                    Comprar
                </button>
            </div>

            <!-- Simulador de Frete -->
            <div class="shipping-calculator" style="margin-top: 1.5rem; padding: 1rem; background: var(--bg-light, #f5f5f5); border-radius: 12px;">
                <div style="display: flex; align-items: center; gap: 0.75rem; margin-bottom: 1rem;">
                    <iconify-icon icon="solar:delivery-bold" style="font-size: 1.25rem; color: var(--primary);"></iconify-icon>
                    <strong style="font-size: 0.95rem;">Calcular Frete</strong>
                </div>
                <div style="display: flex; gap: 0.75rem;">
                    <input type="text" id="shippingZipcode" class="shipping-cep-input" placeholder="Digite seu CEP" maxlength="9" 
                        style="flex: 1; padding: 0.75rem 1rem; border: 1px solid var(--border-color, #ddd); border-radius: 8px; font-size: 1rem;">
                    <button type="button" onclick="calculateShipping()" class="btn-calc-shipping" 
                        style="padding: 0.75rem 1.25rem; background: var(--primary); color: #fff; border: none; border-radius: 8px; font-weight: 600; cursor: pointer;">
                        Calcular
                    </button>
                </div>
                <div id="shippingResults" style="margin-top: 1rem; display: none;">
                    <div id="shippingLoading" style="text-align: center; padding: 1rem; display: none;">
                        <iconify-icon icon="svg-spinners:ring-resize" style="font-size: 1.5rem;"></iconify-icon>
                        <span style="margin-left: 0.5rem;">Calculando...</span>
                    </div>
                    <div id="shippingOptions"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabs de Descrição, Especificações e Avaliações -->
    <div class="product-tabs">
        <div class="product-tabs-nav">
            <button type="button" class="product-tab-btn active" data-tab="description" onclick="switchProductTab('description')">
                <iconify-icon icon="solar:document-text-linear"></iconify-icon> Descrição
            </button>
            <button type="button" class="product-tab-btn" data-tab="specifications" onclick="switchProductTab('specifications')">
                <iconify-icon icon="solar:list-check-linear"></iconify-icon> Especificações
            </button>
            <button type="button" class="product-tab-btn" data-tab="reviews" onclick="switchProductTab('reviews')">
                <iconify-icon icon="solar:chat-round-dots-linear"></iconify-icon> Avaliações
            </button>
        </div>

        <!-- Tab Descrição -->
        <div class="product-tab-content active" id="tab-description">
            <div class="product-description-tab">
                <?php if (!empty($product['description'])): ?>
                    <div class="description-content">
                        <?php echo nl2br(htmlspecialchars($product['description'])); ?>
                    </div>
                <?php else: ?>
                    <div class="no-reviews">
                        <iconify-icon icon="solar:document-text-linear"></iconify-icon>
                        <p>Este produto ainda não possui descrição.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Tab Especificações -->
        <div class="product-tab-content" id="tab-specifications">
            <?php
            $specifications = json_decode($product['specifications'] ?? '[]', true) ?: [];
            if (!empty($specifications)):
            ?>
            <div class="product-specifications">
                <table class="specifications-table">
                    <tbody>
                        <?php foreach ($specifications as $spec): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($spec['name']); ?></td>
                            <td><?php echo htmlspecialchars($spec['value']); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php else: ?>
            <div class="no-reviews">
                <iconify-icon icon="solar:document-text-linear"></iconify-icon>
                <p>Nenhuma especificação cadastrada para este produto.</p>
            </div>
            <?php endif; ?>
        </div>

        <!-- Tab Avaliações -->
        <div class="product-tab-content" id="tab-reviews">
            <div class="reviews-container">
                <?php
                $reviewsStmt = $pdo->prepare("SELECT * FROM product_reviews WHERE product_id = ? AND is_approved = 1 ORDER BY created_at DESC LIMIT 10");
                try {
                    $reviewsStmt->execute([$productId]);
                    $reviews = $reviewsStmt->fetchAll(PDO::FETCH_ASSOC);
                } catch (PDOException $e) {
                    $reviews = [];
                }
                
                $totalReviews = count($reviews);
                $averageRating = 0;
                $ratingCounts = [5 => 0, 4 => 0, 3 => 0, 2 => 0, 1 => 0];
                if ($totalReviews > 0) {
                    $sum = 0;
                    foreach ($reviews as $review) {
                        $sum += $review['rating'];
                        $ratingCounts[$review['rating']]++;
                    }
                    $averageRating = $sum / $totalReviews;
                }
                ?>
                
                <?php if ($totalReviews > 0): ?>
                <div class="reviews-summary">
                    <div class="reviews-average">
                        <div class="reviews-average-number"><?php echo number_format($averageRating, 1); ?></div>
                        <div class="reviews-average-stars">
                            <?php for ($i = 1; $i <= 5; $i++): ?>
                            <iconify-icon icon="<?php echo $i <= round($averageRating) ? 'solar:star-bold' : 'solar:star-linear'; ?>"></iconify-icon>
                            <?php endfor; ?>
                        </div>
                        <div class="reviews-average-count"><?php echo $totalReviews; ?> avaliação<?php echo $totalReviews > 1 ? 'ões' : ''; ?></div>
                    </div>
                    <div class="reviews-bars">
                        <?php for ($i = 5; $i >= 1; $i--): ?>
                        <div class="review-bar-row">
                            <span class="review-bar-label"><?php echo $i; ?> estrela<?php echo $i > 1 ? 's' : ''; ?></span>
                            <div class="review-bar-track">
                                <div class="review-bar-fill" style="width: <?php echo $totalReviews > 0 ? ($ratingCounts[$i] / $totalReviews * 100) : 0; ?>%"></div>
                            </div>
                        </div>
                        <?php endfor; ?>
                    </div>
                </div>

                <div class="reviews-list">
                    <?php foreach ($reviews as $review): ?>
                    <div class="review-item">
                        <div class="review-header">
                            <div class="review-author">
                                <div class="review-avatar"><?php echo strtoupper(substr($review['author_name'] ?? 'A', 0, 1)); ?></div>
                                <div>
                                    <strong><?php echo htmlspecialchars($review['author_name'] ?? 'Anônimo'); ?></strong>
                                    <br><small><?php echo date('d/m/Y', strtotime($review['created_at'])); ?></small>
                                </div>
                            </div>
                            <div class="review-stars">
                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                <iconify-icon icon="<?php echo $i <= $review['rating'] ? 'solar:star-bold' : 'solar:star-linear'; ?>"></iconify-icon>
                                <?php endfor; ?>
                            </div>
                        </div>
                        <div class="review-content"><?php echo nl2br(htmlspecialchars($review['comment'] ?? '')); ?></div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <div class="no-reviews">
                    <iconify-icon icon="solar:chat-round-dots-linear"></iconify-icon>
                    <p>Este produto ainda não possui avaliações.</p>
                    <p>Seja o primeiro a avaliar!</p>
                </div>
                <?php endif; ?>
                
                <button type="button" class="write-review-btn" onclick="openReviewModal()">
                    <iconify-icon icon="solar:pen-bold"></iconify-icon>
                    Escrever Avaliação
                </button>
            </div>
        </div>
    </div>

    <!-- Produtos Relacionados -->
    <?php if (!empty($relatedProducts)): ?>
    <section class="related-section">
        <h2 class="section-title">Produtos Relacionados</h2>
        <div class="related-grid">
            <?php foreach ($relatedProducts as $rp): ?>
            <article class="product-card" onclick="window.location.href='<?php echo storeUrl('produto/' . $rp['id']); ?>'">
                <div class="product-card-image">
                    <?php if (!empty($rp['image_url'])): ?>
                    <img src="<?php echo htmlspecialchars($rp['image_url']); ?>" alt="<?php echo htmlspecialchars($rp['name']); ?>">
                    <?php endif; ?>
                </div>
                <div class="product-card-info">
                    <h3 class="product-card-name"><?php echo htmlspecialchars($rp['name']); ?></h3>
                    <span class="product-card-price">R$ <?php echo number_format($rp['price'] ?? 0, 2, ',', '.'); ?></span>
                </div>
            </article>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>
</main>

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

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

<script>
// ============================================
// CONFIGURAÇÃO DO PRODUTO E VARIAÇÕES
// ============================================
const productConfig = {
    id: <?php echo $product['id']; ?>,
    name: '<?php echo addslashes($product['name']); ?>',
    basePrice: <?php echo $product['price'] ?? 0; ?>,
    image: '<?php echo addslashes($product['image_url'] ?? ''); ?>',
    hasVariations: <?php echo $hasVariations ? 'true' : 'false'; ?>,
    variationTypes: <?php echo json_encode(array_keys($variationsByType)); ?>,
    variations: <?php echo json_encode($variations); ?>,
    variants: <?php echo json_encode($productVariants ?? []); ?>,
    minPrice: <?php echo $minPrice; ?>,
    maxPrice: <?php echo $maxPrice; ?>,
    hasPriceRange: <?php echo $hasPriceRange ? 'true' : 'false'; ?>
};

const selectedVariations = {};
let currentTotalPrice = productConfig.basePrice;
let currentStock = <?php echo $stock; ?>;
const storeId = <?php echo $store['id']; ?>;

function selectVariation(btn) {
    if (btn.classList.contains('out-of-stock')) return;
    
    const type = btn.dataset.variationType;
    const value = btn.dataset.variationValue;
    const variationId = btn.dataset.variationId;
    const priceAdj = parseFloat(btn.dataset.priceAdjustment) || 0;
    const stock = parseInt(btn.dataset.stock) || 0;
    
    const sameTypeButtons = document.querySelectorAll('.variation-btn[data-variation-type="' + type + '"]');
    sameTypeButtons.forEach(b => b.classList.remove('selected'));
    
    btn.classList.add('selected');
    
    selectedVariations[type] = {
        id: variationId,
        value: value,
        priceAdjustment: priceAdj,
        stock: stock
    };
    
    const labelId = 'selected_' + type.replace(/[^a-zA-Z0-9]/g, '_');
    const label = document.getElementById(labelId);
    if (label) {
        label.textContent = value;
    }
    
    updatePrice();
    updateStockDisplay();
    hideVariationWarning();
}

function updatePrice() {
    // Verificar se todas as opções foram selecionadas
    const selectedTypes = Object.keys(selectedVariations);
    const allTypesSelected = productConfig.variationTypes.every(t => selectedTypes.includes(t));
    
    if (allTypesSelected && productConfig.variants && productConfig.variants.length > 0) {
        // Construir o título da variante selecionada (ex: "Azul / G")
        const selectedValues = productConfig.variationTypes.map(t => selectedVariations[t].value);
        const targetTitle = selectedValues.join(' / ');
        
        console.log('Buscando variante:', targetTitle);
        console.log('Variantes disponíveis:', productConfig.variants.map(v => v.title));
        
        // Buscar a variante exata pelo título
        const matchedVariant = productConfig.variants.find(v => v.title === targetTitle);
        
        if (matchedVariant && matchedVariant.price) {
            console.log('Variante encontrada! Preço:', matchedVariant.price);
            currentTotalPrice = parseFloat(matchedVariant.price);
        } else {
            // Tentar encontrar por option_values (JSON)
            const matchedByOptions = productConfig.variants.find(v => {
                try {
                    const opts = typeof v.option_values === 'string' ? JSON.parse(v.option_values) : v.option_values;
                    return productConfig.variationTypes.every(t => opts[t] === selectedVariations[t].value);
                } catch(e) { return false; }
            });
            
            if (matchedByOptions && matchedByOptions.price) {
                console.log('Encontrado por options! Preço:', matchedByOptions.price);
                currentTotalPrice = parseFloat(matchedByOptions.price);
            } else {
                console.log('Variante não encontrada, usando preço base');
                currentTotalPrice = productConfig.basePrice;
            }
        }
    } else {
        // Fallback: sistema antigo com ajustes
        let totalAdj = 0;
        Object.values(selectedVariations).forEach(v => {
            totalAdj += v.priceAdjustment || 0;
        });
        currentTotalPrice = productConfig.basePrice + totalAdj;
    }

    const priceEl = document.getElementById('displayPrice');
    const installmentsEl = document.getElementById('displayInstallments');

    if (priceEl) {
        priceEl.textContent = 'R$ ' + currentTotalPrice.toLocaleString('pt-BR', {minimumFractionDigits: 2, maximumFractionDigits: 2});
    }

    if (installmentsEl) {
        const installmentValue = currentTotalPrice / 10;
        installmentsEl.textContent = 'ou 10x de R$ ' + installmentValue.toLocaleString('pt-BR', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' sem juros';
    }
}

function updateStockDisplay() {
    const stocks = Object.values(selectedVariations).map(v => v.stock);
    
    if (stocks.length > 0) {
        currentStock = Math.min(...stocks);
    } else {
        currentStock = <?php echo $stock; ?>;
    }
    
    const stockStatus = document.getElementById('stockStatus');
    const qtyInput = document.getElementById('quantity');
    const btnCart = document.getElementById('btnAddToCart');
    const btnWhatsApp = document.querySelector('.btn-whatsapp');
    
    if (qtyInput) {
        qtyInput.max = Math.max(1, currentStock);
        if (parseInt(qtyInput.value) > currentStock) {
            qtyInput.value = Math.max(1, currentStock);
        }
    }
    
    if (stockStatus) {
        stockStatus.className = 'stock-status';
        let icon = stockStatus.querySelector('iconify-icon');
        let textSpan = stockStatus.querySelector('span') || stockStatus;
        
        if (currentStock <= 0) {
            stockStatus.classList.add('out-of-stock');
            if (icon) icon.setAttribute('icon', 'solar:close-circle-bold');
            textSpan.textContent = 'Fora de estoque';
            if (btnCart) btnCart.disabled = true;
            if (btnWhatsApp) btnWhatsApp.disabled = true;
        } else if (currentStock <= 5) {
            stockStatus.classList.add('low-stock');
            if (icon) icon.setAttribute('icon', 'solar:danger-triangle-bold');
            textSpan.textContent = 'Apenas ' + currentStock + ' em estoque';
            if (btnCart) btnCart.disabled = false;
            if (btnWhatsApp) btnWhatsApp.disabled = false;
        } else {
            stockStatus.classList.add('in-stock');
            if (icon) icon.setAttribute('icon', 'solar:check-circle-bold');
            textSpan.textContent = 'Em estoque';
            if (btnCart) btnCart.disabled = false;
            if (btnWhatsApp) btnWhatsApp.disabled = false;
        }
    }
}

function validateVariationSelection() {
    if (!productConfig.hasVariations) return true;
    
    const requiredTypes = productConfig.variationTypes;
    const selectedTypes = Object.keys(selectedVariations);
    
    for (const type of requiredTypes) {
        if (!selectedTypes.includes(type)) {
            return false;
        }
    }
    return true;
}

function showVariationWarning() {
    const warning = document.getElementById('variationWarning');
    if (warning) {
        warning.classList.add('show');
        warning.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
}

function hideVariationWarning() {
    const warning = document.getElementById('variationWarning');
    if (warning) {
        warning.classList.remove('show');
    }
}

function getSelectedVariationsText() {
    const parts = [];
    for (const [type, data] of Object.entries(selectedVariations)) {
        parts.push(type + ': ' + data.value);
    }
    return parts.join(', ');
}

function getSelectedVariationIds() {
    return Object.values(selectedVariations).map(v => v.id);
}

function handleAddToCart() {
    if (!validateVariationSelection()) {
        showVariationWarning();
        return;
    }
    
    const quantity = parseInt(document.getElementById('quantity').value) || 1;
    const variationsText = getSelectedVariationsText();
    const variationIds = getSelectedVariationIds();
    
    const cartItemId = productConfig.id + '_' + variationIds.join('_');
    
    addToCartWithVariations(
        cartItemId,
        productConfig.id,
        productConfig.name,
        currentTotalPrice,
        productConfig.image,
        quantity,
        variationsText,
        selectedVariations
    );
}

function addToCartWithVariations(cartItemId, productId, name, price, image, quantity, variationsText, variationsData) {
    // Usa a variável global 'cart' e CART_STORAGE_KEY do cart.php
    
    let displayName = name;
    if (variationsText) {
        displayName = name + ' (' + variationsText + ')';
    }
    
    const existingIndex = cart.findIndex(item => item.id === cartItemId);
    
    if (existingIndex >= 0) {
        cart[existingIndex].quantity += quantity;
    } else {
        cart.push({
            cartItemId: cartItemId,
            id: cartItemId,
            name: displayName,
            originalName: name,
            price: price,
            image: image,
            quantity: quantity,
            variations: variationsData,
            variationsText: variationsText
        });
    }
    
    saveCart();
    
    if (typeof updateCartCount === 'function') {
        updateCartCount();
    }
    
    showAddToCartFeedback();
    
    if (typeof openCart === 'function') {
        setTimeout(() => openCart(), 300);
    }
}

function showAddToCartFeedback() {
    const btn = document.getElementById('btnAddToCart');
    if (!btn) return;
    
    const originalHTML = btn.innerHTML;
    btn.innerHTML = '<iconify-icon icon="solar:check-circle-bold" style="font-size: 1.2rem;"></iconify-icon> Adicionado!';
    btn.style.background = 'var(--success)';
    
    setTimeout(() => {
        btn.innerHTML = originalHTML;
        btn.style.background = '';
    }, 2000);
}

function buyNowViaWhatsApp() {
    if (!validateVariationSelection()) {
        showVariationWarning();
        return;
    }
    
    const quantity = parseInt(document.getElementById('quantity').value) || 1;
    const variationsText = getSelectedVariationsText();
    const variationIds = getSelectedVariationIds();
    const cartItemId = productConfig.id + '_' + variationIds.join('_');
    
    addToCartWithVariations(
        cartItemId,
        productConfig.id,
        productConfig.name,
        currentTotalPrice,
        productConfig.image,
        quantity,
        variationsText,
        selectedVariations
    );
    
    // Redirecionar para página de checkout
    setTimeout(() => {
        window.location.href = '<?php echo storeUrl(); ?>/checkout';
    }, 300);
}

function changeImage(src, el) {
    document.getElementById('mainImageSrc').src = src;
    document.querySelectorAll('.thumbnail').forEach(t => t.classList.remove('active'));
    el.classList.add('active');
}

function changeQty(delta) {
    const input = document.getElementById('quantity');
    let val = parseInt(input.value) + delta;
    const max = parseInt(input.max) || 99;
    if (val < 1) val = 1;
    if (val > max) val = max;
    input.value = val;
}

function addToCart(productId, name, price, image, quantity) {
    if (productConfig.hasVariations) {
        handleAddToCart();
    } else {
        addToCartWithVariations(
            productId.toString(),
            productId,
            name,
            price,
            image,
            quantity,
            '',
            {}
        );
    }
}
</script>


<!-- Modal de Avaliação -->
<div class="review-modal-overlay" id="reviewModal">
    <div class="review-modal">
        <div class="review-modal-header">
            <h3>Escrever Avaliação</h3>
            <button type="button" class="review-modal-close" onclick="closeReviewModal()">&times;</button>
        </div>
        <form id="reviewForm" onsubmit="submitReview(event)">
            <input type="hidden" name="product_id" value="<?php echo $productId; ?>">
            <input type="hidden" name="store_id" value="<?php echo $storeId ?? $store['id'] ?? 0; ?>">
            
            <div class="review-form-group">
                <label>Sua Avaliação</label>
                <div class="star-rating">
                    <input type="radio" name="rating" value="5" id="star5" required>
                    <label for="star5" onclick="setStarText('Excelente!')"><iconify-icon icon="solar:star-bold"></iconify-icon></label>
                    <input type="radio" name="rating" value="4" id="star4">
                    <label for="star4" onclick="setStarText('Muito Bom')"><iconify-icon icon="solar:star-bold"></iconify-icon></label>
                    <input type="radio" name="rating" value="3" id="star3">
                    <label for="star3" onclick="setStarText('Bom')"><iconify-icon icon="solar:star-bold"></iconify-icon></label>
                    <input type="radio" name="rating" value="2" id="star2">
                    <label for="star2" onclick="setStarText('Regular')"><iconify-icon icon="solar:star-bold"></iconify-icon></label>
                    <input type="radio" name="rating" value="1" id="star1">
                    <label for="star1" onclick="setStarText('Ruim')"><iconify-icon icon="solar:star-bold"></iconify-icon></label>
                </div>
                <span class="star-rating-text" id="starText">Clique nas estrelas para avaliar</span>
            </div>
            
            <div class="review-form-group">
                <label for="author_name">Seu Nome</label>
                <input type="text" name="author_name" id="author_name" required placeholder="Digite seu nome">
            </div>
            
            <div class="review-form-group">
                <label for="author_email">Seu E-mail</label>
                <input type="email" name="author_email" id="author_email" placeholder="Digite seu e-mail (opcional)">
            </div>
            
            <div class="review-form-group">
                <label for="comment">Seu Comentário</label>
                <textarea name="comment" id="comment" required rows="4" placeholder="Conte sua experiência com este produto (mínimo 10 caracteres)"></textarea>
            </div>
            
            <button type="submit" class="review-submit-btn" id="submitBtn">
                <iconify-icon icon="solar:send-bold"></iconify-icon>
                Enviar Avaliação
            </button>
        </form>
    </div>
</div>

<script>
function switchProductTab(tabId) {
    document.querySelectorAll(".product-tab-btn").forEach(function(btn) {
        btn.classList.remove("active");
    });
    document.querySelectorAll(".product-tab-content").forEach(function(content) {
        content.classList.remove("active");
    });
    document.querySelector("[data-tab=\"" + tabId + "\"]").classList.add("active");
    document.getElementById("tab-" + tabId).classList.add("active");
}

function openReviewModal() {
    document.getElementById("reviewModal").classList.add("active");
    document.body.style.overflow = "hidden";
}

function closeReviewModal() {
    document.getElementById("reviewModal").classList.remove("active");
    document.body.style.overflow = "";
}

function setStarText(text) {
    document.getElementById("starText").textContent = text;
}

function submitReview(event) {
    event.preventDefault();
    var form = document.getElementById("reviewForm");
    var btn = document.getElementById("submitBtn");
    var formData = new FormData(form);
    
    btn.disabled = true;
    btn.innerHTML = "<iconify-icon icon=\"solar:refresh-bold\"></iconify-icon> Enviando...";
    
    fetch("/api/submit-review.php", {
        method: "POST",
        body: formData
    })
    .then(function(response) { return response.json(); })
    .then(function(data) {
        if (data.success) {
            alert("Avaliação enviada com sucesso! Obrigado pelo seu feedback.");
            closeReviewModal();
            form.reset();
            document.getElementById("starText").textContent = "Clique nas estrelas para avaliar";
            window.location.reload();
        } else {
            alert(data.message || "Erro ao enviar avaliação. Tente novamente.");
        }
    })
    .catch(function(error) {
        console.error("Error:", error);
        alert("Erro ao enviar avaliação. Tente novamente.");
    })
    .finally(function() {
        btn.disabled = false;
        btn.innerHTML = "<iconify-icon icon=\"solar:send-bold\"></iconify-icon> Enviar Avaliação";
    });
}

document.getElementById("reviewModal").addEventListener("click", function(e) {
    if (e.target === this) closeReviewModal();
});

// ========== SIMULADOR DE FRETE ==========
function calculateShipping() {
    const zipcode = document.getElementById('shippingZipcode').value.replace(/\D/g, '');
    if (zipcode.length !== 8) {
        alert('Por favor, digite um CEP válido com 8 dígitos');
        return;
    }
    
    const resultsDiv = document.getElementById('shippingResults');
    const loadingDiv = document.getElementById('shippingLoading');
    const optionsDiv = document.getElementById('shippingOptions');
    
    resultsDiv.style.display = 'block';
    loadingDiv.style.display = 'block';
    optionsDiv.innerHTML = '';
    
    const productId = <?= json_encode($productId) ?>;
    const storeId = <?= json_encode($currentStoreId) ?>;
    const quantity = parseInt(document.getElementById('productQuantity')?.value || 1);
    
    fetch('/api/shipping/calculate.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            cart_total: (typeof productConfig !== "undefined" ? productConfig.basePrice : 0) * quantity,
            store_id: storeId,
            items: [{ product_id: productId, quantity: quantity }],
            zipcode: zipcode
        })
    })
    .then(r => r.json())
    .then(data => {
        loadingDiv.style.display = 'none';
        if (data.success && data.options && data.options.length > 0) {
            optionsDiv.innerHTML = data.options.map(opt => `
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem; background: #fff; border-radius: 8px; margin-bottom: 0.5rem; border: 1px solid var(--border-color, #eee);">
                    <div>
                        <strong style="display: block;">${opt.carrier} - ${opt.service}</strong>
                        <small style="color: #666;">${opt.delivery_time}</small>
                    </div>
                    <div style="text-align: right;">
                        ${opt.price == 0 || opt.free_shipping ? '<span style="color: #10b981; font-weight: 600;">Grátis</span>' : `<strong style="color: var(--primary);">R$ ${opt.price.toFixed(2).replace('.', ',')}</strong>`}
                    </div>
                </div>
            `).join('');
        } else {
            optionsDiv.innerHTML = '<div style="text-align: center; padding: 1rem; color: #666;">Nenhuma opção de frete disponível para este CEP.</div>';
        }
    })
    .catch(err => {
        loadingDiv.style.display = 'none';
        optionsDiv.innerHTML = '<div style="color: #ef4444; text-align: center;">Erro ao calcular frete. Tente novamente.</div>';
        console.error('Shipping error:', err);
    });
}

// Máscar de CEP
document.getElementById('shippingZipcode')?.addEventListener('input', function(e) {
    let v = e.target.value.replace(/\D/g, '');
    if (v.length > 5) v = v.slice(0,5) + '-' + v.slice(5,8);
    e.target.value = v;
});
</script>

</body>
</html>

