// 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';
}

function previewHeroImage(input) {
    if (input.files && input.files[0]) {
        const file = input.files[0];
        if (file.size > 5 * 1024 * 1024) {
            alert('O arquivo é muito grande. O tamanho máximo é 5MB.');
            input.value = '';
            return;
        }

        const reader = new FileReader();
        reader.onload = function(e) {
            const previewBox = document.getElementById('heroPreviewBox');
            previewBox.innerHTML = '<img src="' + e.target.result + '" alt="Hero Preview" id="heroPreviewImg" style="width: 100%; height: 100%; object-fit: cover;"><button type="button" class="logo-remove-btn" onclick="removeHeroImage()"><iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon></button>';
        };
        reader.readAsDataURL(file);
    }
}

function removeHeroImage() {
    const previewBox = document.getElementById('heroPreviewBox');
    previewBox.innerHTML = '<div class="logo-placeholder" id="heroPlaceholder"><iconify-icon icon="solar:gallery-add-bold"></iconify-icon><span>Clique para enviar imagem</span></div>';
    document.getElementById('heroImageInput').value = '';
}

// Clique no preview do hero abre o file input
document.getElementById('heroPreviewBox')?.addEventListener('click', function(e) {
    if (!e.target.closest('.logo-remove-btn')) {
        document.getElementById('heroImageInput').click();
    }
});


// 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="toggle-switch" title="Ativar/Desativar">
                    <input type="checkbox" name="section_enabled[${newIndex}]" value="1" checked>
                    <span class="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>
        `;
    }
}


// ========================================
// 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);
}
