<?php
/**
 * Painel de Customização White Label
 * Permite personalizar cores e logos do sistema
 */

// Conexão com o banco de dados
// Nota: Autenticação já verificada em dashboard/index.php
require_once __DIR__ . '/../../config/config_db.php';
require_once __DIR__ . '/../../backend/auth_helper.php';
require_once __DIR__ . '/../../backend/settings_helper.php';

$mensagem = '';
$tipo_mensagem = '';
$activeTab = isset($_GET['tab']) ? $_GET['tab'] : 'colors';

// Processar formulário de cores
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_colors') {
    try {
        // Cores do Dashboard
        // Campos de cores (hex ou rgba)
        $color_keys = [
            'color_sidebar_bg',      // Fundo da Sidebar
            'color_sidebar_text',    // Texto da Sidebar
            'color_header_bg',        // Fundo do Header
            'color_header_text',      // Texto do Header
            'color_body_bg',          // Fundo do Body
            'color_card_bg',          // Fundo dos Cards
            'color_text_main',        // Texto Principal
            'color_text_muted',       // Texto Muted
            'color_border',           // Cor das Bordas
            // Cores do Marketplace
            'color_marketplace_bg',           // Fundo do Marketplace
            'color_marketplace_title',        // Cor do Título do Marketplace
            'color_marketplace_header_bg',    // Fundo do Topo/Filters do Marketplace
            'color_marketplace_header_text',  // Texto do Topo/Filters
            'color_marketplace_card_bg',      // Fundo dos Cards de Produtos
            'color_marketplace_product_name', // Nome dos Produtos
            'color_marketplace_category',      // Categoria dos Produtos
            'color_marketplace_price',        // Preço dos Produtos
            'color_marketplace_button_buy',    // Botão Comprar
            'color_marketplace_button_affiliate', // Botão Afiliar
            // Cores de Botões e Ações
            'color_button_primary',            // Botão Primário
            'color_button_primary_hover',     // Botão Primário Hover
            'color_button_edit',              // Botão Editar
            'color_button_view',              // Botão Visualizar
            'color_button_delete',            // Botão Excluir
            'color_button_save',              // Botão Salvar
            // Cores de Status
            'color_status_success',           // Status Sucesso
            'color_status_warning',           // Status Aviso
            'color_status_danger',           // Status Erro
            'color_status_info',             // Status Info
            // Cores de Tabelas
            'color_table_header_bg',          // Fundo do Header da Tabela
            'color_table_header_text',        // Texto do Header da Tabela
            'color_table_row_hover',          // Hover da Linha da Tabela
            // Cores de Links
            'color_link',                     // Cor dos Links
            'color_link_hover',              // Cor dos Links Hover
            // Cores de Badges
            'color_badge_success',            // Badge Sucesso (Ativo)
            'color_badge_danger',            // Badge Erro (Bloqueado)
            'color_badge_info',              // Badge Info (Admin)
            'color_badge_warning',           // Badge Aviso (Usuário)
            // Cores de Inputs
            'color_input_focus',              // Borda do Input em Focus
            'color_input_focus_shadow',       // Sombra do Input em Focus
            // Cores de Mensagens
            'color_message_success_bg',       // Fundo Mensagem Sucesso
            'color_message_success_text',     // Texto Mensagem Sucesso
            'color_message_error_bg',        // Fundo Mensagem Erro
            'color_message_error_text',       // Texto Mensagem Erro
            // Cores de Modais
            'color_modal_bg',                 // Fundo do Modal
            'color_modal_header_bg',          // Fundo do Header do Modal
            'color_modal_header_text',        // Texto do Header do Modal
            // Cores de gradiente (hex)
            'bg_body_gradient_start',         // Cor inicial do gradiente do Body
            'bg_body_gradient_end',            // Cor final do gradiente do Body
            'bg_sidebar_gradient_start',      // Cor inicial do gradiente da Sidebar
            'bg_sidebar_gradient_end',        // Cor final do gradiente da Sidebar
            'bg_header_gradient_start',       // Cor inicial do gradiente do Header
            'bg_header_gradient_end'          // Cor final do gradiente do Header
        ];
        
        // Campos de tipo de fundo (solid/gradient)
        $gradient_type_keys = [
            'bg_body_type',           // Tipo de fundo do Body (solid/gradient)
            'bg_sidebar_type',        // Tipo de fundo da Sidebar (solid/gradient)
            'bg_header_type'          // Tipo de fundo do Header (solid/gradient)
        ];
        
        // Campos de direção do gradiente
        $gradient_direction_keys = [
            'bg_body_gradient_direction',      // Direção do gradiente do Body
            'bg_sidebar_gradient_direction',   // Direção do gradiente da Sidebar
            'bg_header_gradient_direction'     // Direção do gradiente do Header
        ];
        
        // Salvar cores (hex ou rgba)
        foreach ($color_keys as $key) {
            $value = trim($_POST[$key] ?? '');
            // Aceitar hex (#RRGGBB) ou rgba/rgb (exceto para color_input_focus_shadow que só aceita rgba)
            if (!empty($value) && (
                preg_match('/^#[0-9A-Fa-f]{6}$/', $value) || 
                preg_match('/^rgba?\([^)]+\)$/', $value)
            )) {
                setSystemSetting($key, $value, 'color');
            }
        }
        
        // Salvar tipos de fundo (solid/gradient)
        foreach ($gradient_type_keys as $key) {
            $value = trim($_POST[$key] ?? 'solid');
            // Validar que seja 'solid' ou 'gradient'
            if (in_array($value, ['solid', 'gradient'])) {
                setSystemSetting($key, $value, 'color');
            } else {
                // Fallback seguro: se valor inválido, usar 'solid'
                setSystemSetting($key, 'solid', 'color');
            }
        }
        
        // Salvar direções de gradiente
        foreach ($gradient_direction_keys as $key) {
            $value = trim($_POST[$key] ?? '');
            // Aceitar valores como '135deg', '45deg', 'to right', 'to left', 'to top', 'to bottom', '180deg'
            if (!empty($value) && (
                preg_match('/^\d+deg$/', $value) || 
                preg_match('/^to (right|left|top|bottom)$/', $value)
            )) {
                setSystemSetting($key, $value, 'color');
            }
        }
        
        clearSettingsCache();
        $mensagem = "Cores salvas com sucesso! Recarregue a página para ver as mudanças.";
        $tipo_mensagem = 'success';
        $activeTab = 'colors';
    } catch (Exception $e) {
        error_log("Erro ao salvar cores: " . $e->getMessage());
        $mensagem = "Erro ao salvar cores: " . $e->getMessage();
        $tipo_mensagem = 'error';
    }
}

// Processar upload de imagens
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'upload_logo') {
    try {
        $logo_type = trim($_POST['logo_type'] ?? '');
        $allowed_types = ['logo_sidebar_admin', 'logo_sidebar_user', 'logo_favicon'];
        
        if (!in_array($logo_type, $allowed_types)) {
            throw new Exception("Tipo de logo inválido");
        }
        
        if (!isset($_FILES['logo_file']) || $_FILES['logo_file']['error'] !== UPLOAD_ERR_OK) {
            throw new Exception("Erro no upload do arquivo");
        }
        
        $file = $_FILES['logo_file'];
        $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'webp', 'ico'];
        $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        
        if (!in_array($file_extension, $allowed_extensions)) {
            throw new Exception("Extensão de arquivo não permitida. Use: " . implode(', ', $allowed_extensions));
        }
        
        // Criar diretório de uploads se não existir
        $upload_dir = __DIR__ . '/../../public/uploads/branding/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        
        // Gerar nome único para o arquivo
        $new_filename = $logo_type . '_' . time() . '.' . $file_extension;
        $upload_path = $upload_dir . $new_filename;
        
        // Mover arquivo
        if (!move_uploaded_file($file['tmp_name'], $upload_path)) {
            throw new Exception("Erro ao salvar arquivo");
        }
        
        // Salvar caminho relativo no banco
        $relative_path = '/public/uploads/branding/' . $new_filename;
        setSystemSetting($logo_type, $relative_path, 'image');
        
        clearSettingsCache();
        $mensagem = "Logo enviado com sucesso! Recarregue a página para ver a mudança.";
        $tipo_mensagem = 'success';
        $activeTab = 'branding';
    } catch (Exception $e) {
        error_log("Erro ao fazer upload: " . $e->getMessage());
        $mensagem = "Erro ao fazer upload: " . $e->getMessage();
        $tipo_mensagem = 'error';
    }
}

// Carregar configurações atuais
$current_settings = getAllSystemSettings();

