<?php
/**
 * Editor de Template - BarberFlow SaaS
 * Permite personalizar cores e seções do template ativo
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/check-access.php';

$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

if (!$userId || !$storeId) {
    header('Location: /pages/login.php');
    exit;
}

// Buscar dados da loja
$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

if (!$store) {
    header('Location: /pages/dashboard.php');
    exit;
}


// Buscar produtos da loja para o seletor de seções
$productsStmt = $pdo->prepare("SELECT id, name, price, image_url FROM products WHERE store_id = ? AND is_active = 1 ORDER BY name ASC");
$productsStmt->execute([$storeId]);
$storeProducts = $productsStmt->fetchAll(PDO::FETCH_ASSOC);

$currentTemplate = $store['storefront_template'] ?? 'barber-classic';
$businessType = $store['business_type'] ?? 'service';
$isRetail = ($businessType === 'retail');


// Ajustar template para tipo de negócio
if ($isRetail && !in_array($currentTemplate, ['retail-light', 'retail-dark'])) {
    $currentTemplate = 'retail-light';
}
// Scan template pages for menu link options
$templateCategory = $isRetail ? 'retail' : 'service';
$templateFolder = $isRetail ? 'modern' : (strpos($currentTemplate, 'elegant') !== false ? 'elegant' : 'classic');
$templatePath = __DIR__ . '/storefront/templates/' . $templateCategory . '/' . $templateFolder;
$templatePages = [];
if (is_dir($templatePath)) {
    $files = glob($templatePath . '/*.php');
    foreach ($files as $file) {
        $filename = basename($file, '.php');
        // Skip internal/system files
        if (!in_array($filename, ['debug_test', 'logout'])) {
            $templatePages[$filename] = ucwords(str_replace('-', ' ', $filename));
        }
    }
 
}
// Determinar URL base da loja
$domainType = $store["domain_type"] ?? "subdomain";
$customDomain = $store["custom_domain"] ?? "";
$subdomain = $store["subdomain"] ?? "";
$storeSlug = $store["slug"] ?? $subdomain;

if ($domainType === "custom" && !empty($customDomain)) {
    $storeBaseUrl = "https://" . $customDomain;
} elseif ($domainType === "subdomain" && !empty($subdomain)) {
    $storeBaseUrl = "https://" . $subdomain . ".duolead.com.br";
} else {
    $storeBaseUrl = "/loja/" . $storeSlug;
}

// Buscar páginas personalizadas da loja
$customPagesStmt = $pdo->prepare("SELECT id, title, slug FROM store_pages WHERE store_id = ? AND is_active = 1 ORDER BY title ASC");
$customPagesStmt->execute([$storeId]);
$customStorePages = $customPagesStmt->fetchAll(PDO::FETCH_ASSOC);

// Opções de link do menu (apenas páginas e links personalizados)
$menuLinkOptions = [];

// Adicionar páginas personalizadas
if (!empty($customStorePages)) {
    $menuLinkOptions['---pages'] = '── Páginas ──';
    foreach ($customStorePages as $customPage) {
        $menuLinkOptions[$storeBaseUrl . '/pagina/' . $customPage['slug']] = $customPage['title'];
    }
}

// Opção de link customizado
$menuLinkOptions['---custom'] = '── Link Externo ──';
$menuLinkOptions['custom'] = '🔗 Link Personalizado...';

// Paletas de cores disponíveis
$colorPalettes = [
    // Paletas para Barbearia/Salão (Escuras)
    'dark' => [
        'gold-classic' => [
            'name' => 'Ouro Clássico',
            'icon' => 'solar:crown-bold',
            'colors' => ['#CCA43B', '#8B7355', '#D4AF37', '#0A0A0A', '#151515', '#FFFFFF', '#B0B0B0']
        ],
        'neon-barber' => [
            'name' => 'Neon Barber',
            'icon' => 'solar:bolt-bold',
            'colors' => ['#00F5FF', '#FF00E5', '#00FF88', '#0D0D0D', '#1A1A2E', '#FFFFFF', '#A0A0B0']
        ],
        'royal-blue' => [
            'name' => 'Azul Royal',
            'icon' => 'solar:stars-bold',
            'colors' => ['#4169E1', '#1E3A8A', '#60A5FA', '#0F172A', '#1E293B', '#F8FAFC', '#94A3B8']
        ],
        'emerald-dark' => [
            'name' => 'Esmeralda',
            'icon' => 'solar:leaf-bold',
            'colors' => ['#10B981', '#047857', '#34D399', '#0A0A0A', '#14231A', '#FFFFFF', '#9CA3AF']
        ],
        'crimson-night' => [
            'name' => 'Carmim Noturno',
            'icon' => 'solar:fire-bold',
            'colors' => ['#DC2626', '#991B1B', '#F87171', '#0F0F0F', '#1F1515', '#FFFFFF', '#B0A0A0']
        ],
        'purple-reign' => [
            'name' => 'Roxo Imperial',
            'icon' => 'solar:magic-stick-bold',
            'colors' => ['#8B5CF6', '#7C3AED', '#A78BFA', '#0F0A1A', '#1E1530', '#F8FAFC', '#A78BFA']
        ],
    ],
    // Paletas para Barbearia/Salão (Claras)
    'light' => [
        'rose-beauty' => [
            'name' => 'Rosé Beauty',
            'icon' => 'mdi:flower-tulip',
            'colors' => ['#D4A5A5', '#B8860B', '#E8C4C4', '#FDF8F5', '#FFFFFF', '#2D2D2D', '#6B6B6B']
        ],
        'ocean-breeze' => [
            'name' => 'Brisa do Mar',
            'icon' => 'solar:water-bold',
            'colors' => ['#0EA5E9', '#0284C7', '#38BDF8', '#F0F9FF', '#FFFFFF', '#0C4A6E', '#64748B']
        ],
        'lavender-spa' => [
            'name' => 'Lavanda Spa',
            'icon' => 'solar:moon-stars-bold',
            'colors' => ['#A855F7', '#9333EA', '#C084FC', '#FAF5FF', '#FFFFFF', '#3B0764', '#7C3AED']
        ],
        'mint-fresh' => [
            'name' => 'Menta Fresh',
            'icon' => 'solar:leaf-bold',
            'colors' => ['#14B8A6', '#0D9488', '#2DD4BF', '#F0FDFA', '#FFFFFF', '#134E4A', '#5EEAD4']
        ],
        'coral-sunset' => [
            'name' => 'Coral Sunset',
            'icon' => 'solar:sun-bold',
            'colors' => ['#F97316', '#EA580C', '#FB923C', '#FFF7ED', '#FFFFFF', '#431407', '#FDBA74']
        ],
        'blush-pink' => [
            'name' => 'Blush Pink',
            'icon' => 'solar:heart-bold',
            'colors' => ['#EC4899', '#DB2777', '#F472B6', '#FDF2F8', '#FFFFFF', '#4A044E', '#F9A8D4']
        ],
    ],
    // Paletas para Loja/Varejo
    'retail-light' => [
        'modern-blue' => [
            'name' => 'Azul Moderno',
            'icon' => 'solar:bag-3-bold',
            'colors' => ['#2563EB', '#1D4ED8', '#10B981', '#FAFBFC', '#FFFFFF', '#111827', '#6B7280']
        ],
        'forest-green' => [
            'name' => 'Verde Floresta',
            'icon' => 'solar:tree-bold',
            'colors' => ['#16A34A', '#15803D', '#22C55E', '#F0FDF4', '#FFFFFF', '#14532D', '#4ADE80']
        ],
        'warm-orange' => [
            'name' => 'Laranja Quente',
            'icon' => 'solar:fire-bold',
            'colors' => ['#EA580C', '#C2410C', '#F97316', '#FFF7ED', '#FFFFFF', '#431407', '#FB923C']
        ],
        'elegant-gray' => [
            'name' => 'Cinza Elegante',
            'icon' => 'solar:diploma-bold',
            'colors' => ['#475569', '#334155', '#64748B', '#F8FAFC', '#FFFFFF', '#0F172A', '#94A3B8']
        ],
        'cherry-red' => [
            'name' => 'Vermelho Cereja',
            'icon' => 'solar:tag-price-bold',
            'colors' => ['#DC2626', '#B91C1C', '#EF4444', '#FEF2F2', '#FFFFFF', '#450A0A', '#FCA5A5']
        ],
        'ocean-teal' => [
            'name' => 'Oceano Teal',
            'icon' => 'solar:water-bold',
            'colors' => ['#0891B2', '#0E7490', '#06B6D4', '#ECFEFF', '#FFFFFF', '#164E63', '#67E8F9']
        ],
    ],
    // Paletas para Loja/Varejo (Escuras)
    'retail-dark' => [
        'purple-luxury' => [
            'name' => 'Roxo Luxo',
            'icon' => 'solar:crown-bold',
            'colors' => ['#8B5CF6', '#7C3AED', '#F59E0B', '#0F172A', '#1E293B', '#F1F5F9', '#94A3B8']
        ],
        'midnight-gold' => [
            'name' => 'Ouro Meia-Noite',
            'icon' => 'solar:moon-bold',
            'colors' => ['#EAB308', '#CA8A04', '#FDE047', '#0A0A0A', '#171717', '#FAFAFA', '#A3A3A3']
        ],
        'cyber-pink' => [
            'name' => 'Cyber Pink',
            'icon' => 'solar:bolt-bold',
            'colors' => ['#EC4899', '#DB2777', '#22D3EE', '#0F0F1A', '#1A1A2E', '#F8FAFC', '#A78BFA']
        ],
        'matrix-green' => [
            'name' => 'Matrix Green',
            'icon' => 'solar:code-bold',
            'colors' => ['#22C55E', '#16A34A', '#4ADE80', '#0A0F0A', '#0F1A0F', '#F0FDF4', '#86EFAC']
        ],
        'fire-ember' => [
            'name' => 'Brasa Ardente',
            'icon' => 'solar:fire-bold',
            'colors' => ['#F97316', '#EA580C', '#EF4444', '#0C0A09', '#1C1917', '#FAFAF9', '#A8A29E']
        ],
        'arctic-blue' => [
            'name' => 'Azul Ártico',
            'icon' => 'solar:snowflake-bold',
            'colors' => ['#06B6D4', '#0891B2', '#38BDF8', '#0C1929', '#0F2942', '#F0F9FF', '#7DD3FC']
        ],
    ],
];

// Configurações padrão dos templates
$defaultTemplateSettings = [
    'barber-classic' => [
        'name' => 'Barbearia Clássica',
        'description' => 'Estilo clássico e elegante para barbearias',
        'colors' => [
            'primary' => '#CCA43B',
            'secondary' => '#8B7355',
            'accent' => '#D4AF37',
            'bg' => '#0A0A0A',
            'card' => '#151515',
            'text' => '#FFFFFF',
            'text_secondary' => '#B0B0B0'
        ],
        'sections' => [
            'hero' => ['name' => 'Banner Principal', 'enabled' => true],
            'services' => ['name' => 'Serviços', 'enabled' => true],
            'professionals' => ['name' => 'Profissionais', 'enabled' => true],
            'gallery' => ['name' => 'Galeria', 'enabled' => true],
            'testimonials' => ['name' => 'Depoimentos', 'enabled' => true],
            'location' => ['name' => 'Localização', 'enabled' => true],
            'contact' => ['name' => 'Contato/WhatsApp', 'enabled' => true]
        ]
    ],
    'salon-beauty' => [
        'name' => 'Salão de Beleza',
        'description' => 'Visual suave e moderno para salões de beleza',
        'colors' => [
            'primary' => '#D4A5A5',
            'secondary' => '#B8860B',
            'accent' => '#E8C4C4',
            'bg' => '#FDF8F5',
            'card' => '#FFFFFF',
            'text' => '#2D2D2D',
            'text_secondary' => '#6B6B6B'
        ],
        'sections' => [
            'hero' => ['name' => 'Banner Principal', 'enabled' => true],
            'services' => ['name' => 'Serviços', 'enabled' => true],
            'professionals' => ['name' => 'Profissionais', 'enabled' => true],
            'gallery' => ['name' => 'Galeria', 'enabled' => true],
            'testimonials' => ['name' => 'Depoimentos', 'enabled' => true],
            'location' => ['name' => 'Localização', 'enabled' => true],
            'contact' => ['name' => 'Contato/WhatsApp', 'enabled' => true]
        ]
    ],
    'retail-light' => [
        'name' => 'Modern',
        'description' => 'Design moderno e elegante com tons claros. Perfeito para lojas de moda, acessórios e lifestyle.',
        'colors' => [
            'primary' => '#2563EB',
            'secondary' => '#1D4ED8',
            'accent' => '#10B981',
            'bg' => '#FAFBFC',
            'card' => '#FFFFFF',
            'text' => '#111827',
            'text_secondary' => '#6B7280'
        ],
        'sections' => [
            'hero' => ['name' => 'Banner Principal', 'enabled' => true],
            'featured' => ['name' => 'Produtos em Destaque', 'enabled' => true],
            'categories' => ['name' => 'Categorias', 'enabled' => true],
            'new_arrivals' => ['name' => 'Novidades', 'enabled' => true],
            'testimonials' => ['name' => 'Depoimentos', 'enabled' => true],
            'newsletter' => ['name' => 'Newsletter', 'enabled' => true]
        ]
    ],
    'retail-dark' => [
        'name' => 'Premium Escuro',
        'description' => 'Estilo premium e sofisticado para lojas',
        'colors' => [
            'primary' => '#8B5CF6',
            'secondary' => '#7C3AED',
            'accent' => '#F59E0B',
            'bg' => '#0F172A',
            'card' => '#1E293B',
            'text' => '#F1F5F9',
            'text_secondary' => '#94A3B8'
        ],
        'sections' => [
            'hero' => ['name' => 'Banner Principal', 'enabled' => true],
            'featured' => ['name' => 'Produtos em Destaque', 'enabled' => true],
            'categories' => ['name' => 'Categorias', 'enabled' => true],
            'new_arrivals' => ['name' => 'Novidades', 'enabled' => true],
            'testimonials' => ['name' => 'Depoimentos', 'enabled' => true],
            'newsletter' => ['name' => 'Newsletter', 'enabled' => true]
        ]
    ]
];

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

// Mesclar configurações padrão com personalizadas
$templateDefaults = $defaultTemplateSettings[$currentTemplate] ?? $defaultTemplateSettings['barber-classic'];
$currentColors = array_merge($templateDefaults['colors'], $customSettings['colors'] ?? []);
$currentSections = $templateDefaults['sections'];
if (isset($customSettings['sections'])) {
    foreach ($customSettings['sections'] as $key => $value) {
        if (isset($currentSections[$key])) {
            $currentSections[$key]['enabled'] = $value;
        }
    }
}

// Configurações do cabeçalho
$headerSettings = $customSettings['header'] ?? [
    'logo_type' => 'text', // 'text', 'image', 'both'
    'logo_text' => $store['name'] ?? 'Minha Loja',
    'logo_image' => $store['logo'] ?? '',
    'show_search' => true,
    'show_cart' => true,
    'show_wishlist' => true,
    'sticky' => true
];

// Configurações do Hero Banner
$heroSettings = $customSettings['hero'] ?? [
    'type' => 'gradient',
    'title' => 'Bem-vindo à nossa loja',
    'subtitle' => 'Encontre os melhores produtos com os melhores preços',
    'button_text' => 'Ver Produtos',
    'button_link' => '#produtos',
    'show_button' => true,
    'background_image' => '',
    'background_images' => [], // Multiple images for slider
    'background_video' => '',
    'overlay_opacity' => 50,
    'text_align' => 'center',
    'height' => 'medium',
    'slider_autoplay' => true,
    'slider_interval' => 5000
];

// Configurações do Rodapé (Footer)
$footerSettings = $customSettings['footer'] ?? [
    'description' => 'Sua loja online de confiança. Produtos de qualidade com os melhores preços e entrega rápida para todo o Brasil.',
    'links_column' => [
        ['name' => 'Início', 'link' => '#'],
        ['name' => 'Produtos', 'link' => '#produtos'],
        ['name' => 'Ofertas', 'link' => '#ofertas'],
        ['name' => 'Sobre nós', 'link' => '#sobre']
    ],
    'help_column' => [
        ['name' => 'FAQ', 'link' => '#faq'],
        ['name' => 'Entregas', 'link' => '#entregas'],
        ['name' => 'Trocas', 'link' => '#trocas'],
        ['name' => 'Contato', 'link' => '#contato']
    ],
    'show_social' => true,
    'instagram_url' => '',
    'facebook_url' => '',
    'copyright_text' => ''
];

// Seções customizadas da vitrine (com produtos)
$customSections = $customSettings['custom_sections'] ?? [];

// Configurações do Menu de Navegação
// Itens fixos que não podem ser alterados
$fixedMenuItems = [
    ['id' => 1, 'name' => 'Início', 'link' => '#', 'icon' => 'solar:home-2-bold', 'fixed' => true],
    ['id' => 2, 'name' => 'Produtos', 'link' => '/produtos', 'icon' => 'solar:bag-3-bold', 'fixed' => true],
];
// Itens customizáveis do usuário
$customMenuItems = $customSettings['menu'] ?? [
    ['id' => 3, 'name' => 'Categorias', 'link' => '#categorias', 'icon' => 'solar:widget-4-bold'],
    ['id' => 4, 'name' => 'Contato', 'link' => '#contato', 'icon' => 'solar:phone-calling-bold']
];
// Combinar itens fixos com customizáveis
$menuItems = array_merge($fixedMenuItems, $customMenuItems);
// Processar salvamento
$message = '';
$messageType = '';

// Verificar se veio de um redirect após salvar (PRG pattern)
if (isset($_GET['saved'])) {
    $message = 'Configurações salvas com sucesso!';
    $messageType = 'success';
}
if (isset($_GET['reset'])) {
    $message = 'Configurações restauradas para o padrão!';
    $messageType = 'success';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';


    // Ação para resetar cores via AJAX
    if ($action === 'reset_colors') {
        $defaultColors = $defaultTemplateSettings[$currentTemplate]['colors'];
        
        // Buscar configurações atuais
        $currentSettings = [];
        if (!empty($store['template_settings'])) {
            $currentSettings = json_decode($store['template_settings'], true) ?? [];
        }
        
        // Substituir apenas as cores
        $currentSettings['colors'] = $defaultColors;
        
        // Salvar no banco
        $updateStmt = $pdo->prepare("UPDATE stores SET template_settings = ? WHERE id = ?");
        $updateStmt->execute([json_encode($currentSettings), $storeId]);
        
        header('Content-Type: application/json');
        echo json_encode(['success' => true, 'colors' => $defaultColors]);
        exit;
    }

    if ($action === 'save_settings') {
        $newColors = [
            'primary' => $_POST['color_primary'] ?? $templateDefaults['colors']['primary'],
            'secondary' => $_POST['color_secondary'] ?? $templateDefaults['colors']['secondary'],
            'accent' => $_POST['color_accent'] ?? $templateDefaults['colors']['accent'],
            'bg' => $_POST['color_bg'] ?? $templateDefaults['colors']['bg'],
            'card' => $_POST['color_card'] ?? $templateDefaults['colors']['card'],
            'text' => $_POST['color_text'] ?? $templateDefaults['colors']['text'],
            'text_secondary' => $_POST['color_text_secondary'] ?? $templateDefaults['colors']['text_secondary']
        ];

        $newSections = [];
        foreach ($templateDefaults['sections'] as $key => $section) {
            $newSections[$key] = isset($_POST['section_' . $key]);
        }
        
        // Configurações do cabeçalho
        $newHeader = [
            'logo_type' => $_POST['header_logo_type'] ?? 'text',
            'logo_text' => $_POST['header_logo_text'] ?? $store['name'],
            'logo_image' => $headerSettings['logo_image'], // Será atualizado pelo upload
            'show_search' => isset($_POST['header_show_search']),
            'show_cart' => isset($_POST['header_show_cart']),
            'show_wishlist' => isset($_POST['header_show_wishlist']),
            'sticky' => isset($_POST['header_sticky'])
        ];
        
        // Processar upload do logo
        if (isset($_FILES['header_logo']) && $_FILES['header_logo']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../uploads/logos/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            $fileExt = strtolower(pathinfo($_FILES['header_logo']['name'], PATHINFO_EXTENSION));
            $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
            
            if (in_array($fileExt, $allowedExts)) {
                $fileName = 'logo_' . $storeId . '_' . time() . '.' . $fileExt;
                $filePath = $uploadDir . $fileName;
                
                if (move_uploaded_file($_FILES['header_logo']['tmp_name'], $filePath)) {
                    // Deletar logo antigo se existir
                    if (!empty($headerSettings['logo_image']) && file_exists($uploadDir . basename($headerSettings['logo_image']))) {
                        @unlink($uploadDir . basename($headerSettings['logo_image']));
                    }
                    $newHeader['logo_image'] = '/uploads/logos/' . $fileName;
                }
            }
        }


        // Processar itens do menu (apenas itens customizáveis, índice >= 2)
        $newMenu = [];
        if (isset($_POST['menu_name']) && is_array($_POST['menu_name'])) {
            foreach ($_POST['menu_name'] as $idx => $menuName) {
                // Ignorar os 2 primeiros itens (Início e Produtos são fixos)
                if ($idx < 2) continue;
                if (trim($menuName) !== '') {
                    $newMenu[] = [
                        'id' => $idx + 1,
                        'name' => $menuName,
                        'link' => $_POST['menu_link'][$idx] ?? '#',
                        'icon' => $_POST['menu_icon'][$idx] ?? 'solar:home-2-bold'
                    ];
                }
            }
        }
        // Se não houver itens customizados, usar os padrões
        if (empty($newMenu)) { 
            $newMenu = [
                ['id' => 3, 'name' => 'Categorias', 'link' => '#categorias', 'icon' => 'solar:widget-4-bold'],
                ['id' => 4, 'name' => 'Contato', 'link' => '#contato', 'icon' => 'solar:phone-calling-bold']
            ]; 
        }

        // Configurações do Hero
        $newHero = [
            'type' => $_POST['hero_type'] ?? 'gradient',
            'show_text' => isset($_POST['hero_show_text']),
            'title' => $_POST['hero_title'] ?? 'Descubra produtos incríveis',
            'subtitle' => $_POST['hero_subtitle'] ?? '',
            'button_text' => $_POST['hero_button_text'] ?? 'Ver Produtos',
            'button_link' => $_POST['hero_button_link'] ?? '#produtos',
            'show_button' => isset($_POST['hero_show_button']),
            'background_image' => $heroSettings['background_image'] ?? '',
            'background_images' => $heroSettings['background_images'] ?? [], // Keep existing images
            'background_video' => $_POST['hero_background_video'] ?? '',
            'overlay_opacity' => (int)($_POST['hero_overlay_opacity'] ?? 50),
            'text_align' => $_POST['hero_text_align'] ?? 'left',
            'height' => $_POST['hero_height'] ?? 'medium',
            'slider_autoplay' => isset($_POST['hero_slider_autoplay']),
            'slider_interval' => (int)(($_POST['hero_slider_interval_seconds'] ?? 5) * 1000)
        ];

        // Handle existing images order/removal
        if (isset($_POST['hero_existing_images']) && is_array($_POST['hero_existing_images'])) {
            $newHero['background_images'] = array_values($_POST['hero_existing_images']);
        }

        // Processar upload de múltiplas imagens do hero
        $uploadDir = __DIR__ . '/../uploads/heroes/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

        if (isset($_FILES['hero_images']) && is_array($_FILES['hero_images']['name'])) {
            foreach ($_FILES['hero_images']['name'] as $idx => $fileName) {
                if ($_FILES['hero_images']['error'][$idx] === UPLOAD_ERR_OK) {
                    $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
                    if (in_array($fileExt, $allowedExts)) {
                        $newFileName = 'hero_' . $storeId . '_' . time() . '_' . $idx . '.' . $fileExt;
                        $filePath = $uploadDir . $newFileName;
                        if (move_uploaded_file($_FILES['hero_images']['tmp_name'][$idx], $filePath)) {
                            $newHero['background_images'][] = '/uploads/heroes/' . $newFileName;
                        }
                    }
                }
            }
        }

        // Fallback: use first image as background_image for compatibility
        if (!empty($newHero['background_images'])) {
            $newHero['background_image'] = $newHero['background_images'][0];
        }


        // Configurações do Rodapé
        $newFooter = [
            'description' => $_POST['footer_description'] ?? $footerSettings['description'],
            'links_column' => [],
            'help_column' => [],
            'show_social' => isset($_POST['footer_show_social']),
            'instagram_url' => $_POST['footer_instagram_url'] ?? '',
            'facebook_url' => $_POST['footer_facebook_url'] ?? '',
            'copyright_text' => $_POST['footer_copyright_text'] ?? ''
        ];

        // Processar links do footer
        if (!empty($_POST['footer_link_name'])) {
            foreach ($_POST['footer_link_name'] as $idx => $linkName) {
                if (!empty(trim($linkName))) {
                    $newFooter['links_column'][] = [
                        'name' => $linkName,
                        'link' => $_POST['footer_link_url'][$idx] ?? '#'
                    ];
                }
            }
        }
        if (empty($newFooter['links_column'])) { $newFooter['links_column'] = $footerSettings['links_column']; }

        // Processar links de ajuda do footer
        if (!empty($_POST['footer_help_name'])) {
            foreach ($_POST['footer_help_name'] as $idx => $helpName) {
                if (!empty(trim($helpName))) {
                    $newFooter['help_column'][] = [
                        'name' => $helpName,
                        'link' => $_POST['footer_help_url'][$idx] ?? '#'
                    ];
                }
            }
        }
        if (empty($newFooter['help_column'])) { $newFooter['help_column'] = $footerSettings['help_column']; }

        // Processar seções customizadas
        $newCustomSections = [];
        if (isset($_POST['section_title']) && is_array($_POST['section_title'])) {
            foreach ($_POST['section_title'] as $idx => $title) {
                if (trim($title) !== '') {
                    $sectionProducts = [];
                    if (isset($_POST['section_products'][$idx]) && !empty($_POST['section_products'][$idx])) {
                        // Produtos vêm como string separada por vírgulas
                        $productsValue = $_POST['section_products'][$idx];
                        if (is_array($productsValue)) {
                            $sectionProducts = array_map('intval', $productsValue);
                        } else {
                            $sectionProducts = array_map('intval', array_filter(explode(',', $productsValue)));
                        }
                    }
                    $newCustomSections[] = [
                        'id' => $idx + 1,
                        'title' => trim($title),
                        'subtitle' => $_POST['section_subtitle'][$idx] ?? '',
                        'products' => $sectionProducts,
                        'enabled' => isset($_POST['section_enabled'][$idx])
                    ];
                }
            }
        }
        $settingsToSave = json_encode([
            'colors' => $newColors,
            'sections' => $newSections,
            'header' => $newHeader,
            'menu' => $newMenu,
            'hero' => $newHero,
            'footer' => $newFooter,
            'custom_sections' => $newCustomSections
        ]);

        $updateStmt = $pdo->prepare("UPDATE stores SET template_settings = ?, updated_at = NOW() WHERE id = ?");
        $updateStmt->execute([$settingsToSave, $storeId]);

        // Redirect PRG para evitar reenvio do formulário
        $activeTab = $_POST['active_tab'] ?? 'colors';
        header('Location: /pages/template-editor.php?saved=1&tab=' . urlencode($activeTab));
        exit;
    } elseif ($action === 'reset_defaults') {
        $updateStmt = $pdo->prepare("UPDATE stores SET template_settings = NULL, updated_at = NOW() WHERE id = ?");
        $updateStmt->execute([$storeId]);

        // Redirect PRG para evitar reenvio do formulário
        header('Location: /pages/template-editor.php?reset=1');
        exit;
    }
}

$pageTitle = 'Editar Template';
include __DIR__ . '/../includes/dashboard-header.php';
include __DIR__ . '/../includes/responsive-styles.php';
?>

<!-- Template Editor Styles (External) -->
<link rel="stylesheet" href="/assets/css/template-editor.css?v=<?php echo time(); ?>">

<main class="main-content">
    <div class="page-header" style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem;">
        <div>
            <h1><iconify-icon icon="solar:palette-2-bold"></iconify-icon> Editar Template</h1>
            <p>Personalize as cores e seções do seu template</p>
        </div>
        <a href="/pages/templates.php" class="btn btn-secondary">
            <iconify-icon icon="solar:arrow-left-bold"></iconify-icon>
            Voltar
        </a>
    </div>

    <?php if ($message): ?>
    <div class="alert alert-<?php echo $messageType; ?>">
        <iconify-icon icon="<?php echo $messageType === 'success' ? 'solar:check-circle-bold' : 'solar:danger-circle-bold'; ?>"></iconify-icon>
        <?php echo $message; ?>
    </div>
    <?php endif; ?>

    <!-- Template Info -->
    <div class="template-info-card">
        <div class="template-info-icon" style="background: <?php echo $currentColors['primary']; ?>20; color: <?php echo $currentColors['primary']; ?>;">
            <iconify-icon icon="<?php echo $isRetail ? 'solar:bag-3-bold' : ($currentTemplate === 'salon-beauty' ? 'mdi:hair-dryer' : 'solar:scissors-bold'); ?>"></iconify-icon>
        </div>
        <div class="template-info-details">
            <h3><?php echo htmlspecialchars($templateDefaults['name']); ?></h3>
            <p><?php echo htmlspecialchars($templateDefaults['description'] ?? 'Personalize as cores e seções do seu template'); ?></p>
        </div>
    </div>

    <form method="POST" id="editorForm" enctype="multipart/form-data">
        <input type="hidden" name="active_tab" id="activeTabInput" value="<?php echo $_POST['active_tab'] ?? 'colors'; ?>">
        <input type="hidden" name="active_section" id="activeSectionInput" value="<?php echo $_POST['active_section'] ?? ''; ?>">
        <input type="hidden" name="action" value="save_settings">

        <div class="editor-layout">
            <!-- Preview Panel - Agora na direita -->
            <div class="editor-container">
                <!-- Editor Panel com Abas -->
                <div class="editor-panel">
                <div class="editor-tabs-container">
                    <!-- Menu de Abas -->
                    <div class="editor-tabs-menu">
                        <div class="editor-tab-item active" onclick="switchTab('colors')" data-tab="colors">
                            <iconify-icon icon="solar:pallete-2-bold"></iconify-icon>
                            <span>Cores</span>
                        </div>
                        <div class="editor-tab-item" onclick="switchTab('sections')" data-tab="sections">
                            <iconify-icon icon="solar:widget-bold"></iconify-icon>
                            <span>Seções</span>
                        </div>
                        <div class="editor-tab-item" onclick="switchTab('header')" data-tab="header">
                            <iconify-icon icon="solar:hamburger-menu-bold"></iconify-icon>
                            <span>Cabeçalho</span>
                            
                        </div>
                        <div class="editor-tab-item" onclick="switchTab('hero')" data-tab="hero">
                            <iconify-icon icon="solar:gallery-wide-bold"></iconify-icon>
                            <span>Destaque</span>
                            
                        </div>
                        <div class="editor-tab-item" onclick="switchTab('footer')" data-tab="footer">
                            <iconify-icon icon="solar:align-bottom-bold"></iconify-icon>
                            <span>Rodapé</span>
                            
                        </div>
                        <div class="editor-tab-item" onclick="switchTab('pages')" data-tab="pages">
                            <iconify-icon icon="solar:documents-bold"></iconify-icon>
                            <span>Páginas</span>
                        </div>
                    </div>
                    
                    <!-- Conteúdo das Abas -->
                    <div class="editor-tabs-content">
                        <!-- Aba: Cores -->
                        <div class="editor-tab-panel active" id="tab-colors">
                            <div class="editor-tab-panel-header">
                                <iconify-icon icon="solar:palette-2-bold"></iconify-icon>
                                <div>
                                    <h3>Cores do Template</h3>
                                    <p>Escolha uma paleta ou personalize cada cor</p>
                                </div>
                            </div>
                        
                        <!-- Paletas de Cores -->
                        <div class="palettes-section">
                            <div class="palettes-section-title">
                                <iconify-icon icon="solar:palette-bold"></iconify-icon>
                                Escolha uma Paleta
                            </div>
                            
                            <?php
                            // Determinar qual conjunto de paletas mostrar
                            if ($isRetail) {
                                $isDarkTemplate = strpos($currentTemplate, 'dark') !== false;
                                $availablePalettes = $isDarkTemplate ? $colorPalettes['retail-dark'] : $colorPalettes['retail-light'];
                                $paletteType = $isDarkTemplate ? 'retail-dark' : 'retail-light';
                            } else {
                                $isDarkTemplate = ($currentTemplate === 'barber-classic' || strpos($currentColors['bg'], '#0') === 0 || strpos($currentColors['bg'], '#1') === 0);
                                $availablePalettes = $isDarkTemplate ? $colorPalettes['dark'] : $colorPalettes['light'];
                                $paletteType = $isDarkTemplate ? 'dark' : 'light';
                            }
                            ?>
                            
                            <div class="palettes-grid">
                                <?php foreach ($availablePalettes as $paletteKey => $palette): 
                                    $colors = $palette['colors'];
                                    $isActive = (strtolower($colors[0]) === strtolower($currentColors['primary']) && strtolower($colors[3]) === strtolower($currentColors['bg']));
                                ?>
                                <div class="palette-card <?php echo $isActive ? 'active' : ''; ?>" 
                                     onclick="applyPalette('<?php echo $paletteKey; ?>', <?php echo htmlspecialchars(json_encode($colors)); ?>)"
                                     data-palette="<?php echo $paletteKey; ?>">
                                    <div class="palette-header">
                                        <div class="palette-icon" style="background: <?php echo $colors[0]; ?>; color: <?php echo $colors[5]; ?>;">
                                            <iconify-icon icon="<?php echo $palette['icon']; ?>"></iconify-icon>
                                        </div>
                                        <span class="palette-name"><?php echo $palette['name']; ?></span>
                                    </div>
                                    <div class="palette-colors">
                                        <?php foreach ($colors as $color): ?>
                                        <div class="palette-color-strip" style="background: <?php echo $color; ?>;"></div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <!-- Toggle para cores avançadas -->

                            <!-- Botão para aplicar paleta selecionada -->
                            <button type="button" id="applyPaletteBtn" class="btn btn-primary btn-sm" onclick="applySelectedPalette()" style="display: none; margin-top: 0.75rem; width: 100%;">
                                <iconify-icon icon="solar:palette-bold"></iconify-icon>
                                Aplicar Esta Paleta
                            </button>
                            <div class="advanced-colors-toggle" onclick="toggleAdvancedColors()">
                                <iconify-icon icon="solar:tuning-2-bold"></iconify-icon>
                                <span>Personalizar cores individualmente</span>
                                <iconify-icon icon="solar:alt-arrow-down-bold"></iconify-icon>
                            </div>
                        </div>
                        
                        <!-- Cores individuais (avançado) -->
                        <div class="advanced-colors-content" id="advancedColors">
                            <div class="color-grid">
                            <div class="color-item">
                                <label class="color-label">Cor Principal</label>
                                <div class="color-input-wrapper">
                                    <div class="color-preview" id="preview_primary" style="background: <?php echo $currentColors['primary']; ?>;"></div>
                                    <input type="color" name="color_primary" id="color_primary" value="<?php echo $currentColors['primary']; ?>" onchange="updateColorPreview('primary')">
                                    <input type="text" class="color-hex" id="hex_primary" value="<?php echo $currentColors['primary']; ?>" oninput="updateColorFromHex('primary')">
                                </div>
                            </div>

                            <div class="color-item">
                                <label class="color-label">Cor Secundária</label>
                                <div class="color-input-wrapper">
                                    <div class="color-preview" id="preview_secondary" style="background: <?php echo $currentColors['secondary']; ?>;"></div>
                                    <input type="color" name="color_secondary" id="color_secondary" value="<?php echo $currentColors['secondary']; ?>" onchange="updateColorPreview('secondary')">
                                    <input type="text" class="color-hex" id="hex_secondary" value="<?php echo $currentColors['secondary']; ?>" oninput="updateColorFromHex('secondary')">
                                </div>
                            </div>

                            <div class="color-item">
                                <label class="color-label">Cor de Destaque</label>
                                <div class="color-input-wrapper">
                                    <div class="color-preview" id="preview_accent" style="background: <?php echo $currentColors['accent']; ?>;"></div>
                                    <input type="color" name="color_accent" id="color_accent" value="<?php echo $currentColors['accent']; ?>" onchange="updateColorPreview('accent')">
                                    <input type="text" class="color-hex" id="hex_accent" value="<?php echo $currentColors['accent']; ?>" oninput="updateColorFromHex('accent')">
                                </div>
                            </div>

                            <div class="color-item">
                                <label class="color-label">Fundo</label>
                                <div class="color-input-wrapper">
                                    <div class="color-preview" id="preview_bg" style="background: <?php echo $currentColors['bg']; ?>;"></div>
                                    <input type="color" name="color_bg" id="color_bg" value="<?php echo $currentColors['bg']; ?>" onchange="updateColorPreview('bg')">
                                    <input type="text" class="color-hex" id="hex_bg" value="<?php echo $currentColors['bg']; ?>" oninput="updateColorFromHex('bg')">
                                </div>
                            </div>

                            <div class="color-item">
                                <label class="color-label">Cards/Blocos</label>
                                <div class="color-input-wrapper">
                                    <div class="color-preview" id="preview_card" style="background: <?php echo $currentColors['card']; ?>;"></div>
                                    <input type="color" name="color_card" id="color_card" value="<?php echo $currentColors['card']; ?>" onchange="updateColorPreview('card')">
                                    <input type="text" class="color-hex" id="hex_card" value="<?php echo $currentColors['card']; ?>" oninput="updateColorFromHex('card')">
                                </div>
                            </div>

                            <div class="color-item">
                                <label class="color-label">Texto Principal</label>
                                <div class="color-input-wrapper">
                                    <div class="color-preview" id="preview_text" style="background: <?php echo $currentColors['text']; ?>;"></div>
                                    <input type="color" name="color_text" id="color_text" value="<?php echo $currentColors['text']; ?>" onchange="updateColorPreview('text')">
                                    <input type="text" class="color-hex" id="hex_text" value="<?php echo $currentColors['text']; ?>" oninput="updateColorFromHex('text')">
                                </div>
                            </div>

                            <div class="color-item">
                                <label class="color-label">Texto Secundário</label>
                                <div class="color-input-wrapper">
                                    <div class="color-preview" id="preview_text_secondary" style="background: <?php echo $currentColors['text_secondary']; ?>;"></div>
                                    <input type="color" name="color_text_secondary" id="color_text_secondary" value="<?php echo $currentColors['text_secondary']; ?>" onchange="updateColorPreview('text_secondary')">
                                    <input type="text" class="color-hex" id="hex_text_secondary" value="<?php echo $currentColors['text_secondary']; ?>" oninput="updateColorFromHex('text_secondary')">
                                </div>
                            </div>
                        </div>
                        </div><!-- /advanced-colors-content -->

                        <!-- Botão Restaurar Cores Padrão -->
                        <div style="margin-top: 1rem; text-align: center;">
                            <button type="button" class="btn btn-secondary btn-sm" onclick="resetColorsToDefault()">
                                <iconify-icon icon="solar:refresh-bold"></iconify-icon>
                                Restaurar Cores Padrão
                            </button>
                        </div>
                        </div><!-- /tab-colors -->
                        
                        <!-- Aba: Seções -->
                        <div class="editor-tab-panel" id="tab-sections">
                            <div class="editor-tab-panel-header">
                                <iconify-icon icon="solar:widget-bold"></iconify-icon>
                                <div>
                                    <h3>Seções da Vitrine</h3>
                                    <p>Crie seções personalizadas com produtos para sua loja</p>
                                </div>
                            </div>

                            <!-- Lista de Seções Customizadas -->
                            <div class="editor-section">
                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                                    <label class="form-label" style="margin: 0;">
                                        <iconify-icon icon="solar:layers-bold" style="margin-right: 0.5rem;"></iconify-icon>
                                        Suas Seções
                                    </label>
                                    <button type="button" class="btn btn-primary btn-sm" onclick="addCustomSection()">
                                        <iconify-icon icon="solar:add-circle-bold"></iconify-icon> Nova Seção
                                    </button>
                                </div>
                                
                                <div id="customSectionsContainer">
                                    <?php if (empty($customSections)): ?>
                                    <div class="empty-sections-message" style="text-align: center; padding: 2rem; background: var(--color-card); border-radius: 0.5rem; border: 2px dashed var(--color-border);">
                                        <iconify-icon icon="solar:layers-minimalistic-bold" style="font-size: 3rem; color: var(--color-text-secondary); margin-bottom: 1rem; display: block;"></iconify-icon>
                                        <p style="color: var(--color-text-secondary); margin: 0;">Nenhuma seção criada ainda.<br>Clique em "Nova Seção" para começar.</p>
                                    </div>
                                    <?php else: ?>
                                    <?php foreach ($customSections as $idx => $section): ?>
                                    <div class="custom-section-item" data-index="<?php echo $idx; ?>" style="background: var(--color-card); border-radius: 0.5rem; padding: 1rem; margin-bottom: 1rem; border: 1px solid var(--color-border);">
                                        <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 1rem;">
                                            <div style="flex: 1;">
                                                <div style="display: flex; gap: 0.5rem; margin-bottom: 0.5rem;">
                                                    <input type="text" name="section_title[<?php echo $idx; ?>]" class="form-input" value="<?php echo htmlspecialchars($section['title']); ?>" placeholder="Título da seção" style="flex: 2;">
                                                    <input type="text" name="section_subtitle[<?php echo $idx; ?>]" class="form-input" value="<?php echo htmlspecialchars($section['subtitle'] ?? ''); ?>" placeholder="Subtítulo (opcional)" style="flex: 2;">
                                                </div>
                                            </div>
                                            <div style="display: flex; align-items: center; gap: 0.5rem; margin-left: 0.5rem;">
                                                <label class="custom-toggle-switch" title="Ativar/Desativar">
                                                    <input type="checkbox" name="section_enabled[<?php echo $idx; ?>]" value="1" <?php echo ($section['enabled'] ?? true) ? 'checked' : ''; ?>>
                                                    <span class="custom-toggle-slider"></span>
                                                </label>
                                                <button type="button" class="btn btn-icon btn-danger" onclick="removeCustomSection(this)" title="Remover seção">
                                                    <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                                                </button>
                                            </div>
                                        </div>
                                        
                                        <div class="section-products-selector">
                                            <label class="form-label-sm" style="font-size: 0.85rem; margin-bottom: 0.75rem; display: flex; align-items: center; justify-content: space-between;">
                                                <span>
                                                    <iconify-icon icon="solar:bag-3-bold" style="margin-right: 0.25rem;"></iconify-icon>
                                                    Produtos desta seção
                                                </span>
                                                <span class="selected-count-badge" style="background: var(--color-primary); color: #fff; padding: 0.2rem 0.6rem; border-radius: 1rem; font-size: 0.75rem;">
                                                    <?php echo count($section['products'] ?? []); ?> selecionados
                                                </span>
                                            </label>
                                            
                                            <!-- Campo hidden para armazenar IDs selecionados -->
                                            <input type="hidden" name="section_products[<?php echo $idx; ?>]" class="selected-products-input" value="<?php echo implode(',', $section['products'] ?? []); ?>">
                                            
                                            <!-- Área de produtos selecionados (tags) -->
                                            <div class="selected-products-area" style="display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 0.75rem; min-height: 50px; padding: 0.75rem; background: var(--color-bg); border-radius: 0.5rem; border: 2px dashed var(--color-border);">
                                                <?php 
                                                $selectedIds = $section['products'] ?? [];
                                                if (empty($selectedIds)): ?>
                                                <span class="empty-hint" style="color: var(--color-text-secondary); font-size: 0.85rem; width: 100%; text-align: center;">
                                                    <iconify-icon icon="solar:box-minimalistic-bold" style="font-size: 1.5rem; display: block; margin-bottom: 0.25rem;"></iconify-icon>
                                                    Toque em "Selecionar Produtos" para adicionar
                                                </span>
                                                <?php else:
                                                    foreach ($storeProducts as $prod):
                                                        if (in_array($prod['id'], $selectedIds)):
                                                ?>
                                                <div class="product-tag" data-id="<?php echo $prod['id']; ?>" onclick="removeProductFromSection(this)">
                                                    <?php if (!empty($prod['image_url'])): ?>
                                                    <img src="<?php echo htmlspecialchars($prod['image_url']); ?>" alt="">
                                                    <?php endif; ?>
                                                    <span><?php echo htmlspecialchars($prod['name']); ?></span>
                                                    <div class="remove-btn"><iconify-icon icon="solar:close-bold"></iconify-icon></div>
                                                </div>
                                                <?php 
                                                        endif;
                                                    endforeach;
                                                endif; ?>
                                            </div>
                                            
                                            <!-- Botão para abrir modal de seleção -->
                                            <button type="button" class="advanced-colors-toggle" onclick="openProductSelectorModal(<?php echo $idx; ?>)" style="width: 100%; padding: 0.875rem; border-style: dashed; font-size: 0.95rem;">
                                                <iconify-icon icon="solar:add-square-bold" style="font-size: 1.2rem;"></iconify-icon>
                                                Selecionar Produtos
                                            </button>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Lista de produtos disponíveis (hidden para usar no JS) -->
                            <script>
                            const storeProductsList = <?php echo json_encode($storeProducts); ?>;
                            </script>

                        </div><!-- /tab-sections -->
                        
                        <!-- Aba: Cabeçalho -->
                        <div class="editor-tab-panel" id="tab-header">
                            <div class="editor-tab-panel-header">
                                <iconify-icon icon="solar:hamburger-menu-bold"></iconify-icon>
                                <div>
                                    <h3>Editar Cabeçalho</h3>
                                    <p>Personalize o topo da sua página</p>
                                </div>
                            </div>
                            
                            <!-- Logo da Loja -->
                            <div class="header-editor-section collapsed">
                                <h4 class="header-section-title" onclick="toggleSection(this)">
                                    <iconify-icon icon="solar:gallery-bold"></iconify-icon>
                                    Logo da Loja
                                    <iconify-icon icon="solar:alt-arrow-down-bold" class="collapse-icon"></iconify-icon>
                                </h4>
                                <div class="header-section-content">
                                
                                <!-- Tipo de Logo -->
                                <div class="form-group">
                                    <label class="form-label">Tipo de Logo</label>
                                    <div class="logo-type-options">
                                        <label class="logo-type-option <?php echo $headerSettings['logo_type'] === 'text' ? 'active' : ''; ?>">
                                            <input type="radio" name="header_logo_type" value="text" <?php echo $headerSettings['logo_type'] === 'text' ? 'checked' : ''; ?> onchange="updateLogoType('text')">
                                            <iconify-icon icon="solar:text-bold"></iconify-icon>
                                            <span>Só Texto</span>
                                        </label>
                                        <label class="logo-type-option <?php echo $headerSettings['logo_type'] === 'image' ? 'active' : ''; ?>">
                                            <input type="radio" name="header_logo_type" value="image" <?php echo $headerSettings['logo_type'] === 'image' ? 'checked' : ''; ?> onchange="updateLogoType('image')">
                                            <iconify-icon icon="solar:gallery-minimalistic-bold"></iconify-icon>
                                            <span>Só Imagem</span>
                                        </label>
                                        <label class="logo-type-option <?php echo $headerSettings['logo_type'] === 'both' ? 'active' : ''; ?>">
                                            <input type="radio" name="header_logo_type" value="both" <?php echo $headerSettings['logo_type'] === 'both' ? 'checked' : ''; ?> onchange="updateLogoType('both')">
                                            <iconify-icon icon="solar:widget-2-bold"></iconify-icon>
                                            <span>Imagem + Texto</span>
                                        </label>
                                    </div>
                                </div>
                                
                                <!-- Nome/Texto do Logo -->
                                <div class="form-group" id="logoTextGroup">
                                    <label class="form-label">Nome da Loja</label>
                                    <input type="text" name="header_logo_text" class="form-input" 
                                           value="<?php echo htmlspecialchars($headerSettings['logo_text']); ?>" 
                                           placeholder="Nome da sua loja"
                                           oninput="updateLogoPreview()">
                                </div>
                                
                                <!-- Upload de Logo -->
                                <div class="form-group" id="logoImageGroup">
                                    <label class="form-label">Imagem do Logo</label>
                                    <div class="logo-upload-area">
                                        <div class="logo-preview-box" id="logoPreviewBox">
                                            <?php if (!empty($headerSettings['logo_image'])): ?>
                                            <img src="<?php echo htmlspecialchars($headerSettings['logo_image']); ?>" alt="Logo" id="logoPreviewImg">
                                            <button type="button" class="logo-remove-btn" onclick="removeLogo()">
                                                <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                                            </button>
                                            <?php else: ?>
                                            <div class="logo-placeholder" id="logoPlaceholder">
                                                <iconify-icon icon="solar:gallery-add-bold"></iconify-icon>
                                                <span>Clique para enviar</span>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                        <input type="file" name="header_logo" id="headerLogoInput" accept="image/*" onchange="previewLogo(this)" style="display: none;">
                                        <div class="logo-upload-info">
                                            <button type="button" class="btn btn-secondary btn-sm" onclick="document.getElementById('headerLogoInput').click()">
                                                <iconify-icon icon="solar:upload-bold"></iconify-icon>
                                                <?php echo empty($headerSettings['logo_image']) ? 'Enviar Logo' : 'Trocar Logo'; ?>
                                            </button>
                                            <p class="logo-upload-hint">PNG, JPG, SVG ou WebP. Máx 2MB.</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            </div><!-- fecha header-section-content -->
                            
                            <!-- Elementos do Cabeçalho -->
                            <div class="header-editor-section collapsed">
                                <h4 class="header-section-title" onclick="toggleSection(this)">
                                    <iconify-icon icon="solar:widget-bold"></iconify-icon>
                                    Elementos do Cabeçalho
                                    <iconify-icon icon="solar:alt-arrow-down-bold" class="collapse-icon"></iconify-icon>
                                </h4>
                                <div class="header-section-content">
                                
                                <div class="sections-list">
                                    <div class="section-toggle">
                                        <div class="section-toggle-info">
                                            <div class="section-icon">
                                                <iconify-icon icon="solar:magnifer-bold"></iconify-icon>
                                            </div>
                                            <span class="section-toggle-name">Barra de Busca</span>
                                        </div>
                                        <label class="toggle-switch">
                                            <input type="checkbox" name="header_show_search" <?php echo $headerSettings['show_search'] ? 'checked' : ''; ?>>
                                            <span class="toggle-slider"></span>
                                        </label>
                                    </div>
                                    
                                    <div class="section-toggle">
                                        <div class="section-toggle-info">
                                            <div class="section-icon">
                                                <iconify-icon icon="solar:cart-large-2-bold"></iconify-icon>
                                            </div>
                                            <span class="section-toggle-name">Carrinho</span>
                                        </div>
                                        <label class="toggle-switch">
                                            <input type="checkbox" name="header_show_cart" <?php echo $headerSettings['show_cart'] ? 'checked' : ''; ?>>
                                            <span class="toggle-slider"></span>
                                        </label>
                                    </div>
                                    
                                    <div class="section-toggle">
                                        <div class="section-toggle-info">
                                            <div class="section-icon">
                                                <iconify-icon icon="solar:heart-bold"></iconify-icon>
                                            </div>
                                            <span class="section-toggle-name">Favoritos</span>
                                        </div>
                                        <label class="toggle-switch">
                                            <input type="checkbox" name="header_show_wishlist" <?php echo $headerSettings['show_wishlist'] ? 'checked' : ''; ?>>
                                            <span class="toggle-slider"></span>
                                        </label>
                                    </div>
                                    
                                    <div class="section-toggle">
                                        <div class="section-toggle-info">
                                            <div class="section-icon">
                                                <iconify-icon icon="solar:pin-bold"></iconify-icon>
                                            </div>
                                            <span class="section-toggle-name">Cabeçalho Fixo (Sticky)</span>
                                        </div>
                                        <label class="toggle-switch">
                                            <input type="checkbox" name="header_sticky" <?php echo $headerSettings['sticky'] ? 'checked' : ''; ?>>
                                            <span class="toggle-slider"></span>
                                        </label>
                                    </div>
                                </div>
                            </div><!-- fecha header-section-content elementos -->
                            </div>

                            <!-- Menu de Navegação -->
                            <div class="header-editor-section collapsed">
                                <h4 class="header-section-title" onclick="toggleSection(this)">
                                    <iconify-icon icon="solar:list-bold"></iconify-icon>
                                    Menu de Navegação
                                    <iconify-icon icon="solar:alt-arrow-down-bold" class="collapse-icon"></iconify-icon>
                                </h4>
                                <div class="header-section-content">
                                    <p style="font-size: 0.85rem; color: var(--text-secondary); margin-bottom: 0.5rem;">
                                        Adicione, remova e organize os itens do menu da sua loja.
                                    </p>
                                    <div style="background: rgba(var(--primary-rgb), 0.1); border: 1px dashed rgba(var(--primary-rgb), 0.3); border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem;">
                                        <iconify-icon icon="solar:info-circle-bold" style="color: var(--primary); font-size: 1.2rem;"></iconify-icon>
                                        <span style="font-size: 0.8rem; color: var(--text-secondary);">Os itens <strong style="color: var(--text-primary);">Início</strong> e <strong style="color: var(--text-primary);">Produtos</strong> são fixos e não podem ser alterados.</span>
                                    </div>

                                    <div class="menu-items-list" id="menuItemsList">
                                        <?php foreach ($menuItems as $index => $item): ?>
                                        <?php $isFixed = isset($item['fixed']) && $item['fixed']; ?>
                                        <div class="menu-item-row <?php echo $isFixed ? 'menu-item-fixed' : ''; ?>" data-index="<?php echo $index; ?>" data-fixed="<?php echo $isFixed ? 'true' : 'false'; ?>">
                                            <div class="menu-item-drag" <?php echo $isFixed ? 'style="opacity: 0.3; pointer-events: none;"' : ''; ?>>
                                                <iconify-icon icon="<?php echo $isFixed ? 'solar:lock-bold' : 'solar:hamburger-menu-linear'; ?>"></iconify-icon>
                                            </div>
                                            <div class="menu-item-icon-picker" <?php echo $isFixed ? 'style="pointer-events: none; opacity: 0.7;"' : 'onclick="openIconPicker('.$index.')" title="Escolher ícone"'; ?>>
                                                <iconify-icon icon="<?php echo htmlspecialchars($item['icon'] ?? 'solar:home-2-bold'); ?>" id="menuIcon_<?php echo $index; ?>"></iconify-icon>
                                                <input type="hidden" name="menu_icon[<?php echo $index; ?>]" value="<?php echo htmlspecialchars($item['icon'] ?? 'solar:home-2-bold'); ?>" id="menuIconInput_<?php echo $index; ?>">
                                            </div>
                                            <div class="menu-item-inputs">
                                                <input type="text" name="menu_name[<?php echo $index; ?>]" value="<?php echo htmlspecialchars($item['name'] ?? ''); ?>" placeholder="Nome do item" <?php echo $isFixed ? 'readonly style="background: rgba(255,255,255,0.05); cursor: not-allowed;"' : ''; ?>>
                                                <?php if ($isFixed): ?>
                                                    <input type="hidden" name="menu_link[<?php echo $index; ?>]" value="<?php echo htmlspecialchars($item['link'] ?? '#'); ?>">
                                                    <span class="menu-fixed-link" style="padding: 0.5rem 0.75rem; background: rgba(255,255,255,0.05); border-radius: 6px; color: var(--text-secondary); font-size: 0.85rem; display: flex; align-items: center; gap: 0.5rem;">
                                                        <iconify-icon icon="solar:link-bold"></iconify-icon>
                                                        <?php echo $item['name'] === 'Início' ? 'Página Inicial' : 'Página de Produtos'; ?>
                                                    </span>
                                                <?php else: ?>
                                                    <?php 
                                                    $currentLink = $item['link'] ?? '#';
                                                    $isCustomLink = !isset($menuLinkOptions[$currentLink]) && $currentLink !== '#';
                                                    ?>
                                                    <input type="hidden" name="menu_link[<?php echo $index; ?>]" value="<?php echo htmlspecialchars($currentLink); ?>">
                                                    <select class="menu-link-select" onchange="handleMenuLinkChange(this, <?php echo $index; ?>)">
                                                        <?php foreach ($menuLinkOptions as $linkValue => $linkLabel): ?>
                                                            <?php if (strpos($linkValue, '---') === 0): ?>
                                                                <option disabled>─────────────────</option>
                                                            <?php elseif ($linkValue === 'custom'): ?>
                                                                <option value="custom" <?php echo $isCustomLink ? 'selected' : ''; ?>><?php echo htmlspecialchars($linkLabel); ?></option>
                                                            <?php else: ?>
                                                                <option value="<?php echo htmlspecialchars($linkValue); ?>" <?php echo (!$isCustomLink && $currentLink === $linkValue) ? 'selected' : ''; ?>><?php echo htmlspecialchars($linkLabel); ?></option>
                                                            <?php endif; ?>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <div id="customLinkWrapper_<?php echo $index; ?>" class="custom-link-wrapper" style="display: <?php echo $isCustomLink ? 'flex' : 'none'; ?>; margin-top: 0.5rem;">
                                                        <input type="text" id="customLinkInput_<?php echo $index; ?>" class="custom-link-input" value="<?php echo $isCustomLink ? htmlspecialchars($currentLink) : ''; ?>" placeholder="https://exemplo.com ou /minha-pagina" oninput="updateCustomLink(this, <?php echo $index; ?>)">
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            <div class="menu-item-actions">
                                                <?php if ($isFixed): ?>
                                                    <span style="color: var(--text-secondary); font-size: 0.7rem; padding: 0.25rem 0.5rem; background: rgba(255,255,255,0.05); border-radius: 4px;">FIXO</span>
                                                <?php else: ?>
                                                    <button type="button" class="menu-item-btn delete" onclick="removeMenuItem(<?php echo $index; ?>)" title="Remover">
                                                        <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>

                                    <button type="button" class="add-menu-item-btn" onclick="addMenuItem()">
                                        <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                                        Adicionar Item ao Menu
                                    </button>
                                </div>
                            </div>

                        </div><!-- /tab-header -->

                        <!-- Aba: Destaque/Hero -->
                        <div class="editor-tab-panel" id="tab-hero">
                            <div class="editor-tab-panel-header">
                                <iconify-icon icon="solar:gallery-wide-bold"></iconify-icon>
                                <div>
                                    <h3>Editar Destaque</h3>
                                    <p>Personalize o banner principal</p>
                                </div>
                            </div>
                            
                            
                            <!-- Tipo do Hero -->
                            <div class="editor-section">
                                <h4 class="section-title">Tipo de Fundo</h4>
                                <div class="logo-type-selector">
                                    <label class="logo-type-option <?php echo ($heroSettings['type'] ?? 'gradient') === 'gradient' ? 'active' : ''; ?>">
                                        <input type="radio" name="hero_type" value="gradient" <?php echo ($heroSettings['type'] ?? 'gradient') === 'gradient' ? 'checked' : ''; ?> onchange="updateHeroType('gradient')">
                                        <iconify-icon icon="solar:pallete-2-bold"></iconify-icon>
                                        <span>Gradiente</span>
                                    </label>
                                    <label class="logo-type-option <?php echo ($heroSettings['type'] ?? '') === 'image' ? 'active' : ''; ?>">
                                        <input type="radio" name="hero_type" value="image" <?php echo ($heroSettings['type'] ?? '') === 'image' ? 'checked' : ''; ?> onchange="updateHeroType('image')">
                                        <iconify-icon icon="solar:gallery-bold"></iconify-icon>
                                        <span>Imagem</span>
                                    </label>
                                    <label class="logo-type-option <?php echo ($heroSettings['type'] ?? '') === 'video' ? 'active' : ''; ?>">
                                        <input type="radio" name="hero_type" value="video" <?php echo ($heroSettings['type'] ?? '') === 'video' ? 'checked' : ''; ?> onchange="updateHeroType('video')">
                                        <iconify-icon icon="solar:video-frame-bold"></iconify-icon>
                                        <span>Vídeo</span>
                                    </label>
                                </div>
                            </div>

                            <!-- Upload de Imagens do Hero (Slider) -->
                            <div class="editor-section" id="heroImageGroup" style="display: <?php echo ($heroSettings['type'] ?? 'gradient') === 'image' ? 'block' : 'none'; ?>;">
                                <h4 class="section-title">Imagens do Slider</h4>
                                <p class="upload-hint" style="margin-bottom: 1rem;">Adicione múltiplas imagens para criar um slider animado no banner principal.</p>
                                
                                <!-- Gallery of existing images -->
                                <div class="hero-images-gallery" id="heroImagesGallery" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 0.75rem; margin-bottom: 1rem;">
                                    <?php 
                                    $heroImages = $heroSettings['background_images'] ?? [];
                                    // Fallback to single image if no array
                                    if (empty($heroImages) && !empty($heroSettings['background_image'])) {
                                        $heroImages = [$heroSettings['background_image']];
                                    }
                                    foreach ($heroImages as $idx => $imgUrl): 
                                    ?>
                                    <div class="hero-image-item" data-index="<?php echo $idx; ?>" style="position: relative; aspect-ratio: 16/9; border-radius: 10px; overflow: hidden; border: 2px solid #e5e7eb;">
                                        <img src="<?php echo htmlspecialchars($imgUrl); ?>" alt="Slide <?php echo $idx + 1; ?>" style="width: 100%; height: 100%; object-fit: cover;">
                                        <input type="hidden" name="hero_existing_images[]" value="<?php echo htmlspecialchars($imgUrl); ?>">
                                        <div class="hero-image-actions" style="position: absolute; top: 6px; right: 6px;">
                                            <button type="button" class="hero-img-btn remove" onclick="removeHeroSlideImage(this)" title="Remover" style="width: 28px; height: 28px; border: none; border-radius: 6px; background: #ef4444; color: white; cursor: pointer; display: flex; align-items: center; justify-content: center;">
                                                <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                                            </button>
                                        </div>
                                        <span class="hero-image-number" style="position: absolute; top: 6px; left: 6px; width: 22px; height: 22px; background: var(--primary, #2563eb); color: #fff; border-radius: 50%; font-size: 0.7rem; font-weight: 600; display: flex; align-items: center; justify-content: center;"><?php echo $idx + 1; ?></span>
                                    </div>
                                    <?php endforeach; ?>
                                    
                                    <!-- Add new image button -->
                                    <div class="hero-image-add" onclick="document.getElementById('heroImagesInput').click()" style="aspect-ratio: 16/9; border: 2px dashed #e5e7eb; border-radius: 10px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 0.5rem; cursor: pointer; color: #9ca3af; background: #f3f4f6;">
                                        <iconify-icon icon="solar:add-circle-bold" style="font-size: 1.75rem;"></iconify-icon>
                                        <span style="font-size: 0.8rem; font-weight: 500;">Adicionar</span>
                                    </div>
                                </div>
                                
                                <input type="file" name="hero_images[]" id="heroImagesInput" accept="image/*" multiple style="display: none;" onchange="previewHeroImages(this)">
                                <p class="upload-hint">Recomendado: 1920x600px, máx 5MB cada. Arraste para reordenar.</p>
                                
                                <!-- Slider Settings -->
                                <div class="slider-settings" style="margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid var(--border);">
                                    <h4 class="section-title">Configurações do Slider</h4>
                                    <div class="toggle-item" style="margin-bottom: 1rem;">
                                        <label class="toggle-label">
                                            <input type="checkbox" name="hero_slider_autoplay" value="1" <?php echo ($heroSettings['slider_autoplay'] ?? true) ? 'checked' : ''; ?>>
                                            <span>Reprodução automática</span>
                                        </label>
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label">Intervalo entre slides (segundos)</label>
                                        <input type="number" name="hero_slider_interval_seconds" id="heroSliderIntervalInput" class="form-input" value="<?php echo intval(($heroSettings['slider_interval'] ?? 5000) / 1000); ?>" min="2" max="15" step="1" style="max-width: 120px;">
                                    </div>
                                </div>
                            </div>

                            <!-- URL do Vídeo -->
                            <div class="editor-section" id="heroVideoGroup" style="display: <?php echo ($heroSettings['type'] ?? 'gradient') === 'video' ? 'block' : 'none'; ?>;">
                                <h4 class="section-title">URL do Vídeo</h4>
                                <input type="text" name="hero_background_video" class="form-input" value="<?php echo htmlspecialchars($heroSettings['background_video'] ?? ''); ?>" placeholder="https://exemplo.com/video.mp4">
                                <p class="upload-hint">Use URL direta de vídeo MP4</p>
                            </div>

                            <!-- Opacidade do Overlay -->
                            <div class="editor-section" id="heroOverlayGroup" style="display: <?php echo ($heroSettings['type'] ?? 'gradient') !== 'gradient' ? 'block' : 'none'; ?>;">
                                <h4 class="section-title">Opacidade do Overlay</h4>
                                <div style="display: flex; align-items: center; gap: 1rem;">
                                    <input type="range" name="hero_overlay_opacity" min="0" max="100" value="<?php echo $heroSettings['overlay_opacity'] ?? 50; ?>" style="flex: 1;">
                                    <span id="overlayValue"><?php echo $heroSettings['overlay_opacity'] ?? 50; ?>%</span>
                                </div>
                            </div>

                            <!-- Textos do Hero -->
                            <div class="editor-section">
                                <h4 class="section-title">Textos</h4>
                                <div class="toggle-item" style="margin-bottom: 1rem;">
                                    <label class="toggle-label">
                                        <input type="checkbox" name="hero_show_text" value="1" <?php echo ($heroSettings['show_text'] ?? true) ? 'checked' : ''; ?>>
                                        <span class="toggle-switch"></span>
                                        <span>Mostrar textos</span>
                                    </label>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Título Principal</label>
                                    <input type="text" name="hero_title" class="form-input" value="<?php echo htmlspecialchars($heroSettings['title'] ?? 'Descubra produtos incríveis'); ?>" placeholder="Título do banner">
                                </div>
                                <div class="form-group" style="margin-top: 1rem;">
                                    <label class="form-label">Subtítulo</label>
                                    <textarea name="hero_subtitle" class="form-input" rows="2" placeholder="Descrição do banner"><?php echo htmlspecialchars($heroSettings['subtitle'] ?? ''); ?></textarea>
                                </div>
                            </div>

                            <!-- Botão CTA -->
                            <div class="editor-section">
                                <h4 class="section-title">Botão de Ação</h4>
                                <div class="toggle-item" style="margin-bottom: 1rem;">
                                    <label class="toggle-label">
                                        <input type="checkbox" name="hero_show_button" value="1" <?php echo ($heroSettings['show_button'] ?? true) ? 'checked' : ''; ?>>
                                        <span class="toggle-switch"></span>
                                        <span>Mostrar botão</span>
                                    </label>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Texto do Botão</label>
                                    <input type="text" name="hero_button_text" class="form-input" value="<?php echo htmlspecialchars($heroSettings['button_text'] ?? 'Ver Produtos'); ?>" placeholder="Ver Produtos">
                                </div>
                                <div class="form-group" style="margin-top: 1rem;">
                                    <label class="form-label">Link do Botão</label>
                                    <input type="text" name="hero_button_link" class="form-input" value="<?php echo htmlspecialchars($heroSettings['button_link'] ?? '#produtos'); ?>" placeholder="#produtos">
                                </div>
                            </div>

                            <!-- Alinhamento e Altura -->
                            <div class="editor-section">
                                <h4 class="section-title">Layout</h4>
                                <div class="form-group">
                                    <label class="form-label">Alinhamento do Texto</label>
                                    <select name="hero_text_align" class="form-input">
                                        <option value="left" <?php echo ($heroSettings['text_align'] ?? 'left') === 'left' ? 'selected' : ''; ?>>Esquerda</option>
                                        <option value="center" <?php echo ($heroSettings['text_align'] ?? '') === 'center' ? 'selected' : ''; ?>>Centro</option>
                                        <option value="right" <?php echo ($heroSettings['text_align'] ?? '') === 'right' ? 'selected' : ''; ?>>Direita</option>
                                    </select>
                                </div>
                                <div class="form-group" style="margin-top: 1rem;">
                                    <label class="form-label">Altura do Banner</label>
                                    <select name="hero_height" class="form-input">
                                        <option value="small" <?php echo ($heroSettings['height'] ?? '') === 'small' ? 'selected' : ''; ?>>Pequeno (300px)</option>
                                        <option value="medium" <?php echo ($heroSettings['height'] ?? 'medium') === 'medium' ? 'selected' : ''; ?>>Médio (400px)</option>
                                        <option value="large" <?php echo ($heroSettings['height'] ?? '') === 'large' ? 'selected' : ''; ?>>Grande (500px)</option>
                                        <option value="full" <?php echo ($heroSettings['height'] ?? '') === 'full' ? 'selected' : ''; ?>>Tela cheia</option>
                                    </select>
                                </div>
                            </div>

                        </div><!-- /tab-hero -->
                        
                        <!-- Aba: Rodapé -->
                        <div class="editor-tab-panel" id="tab-footer">
                            <div class="editor-tab-panel-header">
                                <iconify-icon icon="solar:align-bottom-bold"></iconify-icon>
                                <div>
                                    <h3>Editar Rodapé</h3>
                                    <p>Personalize o rodapé da sua página</p>
                                </div>
                            </div>
                            

                            <!-- Descrição do Rodapé -->
                            <div class="editor-section">
                                <label class="form-label">Descrição da Loja</label>
                                <textarea name="footer_description" class="form-input" rows="3" placeholder="Descrição que aparece no rodapé"><?php echo htmlspecialchars($footerSettings['description'] ?? ''); ?></textarea>
                                <small style="color: var(--color-text-secondary); margin-top: 0.25rem; display: block;">Texto que aparece abaixo do logo no rodapé</small>
                            </div>

                            <!-- Links do Footer -->
                            <div class="editor-section">
                                <label class="form-label">
                                    <iconify-icon icon="solar:link-bold" style="margin-right: 0.5rem;"></iconify-icon>
                                    Coluna Links
                                </label>
                                <div id="footerLinksContainer">
                                    <?php foreach ($footerSettings['links_column'] as $idx => $link): ?>
                                    <?php 
                                    $footerLinkUrl = $link['link'] ?? '#';
                                    $isFooterCustomLink = !isset($menuLinkOptions[$footerLinkUrl]) && $footerLinkUrl !== '#' && !empty($footerLinkUrl);
                                    ?>
                                    <div class="footer-link-row" style="display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 0.75rem; align-items: flex-start; padding: 0.75rem; background: rgba(255,255,255,0.02); border-radius: 8px; border: 1px solid var(--border);">
                                        <input type="text" name="footer_link_name[]" class="form-input" value="<?php echo htmlspecialchars($link['name']); ?>" placeholder="Título do Link" style="flex: 1; min-width: 150px;">
                                        <input type="hidden" name="footer_link_url[]" value="<?php echo htmlspecialchars($footerLinkUrl); ?>">
                                        <select class="form-input footer-link-select" onchange="handleFooterLinkChange(this)" style="flex: 1; min-width: 180px;">
                                            <?php foreach ($menuLinkOptions as $linkValue => $linkLabel): ?>
                                                <?php if (strpos($linkValue, '---') === 0): ?>
                                                    <option disabled>─────────────────</option>
                                                <?php elseif ($linkValue === 'custom'): ?>
                                                    <option value="custom" <?php echo $isFooterCustomLink ? 'selected' : ''; ?>><?php echo htmlspecialchars($linkLabel); ?></option>
                                                <?php else: ?>
                                                    <option value="<?php echo htmlspecialchars($linkValue); ?>" <?php echo (!$isFooterCustomLink && $footerLinkUrl === $linkValue) ? 'selected' : ''; ?>><?php echo htmlspecialchars($linkLabel); ?></option>
                                                <?php endif; ?>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="footer-custom-link-wrapper" style="display: <?php echo $isFooterCustomLink ? 'flex' : 'none'; ?>; width: 100%; margin-top: 0.5rem;">
                                            <input type="text" class="form-input footer-custom-link-input" value="<?php echo $isFooterCustomLink ? htmlspecialchars($footerLinkUrl) : ''; ?>" placeholder="https://exemplo.com ou /minha-pagina" oninput="updateFooterCustomLink(this)">
                                        </div>
                                        <button type="button" class="btn btn-icon btn-danger" onclick="this.closest('.footer-link-row').remove()" title="Remover" style="flex-shrink: 0;">
                                            <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                                        </button>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                                <button type="button" class="btn btn-secondary btn-sm" onclick="addFooterLink()">
                                    <iconify-icon icon="solar:add-circle-bold"></iconify-icon> Adicionar Link
                                </button>
                            </div>

                            <!-- Links de Ajuda -->
                            <div class="editor-section">
                                <label class="form-label">
                                    <iconify-icon icon="solar:question-circle-bold" style="margin-right: 0.5rem;"></iconify-icon>
                                    Coluna Ajuda
                                </label>
                                <div id="footerHelpContainer">
                                    <?php foreach ($footerSettings['help_column'] as $idx => $help): ?>
                                    <?php 
                                    $footerHelpUrl = $help['link'] ?? '#';
                                    $isFooterHelpCustomLink = !isset($menuLinkOptions[$footerHelpUrl]) && $footerHelpUrl !== '#' && !empty($footerHelpUrl);
                                    ?>
                                    <div class="footer-link-row" style="display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 0.75rem; align-items: flex-start; padding: 0.75rem; background: rgba(255,255,255,0.02); border-radius: 8px; border: 1px solid var(--border);">
                                        <input type="text" name="footer_help_name[]" class="form-input" value="<?php echo htmlspecialchars($help['name']); ?>" placeholder="Título do Link" style="flex: 1; min-width: 150px;">
                                        <input type="hidden" name="footer_help_url[]" value="<?php echo htmlspecialchars($footerHelpUrl); ?>">
                                        <select class="form-input footer-help-select" onchange="handleFooterHelpChange(this)" style="flex: 1; min-width: 180px;">
                                            <?php foreach ($menuLinkOptions as $linkValue => $linkLabel): ?>
                                                <?php if (strpos($linkValue, '---') === 0): ?>
                                                    <option disabled>─────────────────</option>
                                                <?php elseif ($linkValue === 'custom'): ?>
                                                    <option value="custom" <?php echo $isFooterHelpCustomLink ? 'selected' : ''; ?>><?php echo htmlspecialchars($linkLabel); ?></option>
                                                <?php else: ?>
                                                    <option value="<?php echo htmlspecialchars($linkValue); ?>" <?php echo (!$isFooterHelpCustomLink && $footerHelpUrl === $linkValue) ? 'selected' : ''; ?>><?php echo htmlspecialchars($linkLabel); ?></option>
                                                <?php endif; ?>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="footer-custom-link-wrapper" style="display: <?php echo $isFooterHelpCustomLink ? 'flex' : 'none'; ?>; width: 100%; margin-top: 0.5rem;">
                                            <input type="text" class="form-input footer-custom-link-input" value="<?php echo $isFooterHelpCustomLink ? htmlspecialchars($footerHelpUrl) : ''; ?>" placeholder="https://exemplo.com ou /minha-pagina" oninput="updateFooterCustomLink(this)">
                                        </div>
                                        <button type="button" class="btn btn-icon btn-danger" onclick="this.closest('.footer-link-row').remove()" title="Remover" style="flex-shrink: 0;">
                                            <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                                        </button>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                                <button type="button" class="btn btn-secondary btn-sm" onclick="addFooterHelp()">
                                    <iconify-icon icon="solar:add-circle-bold"></iconify-icon> Adicionar Link
                                </button>
                            </div>
                            <!-- Redes Sociais -->
                            <div class="editor-section">
                                <label class="form-label">
                                    <iconify-icon icon="solar:share-circle-bold" style="margin-right: 0.5rem;"></iconify-icon>
                                    Redes Sociais
                                </label>
                                
                                <div class="form-group" style="margin-bottom: 1rem;">
                                    <label class="toggle-label" style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
                                        <input type="checkbox" name="footer_show_social" value="1" <?php echo ($footerSettings['show_social'] ?? true) ? 'checked' : ''; ?>>
                                        <span>Exibir ícones de redes sociais</span>
                                    </label>
                                </div>

                                <div class="form-group" style="margin-bottom: 0.75rem;">
                                    <label class="form-label-sm">
                                        <iconify-icon icon="mdi:instagram" style="margin-right: 0.5rem; color: #E4405F;"></iconify-icon>
                                        URL do Instagram
                                    </label>
                                    <input type="url" name="footer_instagram_url" class="form-input" value="<?php echo htmlspecialchars($footerSettings['instagram_url'] ?? ''); ?>" placeholder="https://instagram.com/sualoja">
                                </div>

                                <div class="form-group" style="margin-bottom: 0.75rem;">
                                    <label class="form-label-sm">
                                        <iconify-icon icon="mdi:facebook" style="margin-right: 0.5rem; color: #1877F2;"></iconify-icon>
                                        URL do Facebook
                                    </label>
                                    <input type="url" name="footer_facebook_url" class="form-input" value="<?php echo htmlspecialchars($footerSettings['facebook_url'] ?? ''); ?>" placeholder="https://facebook.com/sualoja">
                                </div>
                            </div>

                            <!-- Copyright -->
                            <div class="editor-section">
                                <label class="form-label">
                                    <iconify-icon icon="solar:copyright-bold" style="margin-right: 0.5rem;"></iconify-icon>
                                    Texto de Copyright (opcional)
                                </label>
                                <input type="text" name="footer_copyright_text" class="form-input" value="<?php echo htmlspecialchars($footerSettings['copyright_text'] ?? ''); ?>" placeholder="Deixe vazio para usar o padrão: © 2024 Nome da Loja">
                                <small style="color: var(--color-text-secondary); margin-top: 0.25rem; display: block;">Se deixar vazio, será usado automaticamente: © <?php echo date('Y'); ?> Nome da Loja. Todos os direitos reservados.</small>
                            </div>

                            
                        </div><!-- /tab-footer -->
                        
                        <div class="editor-tab-panel" id="tab-pages">
                            <div class="editor-tab-panel-header">
                                <iconify-icon icon="solar:documents-bold"></iconify-icon>
                                <div>
                                    <h3>Páginas Personalizadas</h3>
                                    <p>Crie páginas como Sobre, Contato, Políticas, etc.</p>
                                </div>
                            </div>
                            
                            <div class="pages-section">
                                <div class="pages-header">
                                    <h4>Suas Páginas</h4>
                                    <button type="button" class="btn btn-primary btn-sm" onclick="openPageModal()">
                                        <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                                        Nova Página
                                    </button>
                                </div>
                                <div class="pages-list" id="pagesList">
                                    <div class="pages-empty">
                                        <iconify-icon icon="solar:document-add-bold"></iconify-icon>
                                        <p>Carregando páginas...</p>
                                    </div>
                                </div>
                            </div>
                    </div>
                        </div><!-- /tab-pages -->
                </div>
                
                <!-- Ações -->
                <div class="editor-actions" style="margin-top: 1.5rem;">
                    <button type="submit" class="btn btn-primary">
                        <iconify-icon icon="solar:diskette-bold"></iconify-icon>
                        Salvar Alterações
                    </button>
                </div>
                </div><!-- /editor-panel -->
            </div><!-- /editor-container -->

        </div><!-- /editor-layout -->
    </form>

    <!-- Form oculto para reset -->
    <form method="POST" id="resetForm" style="display: none;">
        <input type="hidden" name="action" value="reset_defaults">
    </form>
</main>

<!-- Modal de Seleção de Ícone -->
<div class="icon-picker-modal" id="iconPickerModal">
    <div class="icon-picker-content">
        <div class="icon-picker-header">
            <h4>Escolher Ícone</h4>
            <button type="button" class="icon-picker-close" onclick="closeIconPicker()">
                <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
            </button>
        </div>
        <input type="text" class="icon-picker-search" placeholder="Buscar ícone..." oninput="filterIcons(this.value)">
        <div class="icon-picker-grid" id="iconPickerGrid">
            <!-- Ícones serão inseridos via JavaScript -->
        </div>
    </div>
</div>

<script>
// Função para toggle das seções collapse

// Menu link options from PHP
const menuLinkOptions = <?php echo json_encode($menuLinkOptions, JSON_UNESCAPED_UNICODE); ?>;


// ===== MENU EDITOR FUNCTIONS =====
let currentIconTarget = null;
let menuItemCount = document.querySelectorAll('.menu-item-row').length;

// Lista de ícones disponíveis
const availableIcons = [
    'solar:home-2-bold', 'solar:home-angle-bold', 'solar:home-smile-bold',
    'solar:bag-3-bold', 'solar:bag-4-bold', 'solar:bag-heart-bold', 'solar:cart-large-2-bold', 'solar:cart-3-bold',
    'solar:widget-4-bold', 'solar:widget-2-bold', 'solar:widget-5-bold', 'solar:widget-6-bold',
    'solar:phone-calling-bold', 'solar:phone-bold', 'solar:chat-round-dots-bold', 'solar:letter-bold',
    'solar:user-bold', 'solar:users-group-rounded-bold', 'solar:user-heart-bold',
    'solar:heart-bold', 'solar:star-bold', 'solar:bookmark-bold', 'solar:fire-bold',
    'solar:tag-price-bold', 'solar:sale-bold', 'solar:ticket-sale-bold', 'solar:gift-bold',
    'solar:box-bold', 'solar:delivery-bold', 'solar:map-point-bold', 'solar:routing-bold',
    'solar:clock-circle-bold', 'solar:calendar-bold', 'solar:calendar-mark-bold',
    'solar:settings-bold', 'solar:tuning-2-bold', 'solar:filter-bold',
    'solar:info-circle-bold', 'solar:question-circle-bold', 'solar:danger-bold',
    'solar:document-text-bold', 'solar:file-text-bold', 'solar:clipboard-text-bold',
    'solar:gallery-bold', 'solar:camera-bold', 'solar:video-frame-bold',
    'solar:music-notes-bold', 'solar:headphones-bold', 'solar:microphone-bold',
    'solar:crown-bold', 'solar:medal-star-bold', 'solar:cup-star-bold',
    'solar:wallet-bold', 'solar:card-bold', 'solar:money-bag-bold',
    'solar:link-bold', 'solar:share-bold', 'solar:download-bold', 'solar:upload-bold',
    'solar:eye-bold', 'solar:search-bold', 'solar:magnifer-bold',
    'solar:bell-bold', 'solar:alarm-bold', 'solar:notification-unread-bold',
    'solar:lock-bold', 'solar:shield-check-bold', 'solar:verified-check-bold',
    'solar:arrow-right-bold', 'solar:arrow-left-bold', 'solar:arrow-up-bold', 'solar:arrow-down-bold',
    'solar:menu-dots-bold', 'solar:list-bold', 'solar:sort-bold',
    'solar:brush-bold', 'solar:palette-bold', 'solar:magic-stick-bold',
    'solar:scissors-bold', 'solar:ruler-bold', 'solar:pen-bold',
    'solar:laptop-bold', 'solar:smartphone-bold', 'solar:tv-bold',
    'solar:gamepad-bold', 'solar:basketball-bold', 'solar:football-bold',
    'solar:leaf-bold', 'solar:flower-bold', 'solar:sun-bold', 'solar:moon-bold',
    'solar:car-bold', 'solar:bus-bold', 'solar:airplane-bold', 'solar:rocket-bold',
    'solar:buildings-bold', 'solar:city-bold', 'solar:hospital-bold',
    'solar:hamburger-bold', 'solar:cup-hot-bold', 'solar:wineglass-bold',
    'solar:t-shirt-bold', 'solar:hanger-bold', 'solar:sneakers-bold'
];

function openIconPicker(index) {
    currentIconTarget = index;
    const modal = document.getElementById('iconPickerModal');
    const grid = document.getElementById('iconPickerGrid');
    
    grid.innerHTML = availableIcons.map(icon => `
        <div class="icon-picker-item" onclick="selectIcon('${icon}')">
            <iconify-icon icon="${icon}"></iconify-icon>
        </div>
    `).join('');
    
    modal.classList.add('active');
}

function closeIconPicker() {
    document.getElementById('iconPickerModal').classList.remove('active');
    currentIconTarget = null;
}

function selectIcon(iconName) {
    if (currentIconTarget !== null) {
        document.getElementById('menuIcon_' + currentIconTarget).setAttribute('icon', iconName);
        document.getElementById('menuIconInput_' + currentIconTarget).value = iconName;
    }
    closeIconPicker();
}

function filterIcons(search) {
    const grid = document.getElementById('iconPickerGrid');
    const filtered = availableIcons.filter(icon => icon.toLowerCase().includes(search.toLowerCase()));
    
    grid.innerHTML = filtered.map(icon => `
        <div class="icon-picker-item" onclick="selectIcon('${icon}')">
            <iconify-icon icon="${icon}"></iconify-icon>
        </div>
    `).join('');
}

function getMenuLinkOptionsHtml(selectedValue = "#", customUrl = "") {
    let html = "";
    let isCustom = selectedValue.startsWith("http") || (selectedValue.startsWith("/") && !selectedValue.startsWith("/pagina/") && !menuLinkOptions[selectedValue]);
    
    for (const [value, label] of Object.entries(menuLinkOptions)) {
        if (value.startsWith("---")) {
            html += `<option disabled>─────────────────</option>`;
        } else if (value === "custom") {
            const selected = isCustom ? "selected" : "";
            html += `<option value="custom" ${selected}>${label}</option>`;
        } else {
            const selected = (!isCustom && value === selectedValue) ? "selected" : "";
            html += `<option value="${value}" ${selected}>${label}</option>`;
        }
    }
    return html;
}

function handleMenuLinkChange(selectEl, index) {
    const customInputWrapper = document.getElementById(`customLinkWrapper_${index}`);
    const customInput = document.getElementById(`customLinkInput_${index}`);
    const hiddenInput = document.querySelector(`input[name="menu_link[${index}]"]`);
    
    if (selectEl.value === "custom") {
        if (customInputWrapper) customInputWrapper.style.display = "flex";
        if (customInput) customInput.focus();
    } else {
        if (customInputWrapper) customInputWrapper.style.display = "none";
        if (hiddenInput) hiddenInput.value = selectEl.value;
    }
}

function updateCustomLink(input, index) {
    const hiddenInput = document.querySelector(`input[name="menu_link[${index}]"]`);
    if (hiddenInput) {
        hiddenInput.value = input.value || "#";
    }
}
function addMenuItem() {
    const list = document.getElementById('menuItemsList');
    const newIndex = menuItemCount++;

    const newItem = document.createElement('div');
    newItem.className = 'menu-item-row';
    newItem.dataset.index = newIndex;
    newItem.innerHTML = `
        <div class="menu-item-drag">
            <iconify-icon icon="solar:hamburger-menu-linear"></iconify-icon>
        </div>
        <div class="menu-item-icon-picker" onclick="openIconPicker(${newIndex})" title="Escolher ícone">
            <iconify-icon icon="solar:home-2-bold" id="menuIcon_${newIndex}"></iconify-icon>
            <input type="hidden" name="menu_icon[${newIndex}]" value="solar:home-2-bold" id="menuIconInput_${newIndex}">
        </div>
        <div class="menu-item-inputs">
            <input type="text" name="menu_name[${newIndex}]" value="" placeholder="Nome do item">
            <input type="hidden" name="menu_link[${newIndex}]" value="#">
            <select class="menu-link-select" onchange="handleMenuLinkChange(this, ${newIndex})">
                ${getMenuLinkOptionsHtml()}
            </select>
            <div id="customLinkWrapper_${newIndex}" class="custom-link-wrapper" style="display: none; margin-top: 0.5rem;">
                <input type="text" id="customLinkInput_${newIndex}" class="custom-link-input" placeholder="https://exemplo.com ou /minha-pagina" oninput="updateCustomLink(this, ${newIndex})">
            </div>
        </div>
        <div class="menu-item-actions">
            <button type="button" class="menu-item-btn delete" onclick="removeMenuItem(${newIndex})" title="Remover">
                <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
            </button>
        </div>
    `;

    list.appendChild(newItem);

}
function removeMenuItem(index) {
    const item = document.querySelector(`.menu-item-row[data-index="${index}"]`);
    if (item && confirm("Remover este item do menu?")) {
        item.remove();
    }

}
// Fechar modal ao clicar fora
document.getElementById('iconPickerModal')?.addEventListener('click', function(e) {
    if (e.target === this) {
        closeIconPicker();
    }
});
function toggleSection(element) {
    const section = element.closest('.header-editor-section');
    if (section) {
        section.classList.toggle('collapsed');
        
        // Salvar estado das seções abertas
        const openSections = [];
        document.querySelectorAll('.header-editor-section:not(.collapsed)').forEach((s, i) => {
            openSections.push(i);
        });
        document.getElementById('activeSectionInput').value = openSections.join(',');
    }
}

const isRetail = <?php echo $isRetail ? 'true' : 'false'; ?>;

// Alternar entre abas
function switchTab(tabName) {
    // Remover active de todas as abas
    document.querySelectorAll('.editor-tab-item').forEach(tab => {
        tab.classList.remove('active');
    });
    document.querySelectorAll('.editor-tab-panel').forEach(panel => {
        panel.classList.remove('active');
    });
    
    // Ativar aba selecionada
    document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
    document.getElementById(`tab-${tabName}`).classList.add('active');
    
    // Salvar aba ativa no input hidden
    document.getElementById('activeTabInput').value = tabName;
}

// Aplicar paleta de cores
// Restaurar cores padrão do template (salva automaticamente)
function resetColorsToDefault() {
    if (!confirm('Tem certeza que deseja restaurar as cores padrão do template?')) return;
    
    // Fazer requisição AJAX para salvar
    const formData = new FormData();
    formData.append('action', 'reset_colors');
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const colors = data.colors;
            const colorMap = {
                'primary': colors.primary,
                'secondary': colors.secondary,
                'accent': colors.accent,
                'bg': colors.bg,
                'card': colors.card,
                'text': colors.text,
                'text_secondary': colors.text_secondary
            };
            
            for (const [key, value] of Object.entries(colorMap)) {
                const colorInput = document.getElementById('color_' + key);
                const hexInput = document.getElementById('hex_' + key);
                const preview = document.getElementById('preview_' + key);
                
                if (colorInput) colorInput.value = value;
                if (hexInput) hexInput.value = value;
                if (preview) preview.style.background = value;
            }
            
            updateMockup();
            showNotification('Cores restauradas e salvas com sucesso!', 'success');
        } else {
            showNotification('Erro ao restaurar cores', 'error');
        }
    })
    .catch(error => {
        console.error('Erro:', error);
        showNotification('Erro ao restaurar cores', 'error');
    });
}



// Paletas são apenas indicadores visuais
// Para aplicar cores de uma paleta, clique nela e depois em "Aplicar Esta Paleta"
function applyPalette(paletteKey, colors) {
    // Apenas atualizar estado visual das paletas
    document.querySelectorAll('.palette-card').forEach(card => {
        card.classList.remove('active');
    });
    document.querySelector(`[data-palette="${paletteKey}"]`)?.classList.add('active');
    
    // Salvar cores da paleta selecionada para uso posterior
    window.selectedPaletteColors = colors;
    
    // Mostrar botão de aplicar
    const applyBtn = document.getElementById('applyPaletteBtn');
    if (applyBtn) applyBtn.style.display = 'inline-flex';
    
    showNotification('Paleta selecionada! Clique em "Aplicar Esta Paleta" para usar estas cores.', 'info');
}

// Função para realmente aplicar as cores da paleta selecionada
function applySelectedPalette() {
    if (!window.selectedPaletteColors) {
        showNotification('Selecione uma paleta primeiro.', 'warning');
        return;
    }
    
    const colors = window.selectedPaletteColors;
    const colorMap = {
        'primary': colors[0],
        'secondary': colors[1],
        'accent': colors[2],
        'bg': colors[3],
        'card': colors[4],
        'text': colors[5],
        'text_secondary': colors[6]
    };

    Object.keys(colorMap).forEach(key => {
        const colorInput = document.getElementById('color_' + key);
        const hexInput = document.getElementById('hex_' + key);
        const preview = document.getElementById('preview_' + key);

        if (colorInput && hexInput && preview) {
            colorInput.value = colorMap[key];
            hexInput.value = colorMap[key].toUpperCase();
            preview.style.background = colorMap[key];
        }
    });

    updateLivePreview();
    showNotification('Cores da paleta aplicadas! Personalize abaixo e clique em Salvar.', 'success');
}

function toggleAdvancedColors() {
    const toggle = document.querySelector('.advanced-colors-toggle');
    const content = document.getElementById('advancedColors');
    
    toggle.classList.toggle('expanded');
    content.classList.toggle('show');
}

// Atualizar preview de cor
function updateColorPreview(colorKey) {
    const colorInput = document.getElementById('color_' + colorKey);
    const hexInput = document.getElementById('hex_' + colorKey);
    const preview = document.getElementById('preview_' + colorKey);

    const color = colorInput.value;
    hexInput.value = color.toUpperCase();
    preview.style.background = color;
    
    // Remover estado ativo das paletas quando editar manualmente
    document.querySelectorAll('.palette-card').forEach(card => {
        card.classList.remove('active');
    });

    updateLivePreview();
}

// Atualizar cor a partir do input hex
function updateColorFromHex(colorKey) {
    const colorInput = document.getElementById('color_' + colorKey);
    const hexInput = document.getElementById('hex_' + colorKey);
    const preview = document.getElementById('preview_' + colorKey);

    let hex = hexInput.value.trim();
    if (!hex.startsWith('#')) hex = '#' + hex;

    if (/^#[0-9A-Fa-f]{6}$/.test(hex)) {
        colorInput.value = hex;
        preview.style.background = hex;
        updateLivePreview();
    }
}

// Atualizar preview ao vivo
function updateLivePreview() {
    const primaryEl = document.getElementById('color_primary');
    const accentEl = document.getElementById('color_accent');
    const bgEl = document.getElementById('color_bg');
    const cardEl = document.getElementById('color_card');
    const textEl = document.getElementById('color_text');
    const textSecondaryEl = document.getElementById('color_text_secondary');
    
    // Se elementos de cor não existem, sair
    if (!primaryEl || !accentEl || !bgEl || !cardEl || !textEl || !textSecondaryEl) return;
    
    const primary = primaryEl.value;
    const accent = accentEl.value;
    const bg = bgEl.value;
    const card = cardEl.value;
    const text = textEl.value;
    const textSecondary = textSecondaryEl.value;

    if (isRetail) {
        // Update Retail Mockup
        const previewMockup = document.getElementById('previewMockup');
        if (!previewMockup) return; // Mockup não existe nesta aba
        previewMockup.style.background = bg;
        
        // Header
        const retailHeader = document.getElementById('retailHeader');
        if (retailHeader) {
            retailHeader.style.background = card;
            retailHeader.style.borderColor = bg + '20';
            const brand = retailHeader.querySelector('.retail-header-brand');
            const actions = retailHeader.querySelector('.retail-header-actions');
            if (brand) brand.style.color = text;
            if (actions) actions.style.color = textSecondary;
        }
        
        // Logo
        document.getElementById('retailLogoIcon').style.background = `linear-gradient(135deg, ${primary}, ${accent})`;
        
        // Hero
        document.getElementById('retailHero').style.background = `linear-gradient(135deg, ${primary}, ${accent})`;
        document.getElementById('retailHeroBtn').style.color = primary;
        
        // Categories
        const retailCategories = document.getElementById('retailCategories');
        retailCategories.style.background = card;
        retailCategories.style.borderColor = bg + '20';
        document.getElementById('retailChipActive').style.background = primary;
        document.querySelectorAll('.retail-category-chip:not(.active)').forEach(chip => {
            chip.style.borderColor = textSecondary + '40';
            chip.style.color = textSecondary;
        });
        
        // Products Section
        document.getElementById('retailProductsSection').style.background = bg;
        document.getElementById('retailSectionTitle').style.color = text;
        document.getElementById('retailSectionLink').style.color = primary;
        
        // Product Cards
        ['retailCard1', 'retailCard2'].forEach(id => {
            const cardEl = document.getElementById(id);
            cardEl.style.background = card;
            cardEl.style.borderColor = bg + '20';
            cardEl.querySelector('.retail-product-image').style.background = bg;
            cardEl.querySelector('.retail-product-placeholder').style.background = `linear-gradient(180deg, ${textSecondary}30, ${textSecondary}20)`;
            cardEl.querySelector('.retail-product-wishlist').style.background = card;
            cardEl.querySelector('.retail-product-wishlist').style.color = textSecondary;
            cardEl.querySelector('.retail-product-name').style.color = text;
            cardEl.querySelector('.retail-product-price').style.color = text;
        });
        
        // Badges
        document.getElementById('retailBadge1').style.background = accent;
        document.getElementById('retailBadge2').style.background = primary;
        
        // Categories in products
        document.getElementById('retailProdCat1').style.color = primary;
        document.getElementById('retailProdCat2').style.color = primary;
        
        // Cart buttons
        document.getElementById('retailCartBtn1').style.background = primary;
        document.getElementById('retailCartBtn2').style.background = primary;
        
        // Footer
        const retailFooter = document.getElementById('retailFooter');
        retailFooter.style.background = card;
        retailFooter.style.borderColor = bg + '20';
        retailFooter.style.color = textSecondary;
        
    } else {
        // Update Service Mockup (Barbearia/Salão)
        document.getElementById('previewMockup').style.background = bg;
        document.getElementById('mockupNav').style.background = card;
        document.getElementById('mockupNav').style.borderColor = primary;
        document.getElementById('mockupNav').style.color = primary;
        document.getElementById('navText').style.color = text;
        document.getElementById('mockupHero').style.background = `linear-gradient(135deg, ${primary}, ${accent})`;
        document.getElementById('mockupServices').style.background = bg;

        document.querySelectorAll('.mockup-section-title').forEach(el => {
            el.style.color = text;
        });

        document.querySelectorAll('.mockup-section-title iconify-icon').forEach(el => {
            el.style.color = primary;
        });

        ['card1', 'card2', 'card3'].forEach(id => {
            const el = document.getElementById(id);
            if (el) {
                el.style.background = card;
                el.querySelector('iconify-icon').style.color = primary;
                el.querySelector('span').style.color = textSecondary;
            }
        });
    }
}

// ========================
// Funções do Editor de Cabeçalho
// ========================

// Atualizar tipo de logo
function updateLogoType(type) {
    document.querySelectorAll('.logo-type-option').forEach(opt => {
        opt.classList.remove('active');
    });
    document.querySelector(`input[name="header_logo_type"][value="${type}"]`).closest('.logo-type-option').classList.add('active');
    
    const textGroup = document.getElementById('logoTextGroup');
    const imageGroup = document.getElementById('logoImageGroup');
    
    // Mostrar/ocultar campos baseado no tipo
    if (type === 'text') {
        textGroup.style.display = 'block';
        imageGroup.style.display = 'none';
    } else if (type === 'image') {
        textGroup.style.display = 'none';
        imageGroup.style.display = 'block';
    } else { // both
        textGroup.style.display = 'block';
        imageGroup.style.display = 'block';
    }
    
    updateLogoPreview();
}

// Preview da imagem do logo
function previewLogo(input) {
    if (input.files && input.files[0]) {
        const file = input.files[0];
        
        // Validar tamanho (2MB max)
        if (file.size > 2 * 1024 * 1024) {
            alert('O arquivo é muito grande. O tamanho máximo é 2MB.');
            input.value = '';
            return;
        }
        
        const reader = new FileReader();
        reader.onload = function(e) {
            const previewBox = document.getElementById('logoPreviewBox');
            previewBox.innerHTML = `
                <img src="${e.target.result}" alt="Logo Preview" id="logoPreviewImg">
                <button type="button" class="logo-remove-btn" onclick="removeLogo()">
                    <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                </button>
            `;
            
            // Atualizar texto do botão
            document.querySelector('.logo-upload-info .btn').innerHTML = `
                <iconify-icon icon="solar:upload-bold"></iconify-icon>
                Trocar Logo
            `;
        };
        reader.readAsDataURL(file);
    }
}

// Remover logo
function removeLogo() {
    const previewBox = document.getElementById('logoPreviewBox');
    previewBox.innerHTML = `
        <div class="logo-placeholder" id="logoPlaceholder">
            <iconify-icon icon="solar:gallery-add-bold"></iconify-icon>
            <span>Clique para enviar</span>
        </div>
    `;
    
    // Limpar input file
    const fileInput = document.getElementById('headerLogoInput');
    fileInput.value = '';
    
    // Atualizar texto do botão
    document.querySelector('.logo-upload-info .btn').innerHTML = `
        <iconify-icon icon="solar:upload-bold"></iconify-icon>
        Enviar Logo
    `;
}

// Atualizar preview do logo (para o mockup)
function updateLogoPreview() {
    // Futuro: Atualizar o mockup com as mudanças do logo
    // Por enquanto, as mudanças serão aplicadas após salvar
}

// Clique na caixa de preview também abre o file input
document.addEventListener('DOMContentLoaded', function() {
    const previewBox = document.getElementById('logoPreviewBox');
    if (previewBox) {
        previewBox.addEventListener('click', function(e) {
            if (!e.target.closest('.logo-remove-btn')) {
                document.getElementById('headerLogoInput').click();
            }
        });
    }
    
    // Inicializar visibilidade dos campos de logo
    const logoType = document.querySelector('input[name="header_logo_type"]:checked')?.value || 'text';
    updateLogoType(logoType);
});

// Confirmar reset
function confirmReset() {
    if (confirm('Tem certeza que deseja restaurar as configurações padrão? Todas as suas personalizações serão perdidas.')) {
        document.getElementById('resetForm').submit();
    }
}

// Clique no preview de cor abre o color picker
document.querySelectorAll('.color-preview').forEach(preview => {
    preview.addEventListener('click', function() {
        const colorKey = this.id.replace('preview_', '');
        document.getElementById('color_' + colorKey).click();
    });
});

// Inicializar

// Restaurar aba ativa após salvar
document.addEventListener('DOMContentLoaded', function() {
    const activeTab = document.getElementById('activeTabInput')?.value || 'colors';
    if (activeTab && activeTab !== 'colors') {
        switchTab(activeTab);
    }
    
    // Restaurar seções abertas
    const activeSections = document.getElementById('activeSectionInput')?.value || '';
    if (activeSections) {
        const indices = activeSections.split(',').map(Number);
        document.querySelectorAll('.header-editor-section').forEach((section, index) => {
            if (indices.includes(index)) {
                section.classList.remove('collapsed');
            }
        });
    }
});
document.addEventListener('DOMContentLoaded', updateLivePreview);

// Inicializar hero type
document.addEventListener('DOMContentLoaded', function() {
    const heroType = document.querySelector('input[name="hero_type"]:checked');
    if (heroType) {
        updateHeroType(heroType.value);
    }
});

// ========================
// Funções do Editor de Hero
// ========================

function updateHeroType(type) {
    document.querySelectorAll('input[name="hero_type"]').forEach(input => {
        input.closest('.logo-type-option').classList.remove('active');
    });
    document.querySelector('input[name="hero_type"][value="' + type + '"]').closest('.logo-type-option').classList.add('active');

    // Mostrar/ocultar campos baseado no tipo
    document.getElementById('heroImageGroup').style.display = type === 'image' ? 'block' : 'none';
    document.getElementById('heroVideoGroup').style.display = type === 'video' ? 'block' : 'none';
    document.getElementById('heroOverlayGroup').style.display = type !== 'gradient' ? 'block' : 'none';
}

// ===== HERO IMAGES SLIDER FUNCTIONS =====

function previewHeroImages(input) {
    if (!input.files || input.files.length === 0) return;
    
    const gallery = document.getElementById('heroImagesGallery');
    const addBtn = gallery.querySelector('.hero-image-add');
    
    Array.from(input.files).forEach((file, idx) => {
        if (file.size > 5 * 1024 * 1024) {
            alert('O arquivo ' + file.name + ' é muito grande. Máximo 5MB.');
            return;
        }
        
        const reader = new FileReader();
        reader.onload = function(e) {
            const itemCount = gallery.querySelectorAll('.hero-image-item').length;
            const div = document.createElement('div');
            div.className = 'hero-image-item';
            div.dataset.index = itemCount;
            div.style.cssText = 'position: relative; aspect-ratio: 16/9; border-radius: 10px; overflow: hidden; border: 2px solid #e5e7eb;';
            div.innerHTML = `
                <img src="${e.target.result}" alt="Slide ${itemCount + 1}" style="width: 100%; height: 100%; object-fit: cover;">
                <input type="hidden" name="hero_new_images_preview[]" value="">
                <div class="hero-image-actions" style="position: absolute; top: 6px; right: 6px;">
                    <button type="button" class="hero-img-btn remove" onclick="removeHeroSlideImage(this)" title="Remover" style="width: 28px; height: 28px; border: none; border-radius: 6px; background: #ef4444; color: white; cursor: pointer; display: flex; align-items: center; justify-content: center;">
                        <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                    </button>
                </div>
                <span class="hero-image-number" style="position: absolute; top: 6px; left: 6px; width: 22px; height: 22px; background: #2563eb; color: #fff; border-radius: 50%; font-size: 0.7rem; font-weight: 600; display: flex; align-items: center; justify-content: center;">${itemCount + 1}</span>
            `;
            gallery.insertBefore(div, addBtn);
            updateHeroImageNumbers();
        };
        reader.readAsDataURL(file);
    });
}

function removeHeroSlideImage(btn) {
    const item = btn.closest('.hero-image-item');
    if (item) {
        item.remove();
        updateHeroImageNumbers();
    }
}

function updateHeroImageNumbers() {
    const gallery = document.getElementById('heroImagesGallery');
    if (!gallery) return;
    const items = gallery.querySelectorAll('.hero-image-item');
    items.forEach((item, idx) => {
        item.dataset.index = idx;
        const num = item.querySelector('.hero-image-number');
        if (num) num.textContent = idx + 1;
    });
}

// Legacy function compatibility (single image - kept for fallback)
function previewHeroImage(input) {
    previewHeroImages(input);
}

function removeHeroImage() {
    // Legacy - now handled by removeHeroSlideImage
}



// Funções para gerenciar links do Footer

// Funções para gerenciar seções customizadas
let customSectionCount = document.querySelectorAll('.custom-section-item').length;

function addCustomSection() {
    const container = document.getElementById('customSectionsContainer');

    // Remove mensagem de vazio se existir
    const emptyMsg = container.querySelector('.empty-sections-message');
    if (emptyMsg) emptyMsg.remove();

    const newIndex = customSectionCount++;

    const newSection = document.createElement('div');
    newSection.className = 'custom-section-item';
    newSection.dataset.index = newIndex;
    newSection.style.cssText = 'background: var(--bg-dark); border-radius: 0.5rem; padding: 1rem; margin-bottom: 1rem; border: 1px solid var(--border);';
    newSection.innerHTML = `
        <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 1rem;">
            <div style="flex: 1;">
                <div style="display: flex; gap: 0.5rem; margin-bottom: 0.5rem;">
                    <input type="text" name="section_title[${newIndex}]" class="form-input" placeholder="Título da seção (ex: Promoções)" style="flex: 2;">
                    <input type="text" name="section_subtitle[${newIndex}]" class="form-input" placeholder="Subtítulo (opcional)" style="flex: 2;">
                </div>
            </div>
            <div style="display: flex; align-items: center; gap: 0.5rem; margin-left: 0.5rem;">
                <label class="custom-toggle-switch" title="Ativar/Desativar">
                    <input type="checkbox" name="section_enabled[${newIndex}]" value="1" checked>
                    <span class="custom-toggle-slider"></span>
                </label>
                <button type="button" class="btn btn-icon btn-danger" onclick="removeCustomSection(this)" title="Remover seção">
                    <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                </button>
            </div>
        </div>

        <div class="section-products-selector">
            <label class="form-label-sm" style="font-size: 0.85rem; margin-bottom: 0.75rem; display: flex; align-items: center; justify-content: space-between;">
                <span>
                    <iconify-icon icon="solar:bag-3-bold" style="margin-right: 0.25rem;"></iconify-icon>
                    Produtos desta seção
                </span>
                <span class="selected-count-badge" style="background: var(--color-primary); color: #fff; padding: 0.2rem 0.6rem; border-radius: 1rem; font-size: 0.75rem;">
                    0 selecionados
                </span>
            </label>
            
            <input type="hidden" name="section_products[${newIndex}]" class="selected-products-input" value="">
            
            <div class="selected-products-area" style="display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 0.75rem; min-height: 50px; padding: 0.75rem; background: var(--color-bg); border-radius: 0.5rem; border: 2px dashed var(--color-border);">
                <span class="empty-hint" style="color: var(--color-text-secondary); font-size: 0.85rem; width: 100%; text-align: center;">
                    <iconify-icon icon="solar:box-minimalistic-bold" style="font-size: 1.5rem; display: block; margin-bottom: 0.25rem;"></iconify-icon>
                    Toque em "Selecionar Produtos" para adicionar
                </span>
            </div>
            
            <button type="button" class="btn btn-outline" onclick="openProductSelectorModal(${newIndex})" style="width: 100%; padding: 0.875rem; border-style: dashed; font-size: 0.95rem;">
                <iconify-icon icon="solar:add-square-bold" style="font-size: 1.2rem;"></iconify-icon>
                Selecionar Produtos
            </button>
        </div>
    `;

    container.appendChild(newSection);
    
    // Scroll para a nova seção
    newSection.scrollIntoView({ behavior: 'smooth', block: 'center' });
}

function removeCustomSection(button) {
    if (confirm('Remover esta seção?')) {
        const section = button.closest('.custom-section-item');
        section.remove();
        
        // Se não houver mais seções, mostrar mensagem de vazio
        const container = document.getElementById('customSectionsContainer');
        if (container.querySelectorAll('.custom-section-item').length === 0) {
            container.innerHTML = `
                <div class="empty-sections-message" style="text-align: center; padding: 2rem; background: var(--color-card); border-radius: 0.5rem; border: 2px dashed var(--color-border);">
                    <iconify-icon icon="solar:layers-minimalistic-bold" style="font-size: 3rem; color: var(--color-text-secondary); margin-bottom: 1rem; display: block;"></iconify-icon>
                    <p style="color: var(--color-text-secondary); margin: 0;">Nenhuma seção criada ainda.<br>Clique em "Nova Seção" para começar.</p>
                </div>
            `;
        }
    }
}
function addFooterLink() {
    const container = document.getElementById('footerLinksContainer');
    const newRow = document.createElement('div');
    newRow.className = 'footer-link-row';
    newRow.style.cssText = 'display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 0.75rem; align-items: flex-start; padding: 0.75rem; background: rgba(255,255,255,0.02); border-radius: 8px; border: 1px solid var(--border);';
    newRow.innerHTML = `
        <input type="text" name="footer_link_name[]" class="form-input" placeholder="Título do Link" style="flex: 1; min-width: 150px;">
        <input type="hidden" name="footer_link_url[]" value="#">
        <select class="form-input footer-link-select" onchange="handleFooterLinkChange(this)" style="flex: 1; min-width: 180px;">
            ${getFooterLinkOptionsHtml()}
        </select>
        <div class="footer-custom-link-wrapper" style="display: none; width: 100%; margin-top: 0.5rem;">
            <input type="text" class="form-input footer-custom-link-input" placeholder="https://exemplo.com ou /minha-pagina" oninput="updateFooterCustomLink(this)">
        </div>
        <button type="button" class="btn btn-icon btn-danger" onclick="this.closest('.footer-link-row').remove()" title="Remover" style="flex-shrink: 0;">
            <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
        </button>
    `;
    container.appendChild(newRow);
}

function addFooterHelp() {
    const container = document.getElementById('footerHelpContainer');
    const newRow = document.createElement('div');
    newRow.className = 'footer-link-row';
    newRow.style.cssText = 'display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 0.75rem; align-items: flex-start; padding: 0.75rem; background: rgba(255,255,255,0.02); border-radius: 8px; border: 1px solid var(--border);';
    newRow.innerHTML = `
        <input type="text" name="footer_help_name[]" class="form-input" placeholder="Título do Link" style="flex: 1; min-width: 150px;">
        <input type="hidden" name="footer_help_url[]" value="#">
        <select class="form-input footer-help-select" onchange="handleFooterHelpChange(this)" style="flex: 1; min-width: 180px;">
            ${getFooterLinkOptionsHtml()}
        </select>
        <div class="footer-custom-link-wrapper" style="display: none; width: 100%; margin-top: 0.5rem;">
            <input type="text" class="form-input footer-custom-link-input" placeholder="https://exemplo.com ou /minha-pagina" oninput="updateFooterCustomLink(this)">
        </div>
        <button type="button" class="btn btn-icon btn-danger" onclick="this.closest('.footer-link-row').remove()" title="Remover" style="flex-shrink: 0;">
            <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
        </button>
    `;
    container.appendChild(newRow);
}

function getFooterLinkOptionsHtml(selectedValue = "#") {
    let html = "";
    let isCustom = selectedValue && selectedValue !== "#" && !menuLinkOptions[selectedValue];
    
    for (const [value, label] of Object.entries(menuLinkOptions)) {
        if (value.startsWith("---")) {
            html += '<option disabled>─────────────────</option>';
        } else if (value === "custom") {
            const selected = isCustom ? "selected" : "";
            html += '<option value="custom" ' + selected + '>' + label + '</option>';
        } else {
            const selected = (!isCustom && value === selectedValue) ? "selected" : "";
            html += '<option value="' + value + '" ' + selected + '>' + label + '</option>';
        }
    }
    return html;
}

function handleFooterLinkChange(selectEl) {
    const row = selectEl.closest('.footer-link-row');
    const customWrapper = row.querySelector('.footer-custom-link-wrapper');
    const customInput = row.querySelector('.footer-custom-link-input');
    const hiddenInput = row.querySelector('input[type="hidden"]');
    
    if (selectEl.value === "custom") {
        customWrapper.style.display = "flex";
        if (customInput) customInput.focus();
    } else {
        customWrapper.style.display = "none";
        if (hiddenInput) hiddenInput.value = selectEl.value;
    }
}

function handleFooterHelpChange(selectEl) {
    handleFooterLinkChange(selectEl);
}

function updateFooterCustomLink(input) {
    const row = input.closest('.footer-link-row');
    const hiddenInput = row.querySelector('input[type="hidden"]');
    if (hiddenInput) {
        hiddenInput.value = input.value || "#";
    }
}
// ============ SELETOR DE PRODUTOS ============
let currentSectionIdx = null;
let selectedProductIds = [];

function openProductSelectorModal(sectionIdx) {
    currentSectionIdx = sectionIdx;
    const sectionItem = document.querySelector(`.custom-section-item[data-index="${sectionIdx}"]`);
    const hiddenInput = sectionItem.querySelector(".selected-products-input");
    
    // Pegar IDs já selecionados
    selectedProductIds = hiddenInput.value ? hiddenInput.value.split(",").map(id => parseInt(id)).filter(id => id > 0) : [];
    
    // Renderizar lista de produtos
    renderProductList();
    
    // Mostrar modal
    document.getElementById("productSelectorModal").classList.add("active");
    document.getElementById("productSearchInput").value = "";
    document.getElementById("productSearchInput").focus();
}

function closeProductSelectorModal() {
    document.getElementById("productSelectorModal").classList.remove("active");
    currentSectionIdx = null;
}

function renderProductList(filter = "") {
    const list = document.getElementById("productSelectorList");
    const filterLower = filter.toLowerCase();
    
    let html = "";
    storeProductsList.forEach(product => {
        if (filter && !product.name.toLowerCase().includes(filterLower)) return;
        
        const isSelected = selectedProductIds.includes(parseInt(product.id));
        const imgUrl = product.image_url || "/assets/images/no-image.jpg";
        const price = parseFloat(product.price).toLocaleString("pt-BR", {style: "currency", currency: "BRL"});
        
        html += `
            <div class="product-selector-item ${isSelected ? "selected" : ""}" onclick="toggleProductInModal(${product.id})">
                <img src="${imgUrl}" alt="${product.name}" onerror="this.src='/assets/images/no-image.jpg'">
                <div class="product-selector-item-info">
                    <div class="product-selector-item-name">${product.name}</div>
                    <div class="product-selector-item-price">${price}</div>
                </div>
                <div class="product-selector-item-check">
                    ${isSelected ? '<iconify-icon icon="solar:check-read-bold"></iconify-icon>' : ""}
                </div>
            </div>
        `;
    });
    
    if (!html) {
        html = '<div style="text-align:center;padding:2rem;color:var(--color-text-secondary);">Nenhum produto encontrado</div>';
    }
    
    list.innerHTML = html;
}

function filterProducts(value) {
    renderProductList(value);
}

function toggleProductInModal(productId) {
    productId = parseInt(productId);
    const idx = selectedProductIds.indexOf(productId);
    if (idx > -1) {
        selectedProductIds.splice(idx, 1);
    } else {
        selectedProductIds.push(productId);
    }
    renderProductList(document.getElementById("productSearchInput").value);
}

function confirmProductSelection() {
    const sectionItem = document.querySelector(`.custom-section-item[data-index="${currentSectionIdx}"]`);
    const hiddenInput = sectionItem.querySelector(".selected-products-input");
    const previewArea = sectionItem.querySelector(".selected-products-area");
    const countBadge = sectionItem.querySelector(".selected-count-badge");
    
    // Atualizar input hidden
    hiddenInput.value = selectedProductIds.join(",");
    
    // Atualizar badge de contagem
    countBadge.textContent = selectedProductIds.length + " selecionados";
    
    // Atualizar preview de produtos selecionados
    if (selectedProductIds.length === 0) {
        previewArea.innerHTML = `
            <span class="empty-hint" style="color: var(--color-text-secondary); font-size: 0.85rem; width: 100%; text-align: center;">
                <iconify-icon icon="solar:box-minimalistic-bold" style="font-size: 1.5rem; display: block; margin-bottom: 0.25rem;"></iconify-icon>
                Toque em "Selecionar Produtos" para adicionar
            </span>
        `;
    } else {
        let tagsHtml = "";
        selectedProductIds.forEach(productId => {
            const product = storeProductsList.find(p => parseInt(p.id) === productId);
            if (product) {
                const imgHtml = product.image_url ? `<img src="${product.image_url}" alt="">` : "";
                tagsHtml += `
                    <div class="product-tag" data-id="${product.id}" onclick="removeProductFromSection(this)">
                        ${imgHtml}
                        <span>${product.name}</span>
                        <div class="remove-btn"><iconify-icon icon="solar:close-bold"></iconify-icon></div>
                    </div>
                `;
            }
        });
        previewArea.innerHTML = tagsHtml;
    }
    
    closeProductSelectorModal();
}

function removeProductFromSection(tagElement) {
    const sectionItem = tagElement.closest(".custom-section-item");
    const productId = parseInt(tagElement.dataset.id);
    const hiddenInput = sectionItem.querySelector(".selected-products-input");
    const previewArea = sectionItem.querySelector(".selected-products-area");
    const countBadge = sectionItem.querySelector(".selected-count-badge");
    
    // Remover ID do input
    let ids = hiddenInput.value ? hiddenInput.value.split(",").map(id => parseInt(id)).filter(id => id > 0) : [];
    ids = ids.filter(id => id !== productId);
    hiddenInput.value = ids.join(",");
    
    // Atualizar badge
    countBadge.textContent = ids.length + " selecionados";
    
    // Remover tag visualmente
    tagElement.remove();
    
    // Se não há mais produtos, mostrar mensagem
    if (ids.length === 0) {
        previewArea.innerHTML = `
            <span class="empty-hint" style="color: var(--color-text-secondary); font-size: 0.85rem; width: 100%; text-align: center;">
                <iconify-icon icon="solar:box-minimalistic-bold" style="font-size: 1.5rem; display: block; margin-bottom: 0.25rem;"></iconify-icon>
                Toque em "Selecionar Produtos" para adicionar
            </span>
        `;
    }
}


</script>

<!-- Modal de Seleção de Produtos -->
<div id="productSelectorModal" class="product-selector-modal" onclick="if(event.target===this)closeProductSelectorModal()">
    <div class="product-selector-content">
        <div class="product-selector-header">
            <h3>
                <iconify-icon icon="solar:bag-3-bold"></iconify-icon>
                Selecionar Produtos
            </h3>
            <button type="button" class="btn btn-icon" onclick="closeProductSelectorModal()" style="background:none;border:none;font-size:1.5rem;cursor:pointer;">
                <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
            </button>
        </div>
        <div class="product-selector-search">
            <input type="text" id="productSearchInput" placeholder="Buscar produtos..." oninput="filterProducts(this.value)">
        </div>
        <div class="product-selector-list" id="productSelectorList">
            <!-- Produtos serão inseridos via JS -->
        </div>
        <div class="product-selector-footer">
            <button type="button" class="btn btn-outline" onclick="closeProductSelectorModal()">Cancelar</button>
            <button type="button" class="btn btn-primary" onclick="confirmProductSelection()">
                <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                Confirmar Seleção
            </button>
        </div>
    </div>
</div>

<!-- Modal de Criar/Editar Página -->
<div class="page-modal-overlay" id="pageModal">
    <div class="page-modal">
        <div class="page-modal-header">
            <h3>
                <iconify-icon icon="solar:document-add-bold"></iconify-icon>
                <span id="pageModalTitle">Nova Página</span>
            </h3>
            <button type="button" class="page-modal-close" onclick="closePageModal()">
                <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
            </button>
        </div>
        <div class="page-modal-body">
            <input type="hidden" id="pageId" value="">
            
            <div class="page-form-group">
                <label>Título da Página *</label>
                <input type="text" id="pageTitle" placeholder="Ex: Sobre Nós, Política de Privacidade..." oninput="generateSlug()">
            </div>
            
            <div class="page-form-group">
                <label>Slug (URL)</label>
                <input type="text" id="pageSlug" placeholder="sobre-nos" oninput="updateSlugPreview()">
                <div class="slug-preview">
                    A página ficará acessível em: <code id="slugPreviewUrl">/pagina/...</code>
                </div>
            </div>
            

            <div class="page-form-group">
                <label>Conteúdo da Página</label>
                <div class="content-editor-wrapper">
                    <div class="content-editor-toolbar">
                        <!-- Formatação de Texto -->
                        <button type="button" class="editor-btn" onclick="formatText('bold')" title="Negrito">
                            <iconify-icon icon="solar:text-bold-bold"></iconify-icon>
                        </button>
                        <button type="button" class="editor-btn" onclick="formatText('italic')" title="Itálico">
                            <iconify-icon icon="solar:text-italic-bold"></iconify-icon>
                        </button>
                        <button type="button" class="editor-btn" onclick="formatText('underline')" title="Sublinhado">
                            <iconify-icon icon="solar:text-underline-bold"></iconify-icon>
                        </button>
                        <button type="button" class="editor-btn" onclick="formatText('strikeThrough')" title="Riscado">
                            <iconify-icon icon="solar:text-cross-bold"></iconify-icon>
                        </button>
                        
                        <div class="editor-separator"></div>
                        
                        <!-- Títulos -->
                        <button type="button" class="editor-btn" onclick="formatBlock('h1')" title="Título 1">
                            <span style="font-weight:bold;font-size:14px;">H1</span>
                        </button>
                        <button type="button" class="editor-btn" onclick="formatBlock('h2')" title="Título 2">
                            <span style="font-weight:bold;font-size:12px;">H2</span>
                        </button>
                        <button type="button" class="editor-btn" onclick="formatBlock('h3')" title="Título 3">
                            <span style="font-weight:bold;font-size:10px;">H3</span>
                        </button>
                        <button type="button" class="editor-btn" onclick="formatBlock('p')" title="Parágrafo">
                            <iconify-icon icon="solar:text-bold"></iconify-icon>
                        </button>
                        
                        <div class="editor-separator"></div>
                        
                        <!-- Listas -->
                        <button type="button" class="editor-btn" onclick="formatText('insertUnorderedList')" title="Lista com marcadores">
                            <iconify-icon icon="solar:list-bold"></iconify-icon>
                        </button>
                        <button type="button" class="editor-btn" onclick="formatText('insertOrderedList')" title="Lista numerada">
                            <iconify-icon icon="mdi:format-list-numbered"></iconify-icon>
                        </button>
                        
                        <div class="editor-separator"></div>
                        
                        <!-- Alinhamento -->
                        <button type="button" class="editor-btn" onclick="formatText('justifyLeft')" title="Alinhar à esquerda">
                            <iconify-icon icon="mdi:format-align-left"></iconify-icon>
                        </button>
                        <button type="button" class="editor-btn" onclick="formatText('justifyCenter')" title="Centralizar">
                            <iconify-icon icon="mdi:format-align-center"></iconify-icon>
                        </button>
                        <button type="button" class="editor-btn" onclick="formatText('justifyRight')" title="Alinhar à direita">
                            <iconify-icon icon="mdi:format-align-right"></iconify-icon>
                        </button>
                        
                        <div class="editor-separator"></div>
                        
                        <!-- Inserir -->
                        <button type="button" class="editor-btn" onclick="insertLink()" title="Inserir Link">
                            <iconify-icon icon="solar:link-bold"></iconify-icon>
                        </button>
                        <button type="button" class="editor-btn" onclick="insertImage()" title="Inserir Imagem">
                            <iconify-icon icon="solar:gallery-bold"></iconify-icon>
                        </button>
                        <button type="button" class="editor-btn" onclick="formatBlock('blockquote')" title="Citação">
                            <iconify-icon icon="mdi:format-quote-close"></iconify-icon>
                        </button>
                        
                        <div class="editor-separator"></div>
                        
                        <!-- Limpar -->
                        <button type="button" class="editor-btn" onclick="formatText('removeFormat')" title="Limpar formatação">
                            <iconify-icon icon="solar:eraser-bold"></iconify-icon>
                        </button>
                    </div>
                    <div id="pageContentEditor" class="content-editor-area" contenteditable="true"></div>
                    <input type="hidden" id="pageContent">
                </div>
            </div>

            <div class="page-form-group">
                <label>Descrição (SEO)</label>
                <input type="text" id="pageDescription" placeholder="Breve descrição para mecanismos de busca (opcional)">
            </div>
            
            <div class="page-form-row">
                <label class="page-form-checkbox">
                    <input type="checkbox" id="pageActive" checked>
                    <span>Página ativa</span>
                </label>
                <label class="page-form-checkbox">
                    <input type="checkbox" id="pageShowInMenu">
                    <span>Mostrar no menu</span>
                </label>
            </div>
        </div>
        <div class="page-modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closePageModal()">Cancelar</button>
            <button type="button" class="btn btn-primary" onclick="savePage()">
                <iconify-icon icon="solar:diskette-bold"></iconify-icon>
                Salvar Página
            </button>
        </div>
    </div>
</div>

<script>
// ========================================
// GERENCIAMENTO DE PÁGINAS PERSONALIZADAS
// ========================================

const storeId = <?php echo json_encode($storeId); ?>;

const baseStoreUrl = <?php echo json_encode($storeBaseUrl); ?>;
const domainType = <?php echo json_encode($domainType); ?>;

// Carregar páginas ao iniciar
document.addEventListener("DOMContentLoaded", function() {
    loadPages();
});

async function loadPages() {
    const container = document.getElementById("pagesList");
    if (!container) return;
    
    try {
        const response = await fetch("/api/store-pages.php?action=list&store_id=" + storeId);
        const data = await response.json();
        
        if (data.success && data.pages.length > 0) {
            container.innerHTML = data.pages.map(page => `
                <div class="page-item" data-id="${page.id}">
                    <div class="page-item-icon">
                        <iconify-icon icon="solar:document-text-bold"></iconify-icon>
                    </div>
                    <div class="page-item-info">
                        <div class="page-item-title">
                            ${escapeHtml(page.title)}
                            ${page.show_in_menu ? '<span class="badge badge-menu">No Menu</span>' : ''}
                            ${!page.is_active ? '<span class="badge badge-draft">Rascunho</span>' : ''}
                        </div>
                        <div class="page-item-slug">${baseStoreUrl}/pagina/${escapeHtml(page.slug)}</div>
                    </div>
                    <div class="page-item-actions">
                        <a href="${baseStoreUrl}/pagina/${page.slug}" target="_blank" class="page-item-btn" title="Visualizar">
                            <iconify-icon icon="solar:eye-bold"></iconify-icon>
                        </a>
                        <button type="button" class="page-item-btn" onclick="editPage(${page.id})" title="Editar">
                            <iconify-icon icon="solar:pen-bold"></iconify-icon>
                        </button>
                        <button type="button" class="page-item-btn delete" onclick="deletePage(${page.id}, '${escapeHtml(page.title)}')" title="Excluir">
                            <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                        </button>
                    </div>
                </div>
            `).join('');
        } else {
            container.innerHTML = `
                <div class="pages-empty">
                    <iconify-icon icon="solar:document-add-bold"></iconify-icon>
                    <p>Você ainda não criou nenhuma página.</p>
                    <button type="button" class="btn btn-primary" onclick="openPageModal()" style="margin-top: 1rem;">
                        <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                        Criar Primeira Página
                    </button>
                </div>
            `;
        }
    } catch (error) {
        console.error("Erro ao carregar páginas:", error);
        container.innerHTML = `
            <div class="pages-empty">
                <iconify-icon icon="solar:danger-triangle-bold" style="color: #ef4444;"></iconify-icon>
                <p>Erro ao carregar páginas. Tente novamente.</p>
            </div>
        `;
    }
}


// ========================================
// FUNÇÕES DO EDITOR DE CONTEÚDO RICO
// ========================================

function formatText(command) {
    document.execCommand(command, false, null);
    document.getElementById('pageContentEditor').focus();
}

function formatBlock(tag) {
    document.execCommand('formatBlock', false, '<' + tag + '>');
    document.getElementById('pageContentEditor').focus();
}

function insertLink() {
    const url = prompt('Digite a URL do link:', 'https://');
    if (url) {
        document.execCommand('createLink', false, url);
    }
    document.getElementById('pageContentEditor').focus();
}


function insertImage() {
    // Abrir galeria de mídia para selecionar imagem
    openMediaGallery(function(result) {
        console.log("Resultado da galeria:", result);
        const editor = document.getElementById('pageContentEditor');
        
        // Se há imagens selecionadas da galeria existente
        if (result.existingUrls && result.existingUrls.length > 0) {
            result.existingUrls.forEach(function(url) {
                console.log("Inserindo imagem:", url);
                insertImageInEditor(url);
            });
        }
        
        // Se há arquivos novos para upload
        if (result.newFiles && result.newFiles.length > 0) {
            uploadAndInsertImages(result.newFiles);
        }
    });
}

// Função para fazer upload e inserir imagens
async function uploadAndInsertImages(files) {
    const editor = document.getElementById('pageContentEditor');
    
    for (const file of files) {
        const formData = new FormData();
        formData.append('image', file);
        formData.append('action', 'upload_page_image');
        
        try {
            const response = await fetch('/api/upload-image.php', {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            
            if (data.success && data.url) {
                insertImageInEditor(data.url);
            } else {
                console.error('Erro ao fazer upload:', data.error);
                alert('Erro ao fazer upload da imagem: ' + (data.error || 'Erro desconhecido'));
            }
        } catch (error) {
            console.error('Erro ao fazer upload:', error);
            alert('Erro ao fazer upload da imagem');
        }
    }
    
    editor.focus();
}

// Sincronizar editor com campo hidden antes de salvar
function syncEditorContent() {
    const editor = document.getElementById('pageContentEditor');
    const hidden = document.getElementById('pageContent');
    if (editor && hidden) {
        // Criar uma cópia do conteúdo para limpar elementos de controle
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = editor.innerHTML;
        
        // Processar cada wrapper de imagem
        const wrappers = tempDiv.querySelectorAll('.img-resize-wrapper');
        wrappers.forEach(function(wrapper) {
            const img = wrapper.querySelector('img');
            if (img) {
                // Copiar estilos do wrapper para a imagem
                if (wrapper.style.width) {
                    img.style.width = wrapper.style.width;
                }
                // Aplicar alinhamento como estilo inline
                if (wrapper.classList.contains('align-left')) {
                    img.style.display = 'block';
                    img.style.marginLeft = '0';
                    img.style.marginRight = 'auto';
                } else if (wrapper.classList.contains('align-center')) {
                    img.style.display = 'block';
                    img.style.marginLeft = 'auto';
                    img.style.marginRight = 'auto';
                } else if (wrapper.classList.contains('align-right')) {
                    img.style.display = 'block';
                    img.style.marginLeft = 'auto';
                    img.style.marginRight = '0';
                }
                // Substituir wrapper pela imagem
                wrapper.parentNode.replaceChild(img, wrapper);
            }
        });
        
        // Remover qualquer handle ou toolbar restante
        tempDiv.querySelectorAll('.img-resize-handle, .img-toolbar').forEach(function(el) {
            el.remove();
        });
        
        hidden.value = tempDiv.innerHTML;
    }
}

// Carregar conteúdo no editor
function loadEditorContent(html) {
    const editor = document.getElementById('pageContentEditor');
    if (editor) {
        editor.innerHTML = html || '';
    }
}

function openPageModal(pageId = null) {
    const modal = document.getElementById("pageModal");
    const title = document.getElementById("pageModalTitle");
    
    // Limpar formulário
    document.getElementById("pageId").value = pageId || "";
    document.getElementById("pageTitle").value = "";
    document.getElementById("pageSlug").value = "";
    document.getElementById("pageContent").value = "";
    loadEditorContent("");
    document.getElementById("pageDescription").value = "";
    document.getElementById("pageActive").checked = true;
    document.getElementById("pageShowInMenu").checked = false;
    
    title.textContent = pageId ? "Editar Página" : "Nova Página";
    modal.classList.add("active");
    
    updateSlugPreview();
}

function closePageModal() {
    document.getElementById("pageModal").classList.remove("active");
}

async function editPage(pageId) {
    try {
        const response = await fetch(`/api/store-pages.php?action=get&id=${pageId}&store_id=${storeId}`);
        const data = await response.json();
        
        if (data.success && data.page) {
            const page = data.page;
            document.getElementById("pageId").value = page.id;
            document.getElementById("pageTitle").value = page.title;
            document.getElementById("pageSlug").value = page.slug;
            document.getElementById("pageContent").value = page.content || "";
            loadEditorContent(page.content || "");
            document.getElementById("pageDescription").value = page.meta_description || "";
            document.getElementById("pageActive").checked = page.is_active == 1;
            document.getElementById("pageShowInMenu").checked = page.show_in_menu == 1;
            
            document.getElementById("pageModalTitle").textContent = "Editar Página";
            document.getElementById("pageModal").classList.add("active");
            updateSlugPreview();
        }
    } catch (error) {
        console.error("Erro ao carregar página:", error);
        alert("Erro ao carregar página. Tente novamente.");
    }
}

async function savePage() {
    // Sincronizar conteúdo do editor
    syncEditorContent();
    const pageId = document.getElementById("pageId").value;
    const title = document.getElementById("pageTitle").value.trim();
    const slug = document.getElementById("pageSlug").value.trim();
    const content = document.getElementById("pageContent").value;
    const description = document.getElementById("pageDescription").value.trim();
    const isActive = document.getElementById("pageActive").checked;
    const showInMenu = document.getElementById("pageShowInMenu").checked;
    
    if (!title) {
        alert("Digite o título da página.");
        return;
    }
    
    if (!slug) {
        alert("Digite o slug da página.");
        return;
    }
    
    try {
        const formData = new FormData();
        formData.append("action", pageId ? "update" : "create");
        formData.append("store_id", storeId);
        if (pageId) formData.append("id", pageId);
        formData.append("title", title);
        formData.append("slug", slug);
        formData.append("content", content);
        formData.append("meta_description", description);
        formData.append("is_active", isActive ? 1 : 0);
        formData.append("show_in_menu", showInMenu ? 1 : 0);
        
        const response = await fetch("/api/store-pages.php", {
            method: "POST",
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            closePageModal();
            loadPages();
            showToast(pageId ? "Página atualizada!" : "Página criada!", "success");
        } else {
            alert(data.error || "Erro ao salvar página.");
        }
    } catch (error) {
        console.error("Erro ao salvar página:", error);
        alert("Erro ao salvar página. Tente novamente.");
    }
}

async function deletePage(pageId, pageTitle) {
    if (!confirm(`Tem certeza que deseja excluir a página "${pageTitle}"?`)) {
        return;
    }
    
    try {
        const formData = new FormData();
        formData.append("action", "delete");
        formData.append("id", pageId);
        formData.append("store_id", storeId);
        
        const response = await fetch("/api/store-pages.php", {
            method: "POST",
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            loadPages();
            showToast("Página excluída!", "success");
        } else {
            alert(data.error || "Erro ao excluir página.");
        }
    } catch (error) {
        console.error("Erro ao excluir página:", error);
        alert("Erro ao excluir página. Tente novamente.");
    }
}

function generateSlug() {
    const title = document.getElementById("pageTitle").value;
    const slug = title
        .toLowerCase()
        .normalize("NFD")
        .replace(/[\u0300-\u036f]/g, "")
        .replace(/[^a-z0-9]+/g, "-")
        .replace(/^-+|-+$/g, "");
    
    document.getElementById("pageSlug").value = slug;
    updateSlugPreview();
}

function updateSlugPreview() {
    const slug = document.getElementById("pageSlug").value || "...";
    document.getElementById("slugPreviewUrl").textContent = baseStoreUrl + "/pagina/" + slug;
}

function escapeHtml(text) {
    const div = document.createElement("div");
    div.textContent = text;
    return div.innerHTML;
}

function showToast(message, type = "info") {
    // Simple toast notification
    const toast = document.createElement("div");
    toast.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        background: ${type === "success" ? "#10b981" : "#3b82f6"};
        color: white;
        padding: 1rem 1.5rem;
        border-radius: 8px;
        z-index: 99999;
        animation: slideIn 0.3s ease;
    `;
    toast.textContent = message;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 3000);
}
</script>
<script src="/assets/js/img-editor.js"></script>

<?php include __DIR__ . '/../includes/media-gallery.php'; ?>
<?php include __DIR__ . '/../includes/dashboard-footer.php'; ?>