// Definir valores padrão se não existirem
$default_colors = [
    // Dashboard
    'color_sidebar_bg' => '#1e3a8a',
    'color_sidebar_text' => '#e0e7ff',
    'color_header_bg' => '#ffffff',
    'color_header_text' => '#1f2937',
    'color_body_bg' => '#f3f4f6',
    'color_card_bg' => '#ffffff',
    'color_text_main' => '#1f2937',
    'color_text_muted' => '#6b7280',
    'color_border' => '#e5e7eb',
    // Marketplace
    'color_marketplace_bg' => '#0f0c29',
    'color_marketplace_title' => '#667eea',
    'color_marketplace_header_bg' => '#ffffff',
    'color_marketplace_header_text' => '#e0e0e0',
    'color_marketplace_card_bg' => '#ffffff',
    'color_marketplace_product_name' => '#ffffff',
    'color_marketplace_category' => '#667eea',
    'color_marketplace_price' => '#4ade80',
    'color_marketplace_button_buy' => '#667eea',
    'color_marketplace_button_affiliate' => '#10b981',
    // Botões e Ações
    'color_button_primary' => '#009846',
    'color_button_primary_hover' => '#007635',
    'color_button_edit' => '#2196F3',
    'color_button_view' => '#17a2b8',
    'color_button_delete' => '#dc3545',
    'color_button_save' => '#28a745',
    // Status
    'color_status_success' => '#28a745',
    'color_status_warning' => '#ffc107',
    'color_status_danger' => '#dc3545',
    'color_status_info' => '#17a2b8',
    // Tabelas
    'color_table_header_bg' => '#f8f9fa',
    'color_table_header_text' => '#495057',
    'color_table_row_hover' => '#f5f5f5',
    // Links
    'color_link' => '#007bff',
    'color_link_hover' => '#0056b3',
    // Badges
    'color_badge_success' => '#28a745',
    'color_badge_danger' => '#dc3545',
    'color_badge_info' => '#17a2b8',
    'color_badge_warning' => '#ffc107',
    // Inputs
    'color_input_focus' => '#009846',
    'color_input_focus_shadow' => 'rgba(0, 152, 70, 0.25)',
    // Mensagens
    'color_message_success_bg' => '#d4edda',
    'color_message_success_text' => '#155724',
    'color_message_error_bg' => '#f8d7da',
    'color_message_error_text' => '#721c24',
    // Modais
    'color_modal_bg' => '#ffffff',
    'color_modal_header_bg' => '#f8f9fa',
    'color_modal_header_text' => '#333333'
];
?>

<style>
.customizacao-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

.customizacao-tabs {
    display: flex;
    gap: 10px;
    margin-bottom: 30px;
    border-bottom: 2px solid var(--border-color, #dee2e6);
    padding-bottom: 10px;
}

.customizacao-tab {
    padding: 12px 24px;
    background: transparent;
    border: none;
    border-bottom: 3px solid transparent;
    cursor: pointer;
    font-size: 16px;
    font-weight: 600;
    color: var(--text-muted, #6c757d);
    transition: all 0.3s;
}

.customizacao-tab:hover {
    color: var(--text-main, #333333);
}

.customizacao-tab.active {
    color: #009846;
    border-bottom-color: #009846;
}

[data-theme="dark"] .customizacao-tab.active {
    color: #4ade80;
    border-bottom-color: #4ade80;
}

.tab-content {
    display: none;
}

.tab-content.active {
    display: block;
}

.color-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 20px;
    margin-top: 20px;
}

.color-item {
    background: var(--bg-card, #ffffff);
    padding: 20px;
    border-radius: 8px;
    border: 1px solid var(--border-color, #dee2e6);
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

[data-theme="dark"] .color-item {
    background: var(--bg-card) !important;
    border-color: var(--border-color) !important;
    box-shadow: 0 2px 4px rgba(0,0,0,0.3) !important;
}

.color-item label {
    display: block;
    font-weight: 600;
    margin-bottom: 10px;
    color: var(--text-main, #333333);
    font-size: 14px;
}

.color-item .color-description {
    font-size: 12px;
    color: var(--text-muted, #6c757d);
    margin-bottom: 10px;
}

.color-item input[type="color"] {
    width: 100%;
    height: 50px;
    border: 2px solid var(--border-color, #dee2e6);
    border-radius: 6px;
    cursor: pointer;
}

.color-item input[type="text"] {
    width: 100%;
    margin-top: 10px;
    padding: 8px;
    border: 1px solid var(--border-color, #dee2e6);
    border-radius: 4px;
    font-family: monospace;
    font-size: 14px;
}

.branding-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-top: 20px;
}

.branding-item {
    background: var(--bg-card, #ffffff);
    padding: 20px;
    border-radius: 8px;
    border: 1px solid var(--border-color, #dee2e6);
    text-align: center;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

[data-theme="dark"] .branding-item {
    background: var(--bg-card) !important;
    border-color: var(--border-color) !important;
    box-shadow: 0 2px 4px rgba(0,0,0,0.3) !important;
}

.branding-item h3 {
    margin-bottom: 10px;
    color: var(--text-main, #333333);
    font-size: 16px;
}

.branding-item .logo-preview {
    width: 100%;
    max-width: 200px;
    height: 100px;
    margin: 15px auto;
    border: 2px dashed var(--border-color, #dee2e6);
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f8f9fa;
    overflow: hidden;
}

[data-theme="dark"] .branding-item .logo-preview {
    background: #1e293b;
    border-color: rgba(255, 255, 255, 0.2);
}

.branding-item .logo-preview img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}

.branding-item input[type="file"] {
    margin: 15px 0;
    width: 100%;
    font-size: 12px;
}

.btn-save {
    background: #009846;
    color: white;
    padding: 12px 30px;
    border: none;
    border-radius: 6px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    margin-top: 20px;
}

.btn-save:hover {
    background: #007635;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 152, 70, 0.3);
}

[data-theme="dark"] .btn-save {
    background: #22c55e;
    color: #ffffff;
}

[data-theme="dark"] .btn-save:hover {
    background: #16a34a;
    box-shadow: 0 4px 8px rgba(34, 197, 94, 0.4);
}

.alert {
    padding: 15px 20px;
    border-radius: 6px;
    margin-bottom: 20px;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-error {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

.info-box {
    background: #e7f3ff;
    border: 1px solid #b3d9ff;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 20px;
    color: #004085;
}

.info-box strong {
    display: block;
    margin-bottom: 5px;
}

[data-theme="dark"] .info-box {
    background: rgba(59, 130, 246, 0.15);
    border: 1px solid rgba(59, 130, 246, 0.3);
    color: #93c5fd;
}

[data-theme="dark"] .info-box strong {
    color: #bfdbfe;
}
</style>

<div class="customizacao-container">
    <h2 style="margin-bottom: 20px; color: var(--text-main, #333333);">
        <i class="fas fa-palette"></i> Customização do Sistema
    </h2>
    
    <?php if ($mensagem): ?>
    <div class="alert alert-<?= $tipo_mensagem === 'success' ? 'success' : 'error'; ?>">
        <?= htmlspecialchars($mensagem); ?>
    </div>
    <?php endif; ?>
    
    <div class="info-box">
        <strong>ℹ️ Informação Importante</strong>
        As cores configuradas aqui serão aplicadas em todo o sistema. Após salvar, recarregue a página (F5) para ver as mudanças.
    </div>
    
    <div class="customizacao-tabs">
        <button class="customizacao-tab <?= $activeTab === 'palettes' ? 'active' : ''; ?>" onclick="showTab('palettes')">
            <i class="fas fa-palette"></i> Paletas Prontas
        </button>
        <button class="customizacao-tab <?= $activeTab === 'colors' ? 'active' : ''; ?>" onclick="showTab('colors')">
            <i class="fas fa-paint-brush"></i> Cores do Sistema
        </button>
        <button class="customizacao-tab <?= $activeTab === 'branding' ? 'active' : ''; ?>" onclick="showTab('branding')">
            <i class="fas fa-image"></i> Logos
        </button>
    </div>
    
    <!-- Tab Paletas Prontas -->
    <div id="tab-palettes" class="tab-content <?= $activeTab === 'palettes' ? 'active' : ''; ?>">
        <div class="info-box" style="margin-bottom: 30px;">
            <strong>🎨 Paletas de Cores Pré-Definidas</strong>
            Escolha uma paleta pronta para aplicar automaticamente todas as cores do sistema. As cores são otimizadas para funcionar tanto no modo claro quanto no modo escuro.
        </div>
        
        <div class="palette-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-top: 20px;">
            <?php
            $palettes = [
                'cyber_future' => [
                    'name' => 'Cyber Future',
                    'description' => 'Tema futurista neon, dark e tech',
                    'preview' => ['#7000FF', '#00F0FF', '#050511', '#090919']
                ],
                'emerald_wealth' => [
                    'name' => 'Emerald Wealth',
                    'description' => 'Tema financeiro, seriedade e luxo',
                    'preview' => ['#10B981', '#064E3B', '#022C22', '#064E3B']
                ],
                'royal_obsidian' => [
                    'name' => 'Royal Obsidian',
                    'description' => 'Tema premium, preto e dourado elegante',
                    'preview' => ['#D4AF37', '#111111', '#000000', '#1A1A1A']
                ],
                'deep_ocean' => [
                    'name' => 'Deep Ocean',
                    'description' => 'Tema corporativo moderno, confiança e tecnologia',
                    'preview' => ['#3B82F6', '#1E3A8A', '#0F172A', '#1E293B']
                ],
                'sunset_valley' => [
                    'name' => 'Sunset Valley',
                    'description' => 'Tema vibrante, energético e criativo',
                    'preview' => ['#F97316', '#BE123C', '#280814', '#450A1F']
                ],
                'titanium_grey' => [
                    'name' => 'Titanium Grey',
                    'description' => 'Tema minimalista, clean estilo Apple',
                    'preview' => ['#64748B', '#94A3B8', '#18181B', '#27272A']
                ]
            ];
            
            foreach ($palettes as $palette_key => $palette):
            ?>
            <div class="palette-item" style="background: var(--bg-card, #ffffff); padding: 20px; border-radius: 8px; border: 2px solid var(--border-color, #dee2e6); cursor: pointer; transition: all 0.3s;" 
                 onmouseover="this.style.borderColor='#009846'; this.style.transform='translateY(-5px)'; this.style.boxShadow='0 4px 12px rgba(0,0,0,0.1)';" 
                 onmouseout="this.style.borderColor='var(--border-color, #dee2e6)'; this.style.transform='translateY(0)'; this.style.boxShadow='none';">
                <h3 style="margin-bottom: 10px; color: var(--text-main, #333333);"><?= htmlspecialchars($palette['name']); ?></h3>
                <p style="font-size: 12px; color: var(--text-muted, #6c757d); margin-bottom: 15px;"><?= htmlspecialchars($palette['description']); ?></p>
                <div style="display: flex; gap: 8px; margin-bottom: 15px;">
                    <?php foreach ($palette['preview'] as $color): ?>
                        <div style="width: 40px; height: 40px; background: <?= htmlspecialchars($color); ?>; border-radius: 6px; border: 1px solid #ddd;"></div>
                    <?php endforeach; ?>
                </div>
                <button type="button" class="btn-save" style="width: 100%; padding: 10px; margin-top: 10px;" onclick="event.stopPropagation(); applyPalette('<?= $palette_key; ?>')">
                    <i class="fas fa-check"></i> Aplicar Paleta
                </button>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    
    <!-- Tab Cores -->
    <div id="tab-colors" class="tab-content <?= $activeTab === 'colors' ? 'active' : ''; ?>">
        <form method="POST" action="">
            <input type="hidden" name="action" value="save_colors">
            
            <div class="color-grid">
                <div class="color-item">
                    <label>Fundo da Sidebar</label>
                    <div class="color-description">Cor de fundo do menu lateral</div>
                    <input type="color" id="color_sidebar_bg_color" value="<?= htmlspecialchars($current_settings['color_sidebar_bg']['value'] ?? $default_colors['color_sidebar_bg']); ?>" onchange="updateTextInput(this, 'color_sidebar_bg')">
                    <input type="text" name="color_sidebar_bg" value="<?= htmlspecialchars($current_settings['color_sidebar_bg']['value'] ?? $default_colors['color_sidebar_bg']); ?>" onchange="updateColorInput(this, 'color_sidebar_bg')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Texto da Sidebar</label>
                    <div class="color-description">Cor do texto dos itens do menu</div>
                    <input type="color" id="color_sidebar_text_color" value="<?= htmlspecialchars($current_settings['color_sidebar_text']['value'] ?? $default_colors['color_sidebar_text']); ?>" onchange="updateTextInput(this, 'color_sidebar_text')">
                    <input type="text" name="color_sidebar_text" value="<?= htmlspecialchars($current_settings['color_sidebar_text']['value'] ?? $default_colors['color_sidebar_text']); ?>" onchange="updateColorInput(this, 'color_sidebar_text')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Fundo do Header</label>
                    <div class="color-description">Cor de fundo do cabeçalho superior</div>
                    <input type="color" id="color_header_bg_color" value="<?= htmlspecialchars($current_settings['color_header_bg']['value'] ?? $default_colors['color_header_bg']); ?>" onchange="updateTextInput(this, 'color_header_bg')">
                    <input type="text" name="color_header_bg" value="<?= htmlspecialchars($current_settings['color_header_bg']['value'] ?? $default_colors['color_header_bg']); ?>" onchange="updateColorInput(this, 'color_header_bg')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Texto do Header</label>
                    <div class="color-description">Cor do texto do cabeçalho</div>
                    <input type="color" id="color_header_text_color" value="<?= htmlspecialchars($current_settings['color_header_text']['value'] ?? $default_colors['color_header_text']); ?>" onchange="updateTextInput(this, 'color_header_text')">
                    <input type="text" name="color_header_text" value="<?= htmlspecialchars($current_settings['color_header_text']['value'] ?? $default_colors['color_header_text']); ?>" onchange="updateColorInput(this, 'color_header_text')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Fundo do Body</label>
                    <div class="color-description">Cor de fundo da página principal</div>
                    <input type="color" id="color_body_bg_color" value="<?= htmlspecialchars($current_settings['color_body_bg']['value'] ?? $default_colors['color_body_bg']); ?>" onchange="updateTextInput(this, 'color_body_bg')">
                    <input type="text" name="color_body_bg" value="<?= htmlspecialchars($current_settings['color_body_bg']['value'] ?? $default_colors['color_body_bg']); ?>" onchange="updateColorInput(this, 'color_body_bg')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Fundo dos Cards</label>
                    <div class="color-description">Cor de fundo dos cards/panéis</div>
                    <input type="color" id="color_card_bg_color" value="<?= htmlspecialchars($current_settings['color_card_bg']['value'] ?? $default_colors['color_card_bg']); ?>" onchange="updateTextInput(this, 'color_card_bg')">
                    <input type="text" name="color_card_bg" value="<?= htmlspecialchars($current_settings['color_card_bg']['value'] ?? $default_colors['color_card_bg']); ?>" onchange="updateColorInput(this, 'color_card_bg')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Texto Principal</label>
                    <div class="color-description">Cor do texto principal do sistema</div>
                    <input type="color" id="color_text_main_color" value="<?= htmlspecialchars($current_settings['color_text_main']['value'] ?? $default_colors['color_text_main']); ?>" onchange="updateTextInput(this, 'color_text_main')">
                    <input type="text" name="color_text_main" value="<?= htmlspecialchars($current_settings['color_text_main']['value'] ?? $default_colors['color_text_main']); ?>" onchange="updateColorInput(this, 'color_text_main')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Texto Muted</label>
                    <div class="color-description">Cor do texto secundário/desabilitado</div>
                    <input type="color" id="color_text_muted_color" value="<?= htmlspecialchars($current_settings['color_text_muted']['value'] ?? $default_colors['color_text_muted']); ?>" onchange="updateTextInput(this, 'color_text_muted')">
                    <input type="text" name="color_text_muted" value="<?= htmlspecialchars($current_settings['color_text_muted']['value'] ?? $default_colors['color_text_muted']); ?>" onchange="updateColorInput(this, 'color_text_muted')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Cor das Bordas</label>
                    <div class="color-description">Cor das bordas dos elementos</div>
                    <input type="color" id="color_border_color" value="<?= htmlspecialchars($current_settings['color_border']['value'] ?? $default_colors['color_border']); ?>" onchange="updateTextInput(this, 'color_border')">
                    <input type="text" name="color_border" value="<?= htmlspecialchars($current_settings['color_border']['value'] ?? $default_colors['color_border']); ?>" onchange="updateColorInput(this, 'color_border')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
            </div>
            
            <!-- Seção de Gradientes -->
            <h3 style="margin-top: 40px; margin-bottom: 20px; color: var(--text-main, #333333); border-top: 2px solid var(--border-color, #dee2e6); padding-top: 20px;">
                <i class="fas fa-fill-drip"></i> Fundos em Gradiente (Opcional)
            </h3>
            
            <div class="info-box" style="margin-bottom: 20px;">
                <strong>💡 Sobre Gradientes</strong>
                Você pode escolher usar cores sólidas (padrão) ou criar fundos em gradiente para uma aparência mais moderna. Se selecionar "Gradiente", configure as cores inicial e final, além da direção.
            </div>
            
            <div class="color-grid">
                <!-- Gradiente do Body -->
                <div class="color-item" style="grid-column: 1 / -1;">
                    <label style="font-size: 16px; margin-bottom: 15px;">
                        <i class="fas fa-desktop"></i> Fundo do Body (Gradiente)
                    </label>
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Tipo de Fundo:</label>
                        <select name="bg_body_type" id="bg_body_type" onchange="toggleGradientFields('body', this.value)" style="width: 100%; padding: 10px; border: 1px solid var(--border-color, #dee2e6); border-radius: 6px; background: var(--bg-card, #ffffff); color: var(--text-main, #333333);">
                            <option value="solid" <?= ($current_settings['bg_body_type']['value'] ?? 'solid') === 'solid' ? 'selected' : ''; ?>>Cor Sólida</option>
                            <option value="gradient" <?= ($current_settings['bg_body_type']['value'] ?? 'solid') === 'gradient' ? 'selected' : ''; ?>>Gradiente</option>
                        </select>
                    </div>
                    <div id="body_gradient_fields" style="display: <?= ($current_settings['bg_body_type']['value'] ?? 'solid') === 'gradient' ? 'block' : 'none'; ?>; margin-top: 15px; padding-top: 15px; border-top: 1px solid var(--border-color, #dee2e6);">
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                            <div>
                                <label style="display: block; margin-bottom: 5px; font-size: 13px;">Cor Inicial:</label>
                                <input type="color" id="bg_body_gradient_start_color" value="<?= htmlspecialchars($current_settings['bg_body_gradient_start']['value'] ?? '#f3f4f6'); ?>" onchange="updateTextInput(this, 'bg_body_gradient_start')">
                                <input type="text" name="bg_body_gradient_start" value="<?= htmlspecialchars($current_settings['bg_body_gradient_start']['value'] ?? '#f3f4f6'); ?>" onchange="updateColorInput(this, 'bg_body_gradient_start')" pattern="^#[0-9A-Fa-f]{6}$" style="width: 100%; margin-top: 5px; padding: 8px; border: 1px solid var(--border-color, #dee2e6); border-radius: 4px;">
                            </div>
                            <div>
                                <label style="display: block; margin-bottom: 5px; font-size: 13px;">Cor Final:</label>
                                <input type="color" id="bg_body_gradient_end_color" value="<?= htmlspecialchars($current_settings['bg_body_gradient_end']['value'] ?? '#e5e7eb'); ?>" onchange="updateTextInput(this, 'bg_body_gradient_end')">
                                <input type="text" name="bg_body_gradient_end" value="<?= htmlspecialchars($current_settings['bg_body_gradient_end']['value'] ?? '#e5e7eb'); ?>" onchange="updateColorInput(this, 'bg_body_gradient_end')" pattern="^#[0-9A-Fa-f]{6}$" style="width: 100%; margin-top: 5px; padding: 8px; border: 1px solid var(--border-color, #dee2e6); border-radius: 4px;">
                            </div>
                        </div>
                        <div>
                            <label style="display: block; margin-bottom: 5px; font-size: 13px;">Direção do Gradiente:</label>
                            <select name="bg_body_gradient_direction" style="width: 100%; padding: 8px; border: 1px solid var(--border-color, #dee2e6); border-radius: 4px; background: var(--bg-card, #ffffff); color: var(--text-main, #333333);">
                                <option value="to right" <?= ($current_settings['bg_body_gradient_direction']['value'] ?? '135deg') === 'to right' ? 'selected' : ''; ?>>→ Direita</option>
                                <option value="to left" <?= ($current_settings['bg_body_gradient_direction']['value'] ?? '135deg') === 'to left' ? 'selected' : ''; ?>>← Esquerda</option>
                                <option value="to bottom" <?= ($current_settings['bg_body_gradient_direction']['value'] ?? '135deg') === 'to bottom' ? 'selected' : ''; ?>>↓ Para Baixo</option>
                                <option value="to top" <?= ($current_settings['bg_body_gradient_direction']['value'] ?? '135deg') === 'to top' ? 'selected' : ''; ?>>↑ Para Cima</option>
                                <option value="135deg" <?= ($current_settings['bg_body_gradient_direction']['value'] ?? '135deg') === '135deg' ? 'selected' : ''; ?>>↘ Diagonal (135°)</option>
                                <option value="45deg" <?= ($current_settings['bg_body_gradient_direction']['value'] ?? '135deg') === '45deg' ? 'selected' : ''; ?>>↗ Diagonal (45°)</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <!-- Gradiente da Sidebar -->
                <div class="color-item" style="grid-column: 1 / -1;">
                    <label style="font-size: 16px; margin-bottom: 15px;">
                        <i class="fas fa-bars"></i> Fundo da Sidebar (Gradiente)
                    </label>
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Tipo de Fundo:</label>
                        <select name="bg_sidebar_type" id="bg_sidebar_type" onchange="toggleGradientFields('sidebar', this.value)" style="width: 100%; padding: 10px; border: 1px solid var(--border-color, #dee2e6); border-radius: 6px; background: var(--bg-card, #ffffff); color: var(--text-main, #333333);">
                            <option value="solid" <?= ($current_settings['bg_sidebar_type']['value'] ?? 'solid') === 'solid' ? 'selected' : ''; ?>>Cor Sólida</option>
                            <option value="gradient" <?= ($current_settings['bg_sidebar_type']['value'] ?? 'solid') === 'gradient' ? 'selected' : ''; ?>>Gradiente</option>
                        </select>
                    </div>
                    <div id="sidebar_gradient_fields" style="display: <?= ($current_settings['bg_sidebar_type']['value'] ?? 'solid') === 'gradient' ? 'block' : 'none'; ?>; margin-top: 15px; padding-top: 15px; border-top: 1px solid var(--border-color, #dee2e6);">
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                            <div>
                                <label style="display: block; margin-bottom: 5px; font-size: 13px;">Cor Inicial:</label>
                                <input type="color" id="bg_sidebar_gradient_start_color" value="<?= htmlspecialchars($current_settings['bg_sidebar_gradient_start']['value'] ?? '#1e3a8a'); ?>" onchange="updateTextInput(this, 'bg_sidebar_gradient_start')">
                                <input type="text" name="bg_sidebar_gradient_start" value="<?= htmlspecialchars($current_settings['bg_sidebar_gradient_start']['value'] ?? '#1e3a8a'); ?>" onchange="updateColorInput(this, 'bg_sidebar_gradient_start')" pattern="^#[0-9A-Fa-f]{6}$" style="width: 100%; margin-top: 5px; padding: 8px; border: 1px solid var(--border-color, #dee2e6); border-radius: 4px;">
                            </div>
                            <div>
                                <label style="display: block; margin-bottom: 5px; font-size: 13px;">Cor Final:</label>
                                <input type="color" id="bg_sidebar_gradient_end_color" value="<?= htmlspecialchars($current_settings['bg_sidebar_gradient_end']['value'] ?? '#4c1d95'); ?>" onchange="updateTextInput(this, 'bg_sidebar_gradient_end')">
                                <input type="text" name="bg_sidebar_gradient_end" value="<?= htmlspecialchars($current_settings['bg_sidebar_gradient_end']['value'] ?? '#4c1d95'); ?>" onchange="updateColorInput(this, 'bg_sidebar_gradient_end')" pattern="^#[0-9A-Fa-f]{6}$" style="width: 100%; margin-top: 5px; padding: 8px; border: 1px solid var(--border-color, #dee2e6); border-radius: 4px;">
                            </div>
                        </div>
                        <div>
                            <label style="display: block; margin-bottom: 5px; font-size: 13px;">Direção do Gradiente:</label>
                            <select name="bg_sidebar_gradient_direction" style="width: 100%; padding: 8px; border: 1px solid var(--border-color, #dee2e6); border-radius: 4px; background: var(--bg-card, #ffffff); color: var(--text-main, #333333);">
                                <option value="180deg" <?= ($current_settings['bg_sidebar_gradient_direction']['value'] ?? '180deg') === '180deg' ? 'selected' : ''; ?>>↓ Vertical (180°)</option>
                                <option value="to right" <?= ($current_settings['bg_sidebar_gradient_direction']['value'] ?? '180deg') === 'to right' ? 'selected' : ''; ?>>→ Horizontal</option>
                                <option value="135deg" <?= ($current_settings['bg_sidebar_gradient_direction']['value'] ?? '180deg') === '135deg' ? 'selected' : ''; ?>>↘ Diagonal (135°)</option>
                                <option value="45deg" <?= ($current_settings['bg_sidebar_gradient_direction']['value'] ?? '180deg') === '45deg' ? 'selected' : ''; ?>>↗ Diagonal (45°)</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <!-- Gradiente do Header -->
                <div class="color-item" style="grid-column: 1 / -1;">
                    <label style="font-size: 16px; margin-bottom: 15px;">
                        <i class="fas fa-heading"></i> Fundo do Header (Gradiente)
                    </label>
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Tipo de Fundo:</label>
                        <select name="bg_header_type" id="bg_header_type" onchange="toggleGradientFields('header', this.value)" style="width: 100%; padding: 10px; border: 1px solid var(--border-color, #dee2e6); border-radius: 6px; background: var(--bg-card, #ffffff); color: var(--text-main, #333333);">
                            <option value="solid" <?= ($current_settings['bg_header_type']['value'] ?? 'solid') === 'solid' ? 'selected' : ''; ?>>Cor Sólida</option>
                            <option value="gradient" <?= ($current_settings['bg_header_type']['value'] ?? 'solid') === 'gradient' ? 'selected' : ''; ?>>Gradiente</option>
                        </select>
                    </div>
                    <div id="header_gradient_fields" style="display: <?= ($current_settings['bg_header_type']['value'] ?? 'solid') === 'gradient' ? 'block' : 'none'; ?>; margin-top: 15px; padding-top: 15px; border-top: 1px solid var(--border-color, #dee2e6);">
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                            <div>
                                <label style="display: block; margin-bottom: 5px; font-size: 13px;">Cor Inicial:</label>
                                <input type="color" id="bg_header_gradient_start_color" value="<?= htmlspecialchars($current_settings['bg_header_gradient_start']['value'] ?? '#ffffff'); ?>" onchange="updateTextInput(this, 'bg_header_gradient_start')">
                                <input type="text" name="bg_header_gradient_start" value="<?= htmlspecialchars($current_settings['bg_header_gradient_start']['value'] ?? '#ffffff'); ?>" onchange="updateColorInput(this, 'bg_header_gradient_start')" pattern="^#[0-9A-Fa-f]{6}$" style="width: 100%; margin-top: 5px; padding: 8px; border: 1px solid var(--border-color, #dee2e6); border-radius: 4px;">
                            </div>
                            <div>
                                <label style="display: block; margin-bottom: 5px; font-size: 13px;">Cor Final:</label>
                                <input type="color" id="bg_header_gradient_end_color" value="<?= htmlspecialchars($current_settings['bg_header_gradient_end']['value'] ?? '#f9fafb'); ?>" onchange="updateTextInput(this, 'bg_header_gradient_end')">
                                <input type="text" name="bg_header_gradient_end" value="<?= htmlspecialchars($current_settings['bg_header_gradient_end']['value'] ?? '#f9fafb'); ?>" onchange="updateColorInput(this, 'bg_header_gradient_end')" pattern="^#[0-9A-Fa-f]{6}$" style="width: 100%; margin-top: 5px; padding: 8px; border: 1px solid var(--border-color, #dee2e6); border-radius: 4px;">
                            </div>
                        </div>
                        <div>
                            <label style="display: block; margin-bottom: 5px; font-size: 13px;">Direção do Gradiente:</label>
                            <select name="bg_header_gradient_direction" style="width: 100%; padding: 8px; border: 1px solid var(--border-color, #dee2e6); border-radius: 4px; background: var(--bg-card, #ffffff); color: var(--text-main, #333333);">
                                <option value="to right" <?= ($current_settings['bg_header_gradient_direction']['value'] ?? 'to right') === 'to right' ? 'selected' : ''; ?>>→ Horizontal</option>
                                <option value="to left" <?= ($current_settings['bg_header_gradient_direction']['value'] ?? 'to right') === 'to left' ? 'selected' : ''; ?>>← Esquerda</option>
                                <option value="to bottom" <?= ($current_settings['bg_header_gradient_direction']['value'] ?? 'to right') === 'to bottom' ? 'selected' : ''; ?>>↓ Vertical</option>
                                <option value="135deg" <?= ($current_settings['bg_header_gradient_direction']['value'] ?? 'to right') === '135deg' ? 'selected' : ''; ?>>↘ Diagonal (135°)</option>
                                <option value="45deg" <?= ($current_settings['bg_header_gradient_direction']['value'] ?? 'to right') === '45deg' ? 'selected' : ''; ?>>↗ Diagonal (45°)</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            
            <h3 style="margin-top: 40px; margin-bottom: 20px; color: var(--text-main, #333333); border-top: 2px solid var(--border-color, #dee2e6); padding-top: 20px;">
                <i class="fas fa-store"></i> Cores do Marketplace
            </h3>
            
            <div class="color-grid">
                <div class="color-item">
                    <label>Fundo do Marketplace</label>
                    <div class="color-description">Cor de fundo da página do marketplace</div>
                    <input type="color" id="color_marketplace_bg_color" value="<?= htmlspecialchars($current_settings['color_marketplace_bg']['value'] ?? $default_colors['color_marketplace_bg']); ?>" onchange="updateTextInput(this, 'color_marketplace_bg')">
                    <input type="text" name="color_marketplace_bg" value="<?= htmlspecialchars($current_settings['color_marketplace_bg']['value'] ?? $default_colors['color_marketplace_bg']); ?>" onchange="updateColorInput(this, 'color_marketplace_bg')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Título do Marketplace</label>
                    <div class="color-description">Cor do título "Marketing Place"</div>
                    <input type="color" id="color_marketplace_title_color" value="<?= htmlspecialchars($current_settings['color_marketplace_title']['value'] ?? $default_colors['color_marketplace_title']); ?>" onchange="updateTextInput(this, 'color_marketplace_title')">
                    <input type="text" name="color_marketplace_title" value="<?= htmlspecialchars($current_settings['color_marketplace_title']['value'] ?? $default_colors['color_marketplace_title']); ?>" onchange="updateColorInput(this, 'color_marketplace_title')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Fundo do Topo (Filters)</label>
                    <div class="color-description">Fundo da área de filtros (será convertido para rgba com transparência)</div>
                    <input type="color" id="color_marketplace_header_bg_color" value="<?php 
                        $header_bg = $current_settings['color_marketplace_header_bg']['value'] ?? $default_colors['color_marketplace_header_bg'];
                        if (strpos($header_bg, 'rgba') !== false || strpos($header_bg, 'rgb') !== false) {
                            $header_bg = '#ffffff';
                        }
                        echo htmlspecialchars($header_bg);
                    ?>" onchange="updateTextInput(this, 'color_marketplace_header_bg')">
                    <input type="text" name="color_marketplace_header_bg" value="<?php 
                        $header_bg = $current_settings['color_marketplace_header_bg']['value'] ?? $default_colors['color_marketplace_header_bg'];
                        if (strpos($header_bg, 'rgba') !== false || strpos($header_bg, 'rgb') !== false) {
                            $header_bg = '#ffffff';
                        }
                        echo htmlspecialchars($header_bg);
                    ?>" onchange="updateColorInput(this, 'color_marketplace_header_bg')" pattern="^#[0-9A-Fa-f]{6}$" required>
                    <small style="color: var(--text-muted, #6c757d); font-size: 11px; display: block; margin-top: 5px;">Nota: Será aplicado com transparência no marketplace</small>
                </div>
                
                <div class="color-item">
                    <label>Texto do Topo (Filters)</label>
                    <div class="color-description">Cor do texto dos filtros e labels</div>
                    <input type="color" id="color_marketplace_header_text_color" value="<?= htmlspecialchars($current_settings['color_marketplace_header_text']['value'] ?? $default_colors['color_marketplace_header_text']); ?>" onchange="updateTextInput(this, 'color_marketplace_header_text')">
                    <input type="text" name="color_marketplace_header_text" value="<?= htmlspecialchars($current_settings['color_marketplace_header_text']['value'] ?? $default_colors['color_marketplace_header_text']); ?>" onchange="updateColorInput(this, 'color_marketplace_header_text')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Fundo dos Cards de Produtos</label>
                    <div class="color-description">Fundo dos cards (será convertido para rgba com transparência)</div>
                    <input type="color" id="color_marketplace_card_bg_color" value="<?php 
                        $card_bg = $current_settings['color_marketplace_card_bg']['value'] ?? $default_colors['color_marketplace_card_bg'];
                        if (strpos($card_bg, 'rgba') !== false || strpos($card_bg, 'rgb') !== false) {
                            $card_bg = '#ffffff';
                        }
                        echo htmlspecialchars($card_bg);
                    ?>" onchange="updateTextInput(this, 'color_marketplace_card_bg')">
                    <input type="text" name="color_marketplace_card_bg" value="<?php 
                        $card_bg = $current_settings['color_marketplace_card_bg']['value'] ?? $default_colors['color_marketplace_card_bg'];
                        if (strpos($card_bg, 'rgba') !== false || strpos($card_bg, 'rgb') !== false) {
                            $card_bg = '#ffffff';
                        }
                        echo htmlspecialchars($card_bg);
                    ?>" onchange="updateColorInput(this, 'color_marketplace_card_bg')" pattern="^#[0-9A-Fa-f]{6}$" required>
                    <small style="color: var(--text-muted, #6c757d); font-size: 11px; display: block; margin-top: 5px;">Nota: Será aplicado com transparência no marketplace</small>
                </div>
                
                <div class="color-item">
                    <label>Nome dos Produtos</label>
                    <div class="color-description">Cor do nome/título dos produtos</div>
                    <input type="color" id="color_marketplace_product_name_color" value="<?= htmlspecialchars($current_settings['color_marketplace_product_name']['value'] ?? $default_colors['color_marketplace_product_name']); ?>" onchange="updateTextInput(this, 'color_marketplace_product_name')">
                    <input type="text" name="color_marketplace_product_name" value="<?= htmlspecialchars($current_settings['color_marketplace_product_name']['value'] ?? $default_colors['color_marketplace_product_name']); ?>" onchange="updateColorInput(this, 'color_marketplace_product_name')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Categoria dos Produtos</label>
                    <div class="color-description">Cor da categoria/tag dos produtos</div>
                    <input type="color" id="color_marketplace_category_color" value="<?= htmlspecialchars($current_settings['color_marketplace_category']['value'] ?? $default_colors['color_marketplace_category']); ?>" onchange="updateTextInput(this, 'color_marketplace_category')">
                    <input type="text" name="color_marketplace_category" value="<?= htmlspecialchars($current_settings['color_marketplace_category']['value'] ?? $default_colors['color_marketplace_category']); ?>" onchange="updateColorInput(this, 'color_marketplace_category')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Preço dos Produtos</label>
                    <div class="color-description">Cor do preço atual dos produtos</div>
                    <input type="color" id="color_marketplace_price_color" value="<?= htmlspecialchars($current_settings['color_marketplace_price']['value'] ?? $default_colors['color_marketplace_price']); ?>" onchange="updateTextInput(this, 'color_marketplace_price')">
                    <input type="text" name="color_marketplace_price" value="<?= htmlspecialchars($current_settings['color_marketplace_price']['value'] ?? $default_colors['color_marketplace_price']); ?>" onchange="updateColorInput(this, 'color_marketplace_price')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Botão Comprar</label>
                    <div class="color-description">Cor do botão "Comprar" nos produtos</div>
                    <input type="color" id="color_marketplace_button_buy_color" value="<?= htmlspecialchars($current_settings['color_marketplace_button_buy']['value'] ?? $default_colors['color_marketplace_button_buy']); ?>" onchange="updateTextInput(this, 'color_marketplace_button_buy')">
                    <input type="text" name="color_marketplace_button_buy" value="<?= htmlspecialchars($current_settings['color_marketplace_button_buy']['value'] ?? $default_colors['color_marketplace_button_buy']); ?>" onchange="updateColorInput(this, 'color_marketplace_button_buy')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Botão Afiliar</label>
                    <div class="color-description">Cor do botão "Afiliar" nos produtos</div>
                    <input type="color" id="color_marketplace_button_affiliate_color" value="<?= htmlspecialchars($current_settings['color_marketplace_button_affiliate']['value'] ?? $default_colors['color_marketplace_button_affiliate']); ?>" onchange="updateTextInput(this, 'color_marketplace_button_affiliate')">
                    <input type="text" name="color_marketplace_button_affiliate" value="<?= htmlspecialchars($current_settings['color_marketplace_button_affiliate']['value'] ?? $default_colors['color_marketplace_button_affiliate']); ?>" onchange="updateColorInput(this, 'color_marketplace_button_affiliate')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
            </div>
            
            <h3 style="margin-top: 40px; margin-bottom: 20px; color: var(--text-main, #333333); border-top: 2px solid var(--border-color, #dee2e6); padding-top: 20px;">
                <i class="fas fa-mouse-pointer"></i> Cores de Botões e Ações
            </h3>
            
            <div class="color-grid">
                <div class="color-item">
                    <label>Botão Primário</label>
                    <div class="color-description">Cor de fundo dos botões principais</div>
                    <input type="color" id="color_button_primary_color" value="<?= htmlspecialchars($current_settings['color_button_primary']['value'] ?? $default_colors['color_button_primary']); ?>" onchange="updateTextInput(this, 'color_button_primary')">
                    <input type="text" name="color_button_primary" value="<?= htmlspecialchars($current_settings['color_button_primary']['value'] ?? $default_colors['color_button_primary']); ?>" onchange="updateColorInput(this, 'color_button_primary')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Botão Primário (Hover)</label>
                    <div class="color-description">Cor quando passa o mouse sobre botões principais</div>
                    <input type="color" id="color_button_primary_hover_color" value="<?= htmlspecialchars($current_settings['color_button_primary_hover']['value'] ?? $default_colors['color_button_primary_hover']); ?>" onchange="updateTextInput(this, 'color_button_primary_hover')">
                    <input type="text" name="color_button_primary_hover" value="<?= htmlspecialchars($current_settings['color_button_primary_hover']['value'] ?? $default_colors['color_button_primary_hover']); ?>" onchange="updateColorInput(this, 'color_button_primary_hover')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Botão Editar</label>
                    <div class="color-description">Cor dos botões de editar</div>
                    <input type="color" id="color_button_edit_color" value="<?= htmlspecialchars($current_settings['color_button_edit']['value'] ?? $default_colors['color_button_edit']); ?>" onchange="updateTextInput(this, 'color_button_edit')">
                    <input type="text" name="color_button_edit" value="<?= htmlspecialchars($current_settings['color_button_edit']['value'] ?? $default_colors['color_button_edit']); ?>" onchange="updateColorInput(this, 'color_button_edit')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Botão Visualizar</label>
                    <div class="color-description">Cor dos botões de visualizar</div>
                    <input type="color" id="color_button_view_color" value="<?= htmlspecialchars($current_settings['color_button_view']['value'] ?? $default_colors['color_button_view']); ?>" onchange="updateTextInput(this, 'color_button_view')">
                    <input type="text" name="color_button_view" value="<?= htmlspecialchars($current_settings['color_button_view']['value'] ?? $default_colors['color_button_view']); ?>" onchange="updateColorInput(this, 'color_button_view')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Botão Excluir</label>
                    <div class="color-description">Cor dos botões de excluir</div>
                    <input type="color" id="color_button_delete_color" value="<?= htmlspecialchars($current_settings['color_button_delete']['value'] ?? $default_colors['color_button_delete']); ?>" onchange="updateTextInput(this, 'color_button_delete')">
                    <input type="text" name="color_button_delete" value="<?= htmlspecialchars($current_settings['color_button_delete']['value'] ?? $default_colors['color_button_delete']); ?>" onchange="updateColorInput(this, 'color_button_delete')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Botão Salvar</label>
                    <div class="color-description">Cor dos botões de salvar</div>
                    <input type="color" id="color_button_save_color" value="<?= htmlspecialchars($current_settings['color_button_save']['value'] ?? $default_colors['color_button_save']); ?>" onchange="updateTextInput(this, 'color_button_save')">
                    <input type="text" name="color_button_save" value="<?= htmlspecialchars($current_settings['color_button_save']['value'] ?? $default_colors['color_button_save']); ?>" onchange="updateColorInput(this, 'color_button_save')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
            </div>
            
            <h3 style="margin-top: 40px; margin-bottom: 20px; color: var(--text-main, #333333); border-top: 2px solid var(--border-color, #dee2e6); padding-top: 20px;">
                <i class="fas fa-info-circle"></i> Cores de Status
            </h3>
            
            <div class="color-grid">
                <div class="color-item">
                    <label>Status Sucesso</label>
                    <div class="color-description">Cor para status de sucesso/ativo</div>
                    <input type="color" id="color_status_success_color" value="<?= htmlspecialchars($current_settings['color_status_success']['value'] ?? $default_colors['color_status_success']); ?>" onchange="updateTextInput(this, 'color_status_success')">
                    <input type="text" name="color_status_success" value="<?= htmlspecialchars($current_settings['color_status_success']['value'] ?? $default_colors['color_status_success']); ?>" onchange="updateColorInput(this, 'color_status_success')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Status Aviso</label>
                    <div class="color-description">Cor para status de aviso</div>
                    <input type="color" id="color_status_warning_color" value="<?= htmlspecialchars($current_settings['color_status_warning']['value'] ?? $default_colors['color_status_warning']); ?>" onchange="updateTextInput(this, 'color_status_warning')">
                    <input type="text" name="color_status_warning" value="<?= htmlspecialchars($current_settings['color_status_warning']['value'] ?? $default_colors['color_status_warning']); ?>" onchange="updateColorInput(this, 'color_status_warning')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Status Erro</label>
                    <div class="color-description">Cor para status de erro/bloqueado</div>
                    <input type="color" id="color_status_danger_color" value="<?= htmlspecialchars($current_settings['color_status_danger']['value'] ?? $default_colors['color_status_danger']); ?>" onchange="updateTextInput(this, 'color_status_danger')">
                    <input type="text" name="color_status_danger" value="<?= htmlspecialchars($current_settings['color_status_danger']['value'] ?? $default_colors['color_status_danger']); ?>" onchange="updateColorInput(this, 'color_status_danger')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Status Info</label>
                    <div class="color-description">Cor para status informativo</div>
                    <input type="color" id="color_status_info_color" value="<?= htmlspecialchars($current_settings['color_status_info']['value'] ?? $default_colors['color_status_info']); ?>" onchange="updateTextInput(this, 'color_status_info')">
                    <input type="text" name="color_status_info" value="<?= htmlspecialchars($current_settings['color_status_info']['value'] ?? $default_colors['color_status_info']); ?>" onchange="updateColorInput(this, 'color_status_info')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
            </div>
            
            <h3 style="margin-top: 40px; margin-bottom: 20px; color: var(--text-main, #333333); border-top: 2px solid var(--border-color, #dee2e6); padding-top: 20px;">
                <i class="fas fa-table"></i> Cores de Tabelas
            </h3>
            
            <div class="color-grid">
                <div class="color-item">
                    <label>Fundo do Header da Tabela</label>
                    <div class="color-description">Cor de fundo do cabeçalho das tabelas</div>
                    <input type="color" id="color_table_header_bg_color" value="<?= htmlspecialchars($current_settings['color_table_header_bg']['value'] ?? $default_colors['color_table_header_bg']); ?>" onchange="updateTextInput(this, 'color_table_header_bg')">
                    <input type="text" name="color_table_header_bg" value="<?= htmlspecialchars($current_settings['color_table_header_bg']['value'] ?? $default_colors['color_table_header_bg']); ?>" onchange="updateColorInput(this, 'color_table_header_bg')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Texto do Header da Tabela</label>
                    <div class="color-description">Cor do texto do cabeçalho das tabelas</div>
                    <input type="color" id="color_table_header_text_color" value="<?= htmlspecialchars($current_settings['color_table_header_text']['value'] ?? $default_colors['color_table_header_text']); ?>" onchange="updateTextInput(this, 'color_table_header_text')">
                    <input type="text" name="color_table_header_text" value="<?= htmlspecialchars($current_settings['color_table_header_text']['value'] ?? $default_colors['color_table_header_text']); ?>" onchange="updateColorInput(this, 'color_table_header_text')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Hover da Linha da Tabela</label>
                    <div class="color-description">Cor de fundo ao passar o mouse sobre linhas</div>
                    <input type="color" id="color_table_row_hover_color" value="<?= htmlspecialchars($current_settings['color_table_row_hover']['value'] ?? $default_colors['color_table_row_hover']); ?>" onchange="updateTextInput(this, 'color_table_row_hover')">
                    <input type="text" name="color_table_row_hover" value="<?= htmlspecialchars($current_settings['color_table_row_hover']['value'] ?? $default_colors['color_table_row_hover']); ?>" onchange="updateColorInput(this, 'color_table_row_hover')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
            </div>
            
            <h3 style="margin-top: 40px; margin-bottom: 20px; color: var(--text-main, #333333); border-top: 2px solid var(--border-color, #dee2e6); padding-top: 20px;">
                <i class="fas fa-link"></i> Cores de Links
            </h3>
            
            <div class="color-grid">
                <div class="color-item">
                    <label>Cor dos Links</label>
                    <div class="color-description">Cor padrão dos links</div>
                    <input type="color" id="color_link_color" value="<?= htmlspecialchars($current_settings['color_link']['value'] ?? $default_colors['color_link']); ?>" onchange="updateTextInput(this, 'color_link')">
                    <input type="text" name="color_link" value="<?= htmlspecialchars($current_settings['color_link']['value'] ?? $default_colors['color_link']); ?>" onchange="updateColorInput(this, 'color_link')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Cor dos Links (Hover)</label>
                    <div class="color-description">Cor dos links ao passar o mouse</div>
                    <input type="color" id="color_link_hover_color" value="<?= htmlspecialchars($current_settings['color_link_hover']['value'] ?? $default_colors['color_link_hover']); ?>" onchange="updateTextInput(this, 'color_link_hover')">
                    <input type="text" name="color_link_hover" value="<?= htmlspecialchars($current_settings['color_link_hover']['value'] ?? $default_colors['color_link_hover']); ?>" onchange="updateColorInput(this, 'color_link_hover')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
            </div>
            
            <h3 style="margin-top: 40px; margin-bottom: 20px; color: var(--text-main, #333333); border-top: 2px solid var(--border-color, #dee2e6); padding-top: 20px;">
                <i class="fas fa-tags"></i> Cores de Badges
            </h3>
            
            <div class="color-grid">
                <div class="color-item">
                    <label>Badge Sucesso (Ativo)</label>
                    <div class="color-description">Cor do badge de status ativo</div>
                    <input type="color" id="color_badge_success_color" value="<?= htmlspecialchars($current_settings['color_badge_success']['value'] ?? $default_colors['color_badge_success']); ?>" onchange="updateTextInput(this, 'color_badge_success')">
                    <input type="text" name="color_badge_success" value="<?= htmlspecialchars($current_settings['color_badge_success']['value'] ?? $default_colors['color_badge_success']); ?>" onchange="updateColorInput(this, 'color_badge_success')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Badge Erro (Bloqueado)</label>
                    <div class="color-description">Cor do badge de status bloqueado</div>
                    <input type="color" id="color_badge_danger_color" value="<?= htmlspecialchars($current_settings['color_badge_danger']['value'] ?? $default_colors['color_badge_danger']); ?>" onchange="updateTextInput(this, 'color_badge_danger')">
                    <input type="text" name="color_badge_danger" value="<?= htmlspecialchars($current_settings['color_badge_danger']['value'] ?? $default_colors['color_badge_danger']); ?>" onchange="updateColorInput(this, 'color_badge_danger')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Badge Info (Admin)</label>
                    <div class="color-description">Cor do badge de admin</div>
                    <input type="color" id="color_badge_info_color" value="<?= htmlspecialchars($current_settings['color_badge_info']['value'] ?? $default_colors['color_badge_info']); ?>" onchange="updateTextInput(this, 'color_badge_info')">
                    <input type="text" name="color_badge_info" value="<?= htmlspecialchars($current_settings['color_badge_info']['value'] ?? $default_colors['color_badge_info']); ?>" onchange="updateColorInput(this, 'color_badge_info')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Badge Aviso (Usuário)</label>
                    <div class="color-description">Cor do badge de usuário comum</div>
                    <input type="color" id="color_badge_warning_color" value="<?= htmlspecialchars($current_settings['color_badge_warning']['value'] ?? $default_colors['color_badge_warning']); ?>" onchange="updateTextInput(this, 'color_badge_warning')">
                    <input type="text" name="color_badge_warning" value="<?= htmlspecialchars($current_settings['color_badge_warning']['value'] ?? $default_colors['color_badge_warning']); ?>" onchange="updateColorInput(this, 'color_badge_warning')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
            </div>
            
            <h3 style="margin-top: 40px; margin-bottom: 20px; color: var(--text-main, #333333); border-top: 2px solid var(--border-color, #dee2e6); padding-top: 20px;">
                <i class="fas fa-keyboard"></i> Cores de Inputs
            </h3>
            
            <div class="color-grid">
                <div class="color-item">
                    <label>Borda do Input (Focus)</label>
                    <div class="color-description">Cor da borda quando o input está em foco</div>
                    <input type="color" id="color_input_focus_color" value="<?= htmlspecialchars($current_settings['color_input_focus']['value'] ?? $default_colors['color_input_focus']); ?>" onchange="updateTextInput(this, 'color_input_focus')">
                    <input type="text" name="color_input_focus" value="<?= htmlspecialchars($current_settings['color_input_focus']['value'] ?? $default_colors['color_input_focus']); ?>" onchange="updateColorInput(this, 'color_input_focus')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Sombra do Input (Focus)</label>
                    <div class="color-description">Cor da sombra quando o input está em foco (rgba)</div>
                    <input type="text" name="color_input_focus_shadow" value="<?= htmlspecialchars($current_settings['color_input_focus_shadow']['value'] ?? $default_colors['color_input_focus_shadow']); ?>" placeholder="rgba(0, 152, 70, 0.25)" pattern="^rgba?\([^)]+\)$" required>
                    <small style="color: var(--text-muted, #6c757d); font-size: 11px; display: block; margin-top: 5px;">Formato: rgba(r, g, b, a)</small>
                </div>
            </div>
            
            <h3 style="margin-top: 40px; margin-bottom: 20px; color: var(--text-main, #333333); border-top: 2px solid var(--border-color, #dee2e6); padding-top: 20px;">
                <i class="fas fa-comment-alt"></i> Cores de Mensagens
            </h3>
            
            <div class="color-grid">
                <div class="color-item">
                    <label>Fundo Mensagem Sucesso</label>
                    <div class="color-description">Fundo das mensagens de sucesso</div>
                    <input type="color" id="color_message_success_bg_color" value="<?= htmlspecialchars($current_settings['color_message_success_bg']['value'] ?? $default_colors['color_message_success_bg']); ?>" onchange="updateTextInput(this, 'color_message_success_bg')">
                    <input type="text" name="color_message_success_bg" value="<?= htmlspecialchars($current_settings['color_message_success_bg']['value'] ?? $default_colors['color_message_success_bg']); ?>" onchange="updateColorInput(this, 'color_message_success_bg')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Texto Mensagem Sucesso</label>
                    <div class="color-description">Texto das mensagens de sucesso</div>
                    <input type="color" id="color_message_success_text_color" value="<?= htmlspecialchars($current_settings['color_message_success_text']['value'] ?? $default_colors['color_message_success_text']); ?>" onchange="updateTextInput(this, 'color_message_success_text')">
                    <input type="text" name="color_message_success_text" value="<?= htmlspecialchars($current_settings['color_message_success_text']['value'] ?? $default_colors['color_message_success_text']); ?>" onchange="updateColorInput(this, 'color_message_success_text')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Fundo Mensagem Erro</label>
                    <div class="color-description">Fundo das mensagens de erro</div>
                    <input type="color" id="color_message_error_bg_color" value="<?= htmlspecialchars($current_settings['color_message_error_bg']['value'] ?? $default_colors['color_message_error_bg']); ?>" onchange="updateTextInput(this, 'color_message_error_bg')">
                    <input type="text" name="color_message_error_bg" value="<?= htmlspecialchars($current_settings['color_message_error_bg']['value'] ?? $default_colors['color_message_error_bg']); ?>" onchange="updateColorInput(this, 'color_message_error_bg')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Texto Mensagem Erro</label>
                    <div class="color-description">Texto das mensagens de erro</div>
                    <input type="color" id="color_message_error_text_color" value="<?= htmlspecialchars($current_settings['color_message_error_text']['value'] ?? $default_colors['color_message_error_text']); ?>" onchange="updateTextInput(this, 'color_message_error_text')">
                    <input type="text" name="color_message_error_text" value="<?= htmlspecialchars($current_settings['color_message_error_text']['value'] ?? $default_colors['color_message_error_text']); ?>" onchange="updateColorInput(this, 'color_message_error_text')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
            </div>
            
            <h3 style="margin-top: 40px; margin-bottom: 20px; color: var(--text-main, #333333); border-top: 2px solid var(--border-color, #dee2e6); padding-top: 20px;">
                <i class="fas fa-window-maximize"></i> Cores de Modais
            </h3>
            
            <div class="color-grid">
                <div class="color-item">
                    <label>Fundo do Modal</label>
                    <div class="color-description">Cor de fundo dos modais</div>
                    <input type="color" id="color_modal_bg_color" value="<?= htmlspecialchars($current_settings['color_modal_bg']['value'] ?? $default_colors['color_modal_bg']); ?>" onchange="updateTextInput(this, 'color_modal_bg')">
                    <input type="text" name="color_modal_bg" value="<?= htmlspecialchars($current_settings['color_modal_bg']['value'] ?? $default_colors['color_modal_bg']); ?>" onchange="updateColorInput(this, 'color_modal_bg')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Fundo do Header do Modal</label>
                    <div class="color-description">Cor de fundo do cabeçalho dos modais</div>
                    <input type="color" id="color_modal_header_bg_color" value="<?= htmlspecialchars($current_settings['color_modal_header_bg']['value'] ?? $default_colors['color_modal_header_bg']); ?>" onchange="updateTextInput(this, 'color_modal_header_bg')">
                    <input type="text" name="color_modal_header_bg" value="<?= htmlspecialchars($current_settings['color_modal_header_bg']['value'] ?? $default_colors['color_modal_header_bg']); ?>" onchange="updateColorInput(this, 'color_modal_header_bg')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
                
                <div class="color-item">
                    <label>Texto do Header do Modal</label>
                    <div class="color-description">Cor do texto do cabeçalho dos modais</div>
                    <input type="color" id="color_modal_header_text_color" value="<?= htmlspecialchars($current_settings['color_modal_header_text']['value'] ?? $default_colors['color_modal_header_text']); ?>" onchange="updateTextInput(this, 'color_modal_header_text')">
                    <input type="text" name="color_modal_header_text" value="<?= htmlspecialchars($current_settings['color_modal_header_text']['value'] ?? $default_colors['color_modal_header_text']); ?>" onchange="updateColorInput(this, 'color_modal_header_text')" pattern="^#[0-9A-Fa-f]{6}$" required>
                </div>
            </div>
            
            <button type="submit" class="btn-save">
                <i class="fas fa-save"></i> Salvar Cores
            </button>
        </form>
    </div>
    
    <!-- Tab Branding -->
    <div id="tab-branding" class="tab-content <?= $activeTab === 'branding' ? 'active' : ''; ?>">
        <div class="branding-grid">
            <?php
            $logos = [
                'logo_sidebar_admin' => ['title' => 'Logo Sidebar (Admin)', 'desc' => 'Logo exibido na sidebar do painel admin'],
                'logo_sidebar_user' => ['title' => 'Logo Sidebar (Usuário)', 'desc' => 'Logo exibido na sidebar do painel do usuário'],
                'logo_favicon' => ['title' => 'Favicon', 'desc' => 'Ícone exibido na aba do navegador (16x16 ou 32x32px)']
            ];
            
            foreach ($logos as $logo_key => $logo_info):
                $current_logo = $current_settings[$logo_key]['value'] ?? '';
            ?>
            <div class="branding-item">
                <h3><?= htmlspecialchars($logo_info['title']); ?></h3>
                <p style="font-size: 12px; color: var(--text-muted, #6c757d); margin-bottom: 15px;">
                    <?= htmlspecialchars($logo_info['desc']); ?>
                </p>
                <div class="logo-preview">
                    <?php if (!empty($current_logo)): ?>
                        <img src="<?= htmlspecialchars($current_logo); ?>" alt="Preview" onerror="this.parentElement.innerHTML='<i class=\'fas fa-image\' style=\'font-size: 40px; color: #ccc;\'></i>'">
                    <?php else: ?>
                        <i class="fas fa-image" style="font-size: 40px; color: #ccc;"></i>
                    <?php endif; ?>
                </div>
                <form method="POST" enctype="multipart/form-data" style="margin-top: 15px;">
                    <input type="hidden" name="action" value="upload_logo">
                    <input type="hidden" name="logo_type" value="<?= htmlspecialchars($logo_key); ?>">
                    <input type="file" name="logo_file" accept="image/*" required>
                    <button type="submit" class="btn-save" style="width: 100%; margin-top: 10px; padding: 8px;">
                        <i class="fas fa-upload"></i> Enviar Logo
                    </button>
                </form>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<script>
function showTab(tabName) {
    // Esconder todas as tabs
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.remove('active');
    });
    
    // Remover active de todos os botões
    document.querySelectorAll('.customizacao-tab').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // Mostrar tab selecionada
    document.getElementById('tab-' + tabName).classList.add('active');
    event.target.classList.add('active');
    
    // Atualizar URL sem recarregar
    const url = new URL(window.location);
    url.searchParams.set('tab', tabName);
    window.history.pushState({}, '', url);
}

function toggleGradientFields(section, type) {
    const gradientFields = document.getElementById(section + '_gradient_fields');
    if (gradientFields) {
        gradientFields.style.display = (type === 'gradient') ? 'block' : 'none';
    }
}

function updateTextInput(colorInput, fieldName) {
    const textInput = colorInput.parentElement.querySelector('input[name="' + fieldName + '"]');
    if (textInput) {
        textInput.value = colorInput.value;
    }
}

function updateColorInput(textInput, fieldName) {
    const colorInput = textInput.parentElement.querySelector('input[type="color"]');
    if (colorInput && /^#[0-9A-Fa-f]{6}$/.test(textInput.value)) {
        colorInput.value = textInput.value;
    }
}

// Paletas pré-definidas
const palettes = {
    'cyber_future': {
        'color_sidebar_bg': '#050511',
        'color_sidebar_text': '#00F0FF',
        'color_header_bg': '#090919',
        'color_header_text': '#ffffff',
        'color_body_bg': '#020617',
        'color_card_bg': '#0f172a',
        'color_text_main': '#ffffff',
        'color_text_muted': '#94a3b8',
        'color_border': 'rgba(0, 240, 255, 0.2)',
        'color_button_primary': '#7000FF',
        'color_button_primary_hover': '#5a00cc'
    },
    'emerald_wealth': {
        'color_sidebar_bg': '#022C22',
        'color_sidebar_text': '#34D399',
        'color_header_bg': '#064E3B',
        'color_header_text': '#ffffff',
        'color_body_bg': '#011F18',
        'color_card_bg': '#064E3B',
        'color_text_main': '#ffffff',
        'color_text_muted': '#6ee7b7',
        'color_border': 'rgba(16, 185, 129, 0.3)',
        'color_button_primary': '#10B981',
        'color_button_primary_hover': '#059669'
    },
    'royal_obsidian': {
        'color_sidebar_bg': '#000000',
        'color_sidebar_text': '#F3E5AB',
        'color_header_bg': '#1A1A1A',
        'color_header_text': '#D4AF37',
        'color_body_bg': '#111111',
        'color_card_bg': '#1A1A1A',
        'color_text_main': '#F3E5AB',
        'color_text_muted': '#D4AF37',
        'color_border': 'rgba(212, 175, 55, 0.3)',
        'color_button_primary': '#D4AF37',
        'color_button_primary_hover': '#B8941F'
    },
    'deep_ocean': {
        'color_sidebar_bg': '#0F172A',
        'color_sidebar_text': '#E0E7FF',
        'color_header_bg': '#1E293B',
        'color_header_text': '#ffffff',
        'color_body_bg': '#020617',
        'color_card_bg': '#1E293B',
        'color_text_main': '#ffffff',
        'color_text_muted': '#94a3b8',
        'color_border': 'rgba(59, 130, 246, 0.3)',
        'color_button_primary': '#3B82F6',
        'color_button_primary_hover': '#2563EB'
    },
    'sunset_valley': {
        'color_sidebar_bg': '#280814',
        'color_sidebar_text': '#FED7AA',
        'color_header_bg': '#450A1F',
        'color_header_text': '#ffffff',
        'color_body_bg': '#1A0409',
        'color_card_bg': '#450A1F',
        'color_text_main': '#ffffff',
        'color_text_muted': '#FCA5A5',
        'color_border': 'rgba(249, 115, 22, 0.3)',
        'color_button_primary': '#F97316',
        'color_button_primary_hover': '#EA580C'
    },
    'titanium_grey': {
        'color_sidebar_bg': '#18181B',
        'color_sidebar_text': '#E2E8F0',
        'color_header_bg': '#27272A',
        'color_header_text': '#ffffff',
        'color_body_bg': '#09090B',
        'color_card_bg': '#27272A',
        'color_text_main': '#ffffff',
        'color_text_muted': '#94A3B8',
        'color_border': 'rgba(100, 116, 139, 0.3)',
        'color_button_primary': '#64748B',
        'color_button_primary_hover': '#475569'
    }
};

function applyPalette(paletteKey) {
    if (!palettes[paletteKey]) {
        alert('Paleta não encontrada!');
        return;
    }
    
    const palette = palettes[paletteKey];
    const form = document.querySelector('form[action=""]');
    
    if (!form) {
        alert('Formulário não encontrado!');
        return;
    }
    
    // Preencher todos os campos do formulário
    for (const [key, value] of Object.entries(palette)) {
        const textInput = form.querySelector('input[name="' + key + '"]');
        const colorInput = form.querySelector('input[type="color"]#' + key + '_color');
        
        if (textInput) {
            textInput.value = value;
        }
        if (colorInput) {
            colorInput.value = value;
        }
    }
    
    // Mostrar mensagem de confirmação
    if (confirm('Paleta "' + paletteKey.charAt(0).toUpperCase() + paletteKey.slice(1) + '" aplicada! Deseja salvar as alterações agora?')) {
        // Criar input hidden para ação
        const actionInput = document.createElement('input');
        actionInput.type = 'hidden';
        actionInput.name = 'action';
        actionInput.value = 'save_colors';
        form.appendChild(actionInput);
        form.submit();
    } else {
        alert('Paleta aplicada visualmente. Role a página para ver os campos preenchidos. Clique em "Salvar Cores" para aplicar permanentemente.');
    }
}
</script>
