<?php
/**
 * IMZ Ad Formats & Preview System
 * 
 * Este ficheiro NÃO substitui o ads-system.php.
 * Deve ser incluído (require_once) no plugin principal.
 * Adiciona:
 *  - Definição de formatos de anúncio (como AdSense)
 *  - Preview em tempo real no admin
 *  - Substituição do formulário de criação
 */

if (!defined('ABSPATH')) exit;

// =============================================================================
// 1. DEFINIÇÃO DOS FORMATOS DE ANÚNCIO
// =============================================================================

function imz_get_ad_formats() {
    return [
        'leaderboard' => [
            'name'        => 'Banner Horizontal',
            'slug'        => 'leaderboard',
            'width'       => 728,
            'height'      => 90,
            'label'       => '728 × 90',
            'description' => 'Clássico leaderboard. Ideal entre secções de conteúdo, parceiros e patrocinadores.',
            'icon'        => '📐',
            'css_class'   => 'imz-fmt-leaderboard',
            'placement'   => 'Entre conteúdo',
        ],
        'rectangle' => [
            'name'        => 'Retângulo Médio',
            'slug'        => 'rectangle',
            'width'       => 300,
            'height'      => 250,
            'label'       => '300 × 250',
            'description' => 'O formato mais universal. Sidebar, entre conteúdo, promoções de eventos.',
            'icon'        => '🖼️',
            'css_class'   => 'imz-fmt-rectangle',
            'placement'   => 'Sidebar / Conteúdo',
        ],
        'native_card' => [
            'name'        => 'Card Nativo',
            'slug'        => 'native_card',
            'width'       => 350,
            'height'      => 280,
            'label'       => '350 × 280',
            'description' => 'Parece uma música normal da plataforma com badge "Patrocinado". Melhor engagement.',
            'icon'        => '🎵',
            'css_class'   => 'imz-fmt-native',
            'placement'   => 'Feed / Conteúdo',
        ],
        'mobile_banner' => [
            'name'        => 'Banner Mobile',
            'slug'        => 'mobile_banner',
            'width'       => 320,
            'height'      => 100,
            'label'       => '320 × 100',
            'description' => 'Optimizado para telemóvel, compacto e eficiente.',
            'icon'        => '📱',
            'css_class'   => 'imz-fmt-mobile',
            'placement'   => 'Mobile',
        ],
        'stories' => [
            'name'        => 'Stories / Vertical',
            'slug'        => 'stories',
            'width'       => 360,
            'height'      => 640,
            'label'       => '360 × 640',
            'description' => 'Formato vertical tipo Instagram Stories. Promoções visuais de artistas.',
            'icon'        => '📲',
            'css_class'   => 'imz-fmt-stories',
            'placement'   => 'Overlay / Modal',
        ],
    ];
}


// =============================================================================
// 2. FORMULÁRIO DE CRIAÇÃO COM PREVIEW (ADMIN)
// =============================================================================

/**
 * Renderiza o formulário de criação de anúncio com seleção de formato e preview.
 * Substituir a secção elseif ($view === 'create') no ads-system.php.
 */
function imz_render_ad_create_form_with_preview() {
    $formats = imz_get_ad_formats();
    ?>
    <style>
    .imz-ad-create-wrap {
        display: grid;
        grid-template-columns: 1fr 400px;
        gap: 24px;
        align-items: start;
    }
    @media (max-width: 1100px) {
        .imz-ad-create-wrap { grid-template-columns: 1fr; }
        .imz-ad-preview-panel { order: -1; }
    }

    /* Formato cards */
    .imz-fmt-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
        gap: 10px;
        margin-bottom: 20px;
    }
    .imz-fmt-card {
        border: 2px solid #e5e7eb;
        border-radius: 10px;
        padding: 14px;
        cursor: pointer;
        transition: all 0.2s;
        background: #fff;
        text-align: center;
        position: relative;
    }
    .imz-fmt-card:hover { border-color: #93c5fd; background: #f0f7ff; }
    .imz-fmt-card.selected { border-color: #2563eb; background: #eff6ff; box-shadow: 0 0 0 2px rgba(37,99,235,0.2); }
    .imz-fmt-card.selected::after {
        content: '✓'; position: absolute; top: 8px; right: 8px;
        width: 20px; height: 20px; background: #2563eb; color: #fff;
        border-radius: 50%; display: flex; align-items: center; justify-content: center;
        font-size: 11px; font-weight: 700;
    }
    .imz-fmt-icon { font-size: 24px; display: block; margin-bottom: 6px; }
    .imz-fmt-name { font-size: 13px; font-weight: 700; color: #111; margin: 0 0 2px; }
    .imz-fmt-dims { font-size: 11px; color: #6b7280; margin: 0 0 4px; font-family: monospace; }
    .imz-fmt-desc { font-size: 11px; color: #9ca3af; margin: 0; line-height: 1.3; }
    .imz-fmt-thumb {
        width: 100%; max-width: 120px; margin: 8px auto 0; display: block;
        border: 1px solid #e5e7eb; border-radius: 4px; background: #f9fafb;
    }

    /* Preview Panel */
    .imz-ad-preview-panel {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 12px;
        overflow: hidden;
        position: sticky;
        top: 40px;
    }
    .imz-ad-preview-header {
        background: #f9fafb;
        padding: 14px 18px;
        border-bottom: 1px solid #e5e7eb;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .imz-ad-preview-header h4 { margin: 0; font-size: 14px; color: #374151; }
    .imz-ad-preview-header span { font-size: 11px; color: #9ca3af; font-family: monospace; }
    .imz-ad-preview-body {
        padding: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 200px;
        background: #1a1a1a;
    }
    .imz-ad-preview-frame {
        border: 1px dashed #444;
        border-radius: 8px;
        overflow: hidden;
        position: relative;
        display: flex;
        flex-direction: column;
        background: #222;
        transition: width 0.3s, height 0.3s;
    }
    .imz-ad-preview-frame img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: block;
    }
    .imz-ad-preview-placeholder {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        color: #555;
        font-size: 12px;
        gap: 6px;
        text-align: center;
        padding: 10px;
        box-sizing: border-box;
    }
    .imz-ad-preview-placeholder svg { width: 32px; height: 32px; stroke: #555; }
    .imz-ad-preview-badge {
        position: absolute;
        top: 6px;
        left: 6px;
        background: rgba(0,0,0,0.6);
        color: #9ca3af;
        font-size: 9px;
        font-weight: 600;
        padding: 2px 6px;
        border-radius: 3px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        backdrop-filter: blur(4px);
    }
    .imz-ad-preview-text-overlay {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background: linear-gradient(transparent, rgba(0,0,0,0.8));
        padding: 20px 12px 10px;
    }
    .imz-ad-preview-text-overlay .ad-title {
        color: #fff;
        font-size: 13px;
        font-weight: 700;
        margin: 0 0 2px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .imz-ad-preview-text-overlay .ad-desc {
        color: #aaa;
        font-size: 11px;
        margin: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .imz-ad-preview-info {
        padding: 12px 18px;
        background: #f9fafb;
        border-top: 1px solid #e5e7eb;
        font-size: 11px;
        color: #6b7280;
        line-height: 1.6;
    }
    .imz-ad-preview-info strong { color: #374151; }

    /* Form fields */
    .imz-ad-create-form label {
        display: block;
        font-size: 13px;
        font-weight: 600;
        color: #374151;
        margin-bottom: 4px;
    }
    .imz-ad-create-form input[type=text],
    .imz-ad-create-form input[type=url],
    .imz-ad-create-form input[type=number],
    .imz-ad-create-form textarea,
    .imz-ad-create-form select {
        width: 100%;
        padding: 8px 10px;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        font-size: 13px;
        box-sizing: border-box;
        margin-bottom: 14px;
    }
    .imz-ad-create-form textarea { height: 60px; resize: vertical; }
    .imz-ad-create-form .field-hint {
        font-size: 11px;
        color: #9ca3af;
        margin: -10px 0 14px;
    }
    .imz-ad-form-section {
        margin-bottom: 20px;
        padding-bottom: 20px;
        border-bottom: 1px solid #f3f4f6;
    }
    .imz-ad-form-section h4 {
        font-size: 14px;
        font-weight: 700;
        color: #111;
        margin: 0 0 12px;
    }
    </style>

    <div class="imz-ad-create-wrap">
        <!-- FORMULÁRIO -->
        <div class="imz-ads-box">
            <h3>➕ Criar Novo Anúncio</h3>
            <form method="post" class="imz-ad-create-form" id="imz-ad-create-form">
                <?php wp_nonce_field('imz_admin_create_ad_action', '_imz_admin_ad_nonce'); ?>

                <!-- 1. Escolha do formato -->
                <div class="imz-ad-form-section">
                    <h4>1. Escolha o Formato</h4>
                    <div class="imz-fmt-grid">
                        <?php $first = true; foreach ($formats as $key => $fmt): ?>
                        <div class="imz-fmt-card<?php echo $first ? ' selected' : ''; ?>" data-format="<?php echo esc_attr($key); ?>" data-width="<?php echo $fmt['width']; ?>" data-height="<?php echo $fmt['height']; ?>">
                            <span class="imz-fmt-icon"><?php echo $fmt['icon']; ?></span>
                            <p class="imz-fmt-name"><?php echo esc_html($fmt['name']); ?></p>
                            <p class="imz-fmt-dims"><?php echo esc_html($fmt['label']); ?></p>
                            <p class="imz-fmt-desc"><?php echo esc_html($fmt['description']); ?></p>
                            <!-- Mini thumbnail do formato -->
                            <div class="imz-fmt-thumb" style="aspect-ratio: <?php echo $fmt['width']; ?>/<?php echo $fmt['height']; ?>; max-height: 60px;"></div>
                        </div>
                        <?php $first = false; endforeach; ?>
                    </div>
                    <input type="hidden" name="ad_format" id="imz-ad-format" value="leaderboard">
                    <input type="hidden" name="ad_type" value="banner">
                </div>

                <!-- 2. Conteúdo -->
                <div class="imz-ad-form-section">
                    <h4>2. Conteúdo do Anúncio</h4>
                    <label>Título *</label>
                    <input type="text" name="ad_title" id="imz-ad-title" required placeholder="Ex: Promoção de Verão" oninput="imzUpdatePreview()">

                    <label>Texto / Descrição</label>
                    <textarea name="ad_text" id="imz-ad-text" placeholder="Uma breve descrição..." oninput="imzUpdatePreview()"></textarea>

                    <label>URL da Imagem *</label>
                    <input type="url" name="ad_image_url" id="imz-ad-image" placeholder="https://seusite.com/imagem.jpg" oninput="imzUpdatePreview()">
                    <p class="field-hint">Use uma imagem com as dimensões recomendadas para o formato escolhido.</p>

                    <label>Link de Destino</label>
                    <input type="url" name="ad_link" id="imz-ad-link" placeholder="https://...">
                </div>

                <!-- 3. Configuração -->
                <div class="imz-ad-form-section">
                    <h4>3. Configuração</h4>
                    <label>Duração (dias)</label>
                    <input type="number" name="ad_duration" value="7" min="1" max="365" style="width:100px;">

                    <?php imz_render_geo_targeting_fields('', ''); ?>

                    <label>Label do Badge</label>
                    <input type="text" name="ad_label" value="Anúncio" placeholder="Anúncio" id="imz-ad-label" oninput="imzUpdatePreview()">
                </div>

                <button type="submit" name="imz_admin_create_ad" class="button button-primary button-hero" style="width:100%;">
                    Criar e Ativar Anúncio
                </button>
            </form>
        </div>

        <!-- PREVIEW -->
        <div class="imz-ad-preview-panel">
            <div class="imz-ad-preview-header">
                <h4>Preview em Tempo Real</h4>
                <span id="imz-preview-dims">728 × 90</span>
            </div>
            <div class="imz-ad-preview-body" id="imz-preview-body">
                <div class="imz-ad-preview-frame" id="imz-preview-frame" style="width: 364px; height: 45px;">
                    <span class="imz-ad-preview-badge" id="imz-preview-badge">Anúncio</span>
                    <div class="imz-ad-preview-placeholder" id="imz-preview-placeholder">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/></svg>
                        <span>Cole a URL da imagem</span>
                    </div>
                    <img id="imz-preview-img" src="" alt="" style="display:none;">
                    <div class="imz-ad-preview-text-overlay" id="imz-preview-overlay" style="display:none;">
                        <p class="ad-title" id="imz-preview-title"></p>
                        <p class="ad-desc" id="imz-preview-desc"></p>
                    </div>
                </div>
            </div>
            <div class="imz-ad-preview-info" id="imz-preview-info">
                <strong>Banner Horizontal</strong> — 728 × 90px<br>
                Ideal entre secções de conteúdo, parceiros e patrocinadores.<br>
                Posicionamento: Entre conteúdo
            </div>
        </div>
    </div>

    <script>
    (function() {
        var formats = <?php echo json_encode($formats); ?>;
        var currentFormat = 'leaderboard';
        var previewMaxWidth = 370;

        // Selecção de formato
        document.querySelectorAll('.imz-fmt-card').forEach(function(card) {
            card.addEventListener('click', function() {
                document.querySelectorAll('.imz-fmt-card').forEach(function(c) { c.classList.remove('selected'); });
                this.classList.add('selected');
                currentFormat = this.getAttribute('data-format');
                document.getElementById('imz-ad-format').value = currentFormat;

                // Mapear formato para tipo antigo (compatibilidade)
                var typeMap = {
                    'leaderboard': 'banner',
                    'rectangle': 'destaque',
                    'native_card': 'destaque',
                    'mobile_banner': 'banner',
                    'stories': 'sidebar'
                };
                var typeInput = document.querySelector('input[name="ad_type"]');
                if (typeInput) typeInput.value = typeMap[currentFormat] || 'banner';

                imzUpdatePreview();
            });
        });

        // Preview update
        window.imzUpdatePreview = function() {
            var fmt = formats[currentFormat];
            if (!fmt) return;

            var frame = document.getElementById('imz-preview-frame');
            var dims = document.getElementById('imz-preview-dims');
            var info = document.getElementById('imz-preview-info');
            var img = document.getElementById('imz-preview-img');
            var placeholder = document.getElementById('imz-preview-placeholder');
            var overlay = document.getElementById('imz-preview-overlay');
            var badge = document.getElementById('imz-preview-badge');
            var titleEl = document.getElementById('imz-preview-title');
            var descEl = document.getElementById('imz-preview-desc');

            // Calcular escala para caber no painel
            var scale = Math.min(previewMaxWidth / fmt.width, 1);
            var displayW = Math.round(fmt.width * scale);
            var displayH = Math.round(fmt.height * scale);

            frame.style.width = displayW + 'px';
            frame.style.height = displayH + 'px';

            dims.textContent = fmt.width + ' × ' + fmt.height;
            info.innerHTML = '<strong>' + fmt.name + '</strong> — ' + fmt.label + '<br>' + fmt.description + '<br>Posicionamento: ' + fmt.placement;

            // Imagem
            var imgUrl = document.getElementById('imz-ad-image').value.trim();
            if (imgUrl) {
                img.src = imgUrl;
                img.style.display = 'block';
                placeholder.style.display = 'none';
                img.onerror = function() {
                    img.style.display = 'none';
                    placeholder.style.display = 'flex';
                    placeholder.querySelector('span').textContent = 'Imagem inválida';
                };
            } else {
                img.style.display = 'none';
                placeholder.style.display = 'flex';
                placeholder.querySelector('span').textContent = 'Cole a URL da imagem';
            }

            // Título e descrição
            var title = document.getElementById('imz-ad-title').value.trim();
            var desc = document.getElementById('imz-ad-text').value.trim();
            if (title || desc) {
                overlay.style.display = 'block';
                titleEl.textContent = title || '';
                descEl.textContent = desc || '';
            } else {
                overlay.style.display = 'none';
            }

            // Badge
            var labelVal = document.getElementById('imz-ad-label').value.trim();
            badge.textContent = labelVal || 'Anúncio';
        };

        // Init
        imzUpdatePreview();
    })();
    </script>
    <?php
}


// =============================================================================
// 3. GUARDAR FORMATO NO META DO ANÚNCIO
// =============================================================================

/**
 * Hook para adicionar o formato ao meta quando o admin cria um anúncio.
 * Deve ser chamado no handler de criação existente no ads-system.php.
 */
add_action('save_post_imz_anuncio', 'imz_save_ad_format_meta', 10, 3);
function imz_save_ad_format_meta($post_id, $post, $update) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if ($post->post_type !== 'imz_anuncio') return;
    
    // O formato vem do formulário POST
    if (isset($_POST['ad_format'])) {
        $format = sanitize_key($_POST['ad_format']);
        $formats = imz_get_ad_formats();
        if (isset($formats[$format])) {
            update_post_meta($post_id, '_imz_ad_format', $format);
            update_post_meta($post_id, '_imz_ad_format_width', $formats[$format]['width']);
            update_post_meta($post_id, '_imz_ad_format_height', $formats[$format]['height']);
        }
    }
    if (isset($_POST['ad_label'])) {
        update_post_meta($post_id, '_imz_ad_label', sanitize_text_field($_POST['ad_label']));
    }
}


// =============================================================================
// 4. CSS DE FORMATOS PARA O FRONTEND
// =============================================================================

/**
 * Retorna CSS inline para os formatos de anúncio no frontend.
 * Adicionar ao enqueue de estilos ou injectar via wp_head.
 */
add_action('wp_head', 'imz_ad_formats_frontend_css');
function imz_ad_formats_frontend_css() {
    ?>
    <style>
    /* =====================================================================
       FORMATOS DE ANÚNCIO — totalmente fluidos.
       Nenhuma altura fixa em px: cada imagem escala com width:100% e
       mantém a proporção via aspect-ratio, em qualquer tamanho de ecrã.
       ===================================================================== */

    .imz-ad-item {
        max-width: 100%;
        box-sizing: border-box;
    }
    .imz-ad-item .imz-ad-image {
        display: block;
        width: 100%;
        height: auto;
        max-width: 100%;
        object-fit: cover;
    }

    /* Formato: Leaderboard (728x90) */
    .imz-ad-item[data-format="leaderboard"] {
        max-width: 728px;
        margin-left: auto;
        margin-right: auto;
    }
    .imz-ad-item[data-format="leaderboard"] .imz-ad-image {
        aspect-ratio: 728 / 90;
    }

    /* Formato: Retângulo (300x250) */
    .imz-ad-item[data-format="rectangle"] {
        max-width: 300px;
    }
    .imz-ad-item[data-format="rectangle"] .imz-ad-image {
        aspect-ratio: 300 / 250;
    }

    /* Formato: Card Nativo (350x280) */
    .imz-ad-item[data-format="native_card"] {
        max-width: 350px;
    }
    .imz-ad-item[data-format="native_card"] .imz-ad-image {
        aspect-ratio: 350 / 200;
    }
    .imz-ad-item[data-format="native_card"] .imz-ad-badge {
        background: rgba(16, 185, 129, 0.8);
        color: #fff;
    }

    /* Formato: Banner Mobile (320x100) */
    .imz-ad-item[data-format="mobile_banner"] {
        max-width: 320px;
        margin-left: auto;
        margin-right: auto;
    }
    .imz-ad-item[data-format="mobile_banner"] .imz-ad-image {
        aspect-ratio: 320 / 100;
    }

    /* Formato: Stories (360x640) */
    .imz-ad-item[data-format="stories"] {
        max-width: 360px;
        margin-left: auto;
        margin-right: auto;
    }
    .imz-ad-item[data-format="stories"] .imz-ad-image {
        aspect-ratio: 360 / 640;
        max-height: 70vh;
    }

    /* Adaptação inteligente em ecrãs pequenos */
    @media (max-width: 600px) {
        /* Leaderboard 728x90 ficaria ilegível (~44px de altura num telemóvel):
           adapta-se à proporção de banner mobile, recortando pelo centro */
        .imz-ad-item[data-format="leaderboard"] .imz-ad-image {
            aspect-ratio: 320 / 100;
        }
        /* Em mobile, todos os formatos ocupam a largura disponível */
        .imz-ad-item[data-format="rectangle"],
        .imz-ad-item[data-format="native_card"] {
            max-width: 100%;
            margin-left: auto;
            margin-right: auto;
        }
        .imz-ad-item[data-format="stories"] .imz-ad-image {
            max-height: 65vh;
        }
    }

    /* Fallback para browsers antigos sem aspect-ratio: altura natural da imagem */
    @supports not (aspect-ratio: 1 / 1) {
        .imz-ad-item .imz-ad-image {
            height: auto;
        }
    }
    </style>
    <?php
}


// =============================================================================
// 4b. SELETOR VISUAL DE TARGETING GEOGRÁFICO (compacto e inteligente)
// =============================================================================

/**
 * Renderiza o seletor de targeting por clique (chips de países e regiões).
 *
 * Comportamento inteligente:
 * - Países: por defeito só mostra os relevantes (selecionados + vistos na
 *   audiência); pesquisa instantânea e botão "Mostrar todos" para o resto.
 * - Regiões: mostra as regiões dos países selecionados — províncias de
 *   Moçambique quando MZ está no alvo (ou sem seleção de país), e regiões
 *   observadas na audiência real para os outros países. Selecionar só ZA
 *   esconde (e desmarca) as províncias moçambicanas.
 *
 * Mantém os mesmos campos POST (ad_target_countries / ad_target_regions, CSV).
 */
function imz_render_geo_targeting_fields(string $countries_csv = '', string $regions_csv = ''): void {
    $selected_countries = array_filter(array_map(function ($c) { return strtoupper(trim($c)); }, explode(',', $countries_csv)));
    $selected_regions   = array_filter(array_map('trim', explode(',', $regions_csv)));
    $selected_regions_lc = array_map(function ($r) { return mb_strtolower(remove_accents($r)); }, $selected_regions);

    $country_groups = function_exists('imz_get_target_countries_list') ? imz_get_target_countries_list() : [];
    $provinces      = function_exists('imz_get_mz_provinces_list') ? imz_get_mz_provinces_list() : [];
    $observed       = function_exists('imz_ads_get_observed_geo') ? imz_ads_get_observed_geo() : ['countries' => [], 'regions' => [], 'regions_by_country' => []];

    $known_codes = [];
    foreach ($country_groups as $group) { $known_codes = array_merge($known_codes, array_keys($group)); }

    // Países observados na audiência que não estão na lista curada
    $extra_observed = array_diff(array_keys($observed['countries']), $known_codes);

    // Códigos selecionados sem chip (vão para o campo "outros")
    $orphan_codes = array_diff($selected_countries, $known_codes, $extra_observed);

    // Chips de regiões disponíveis: províncias MZ + regiões observadas por país
    $region_chips = []; // cada item: ['label','value','country','count']
    foreach ($provinces as $label => $value) {
        $count = 0;
        foreach (($observed['regions_by_country']['MZ'] ?? []) as $obs_region => $obs_count) {
            if (mb_stripos(remove_accents($obs_region), remove_accents($value)) !== false || mb_stripos(remove_accents($value), remove_accents($obs_region)) !== false) {
                $count += $obs_count;
            }
        }
        $region_chips[] = ['label' => $label, 'value' => $value, 'country' => 'MZ', 'count' => $count];
    }
    foreach (($observed['regions_by_country'] ?? []) as $cc => $regions) {
        if ($cc === 'MZ') continue;
        foreach ($regions as $region_name => $count) {
            $region_chips[] = ['label' => $region_name, 'value' => $region_name, 'country' => $cc, 'count' => $count];
        }
    }

    // Regiões selecionadas sem chip correspondente (campo "outras")
    $chip_values_lc = array_map(function ($c) { return mb_strtolower(remove_accents($c['value'])); }, $region_chips);
    $orphan_regions = [];
    foreach ($selected_regions as $i => $r) {
        if (!in_array($selected_regions_lc[$i], $chip_values_lc, true)) $orphan_regions[] = $r;
    }

    static $assets_printed = false;
    if (!$assets_printed) {
        $assets_printed = true;
        ?>
        <style>
        .imz-geo-targeting { margin-bottom: 14px; }
        .imz-geo-picker { margin-bottom: 16px; }
        .imz-geo-picker-label { display: block; font-weight: 600; margin-bottom: 6px; }
        .imz-geo-hint { font-size: 12px; color: #6b7280; margin: 2px 0 8px; }
        .imz-geo-search input { width: 100%; max-width: 320px; padding: 7px 12px; border: 1px solid #d1d5db; border-radius: 50px; font-size: 13px; box-sizing: border-box; margin-bottom: 8px; }
        .imz-geo-group-title { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.4px; color: #6b7280; margin: 10px 0 6px; }
        .imz-geo-chips { display: flex; flex-wrap: wrap; gap: 6px; }
        .imz-geo-chip { display: inline-flex; align-items: center; gap: 5px; padding: 5px 12px; border: 1px solid #d1d5db; border-radius: 50px; font-size: 12.5px; cursor: pointer; background: #fff; color: #374151; transition: all 0.15s; user-select: none; line-height: 1.3; }
        .imz-geo-chip:hover { border-color: #2563eb; }
        .imz-geo-chip input { display: none; }
        .imz-geo-chip.on { background: #2563eb; border-color: #2563eb; color: #fff; font-weight: 600; }
        .imz-geo-chip .geo-count { font-size: 10px; opacity: 0.65; }
        .imz-geo-chip .geo-cc { font-size: 10px; opacity: 0.55; font-family: monospace; }
        .imz-geo-toggle-all { background: none; border: none; color: #2563eb; font-size: 12.5px; cursor: pointer; padding: 6px 0; display: block; }
        .imz-geo-toggle-all:hover { text-decoration: underline; }
        .imz-geo-extra { margin-top: 8px; }
        .imz-geo-extra input { width: 100%; max-width: 420px; padding: 6px 10px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 12.5px; box-sizing: border-box; }
        .imz-geo-summary { margin-top: 8px; font-size: 12px; color: #065f46; background: #ecfdf5; border: 1px solid #a7f3d0; border-radius: 6px; padding: 6px 10px; display: inline-block; }
        .imz-geo-summary.all { color: #6b7280; background: #f9fafb; border-color: #e5e7eb; }
        .imz-geo-none { font-size: 12px; color: #92400e; background: #fef3c7; border: 1px solid #fde68a; border-radius: 6px; padding: 6px 10px; display: none; margin-bottom: 8px; }
        </style>
        <script>
        function imzGeoNorm(s) {
            return (s || '').toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '');
        }
        function imzGeoSync(picker) {
            var values = [];
            picker.querySelectorAll('.imz-geo-chip input:checked').forEach(function (cb) { values.push(cb.value); });
            var extra = picker.querySelector('.imz-geo-extra input');
            if (extra && extra.value.trim() !== '') {
                extra.value.split(',').forEach(function (v) {
                    v = v.trim();
                    if (v !== '' && values.indexOf(v) === -1) values.push(v);
                });
            }
            picker.querySelector('.imz-geo-value').value = values.join(', ');
            var summary = picker.querySelector('.imz-geo-summary');
            if (summary) {
                if (values.length === 0) {
                    summary.textContent = summary.getAttribute('data-all-text');
                    summary.classList.add('all');
                } else {
                    summary.textContent = '🎯 ' + values.length + ' selecionado(s): ' + values.join(', ');
                    summary.classList.remove('all');
                }
            }
        }
        function imzGeoCountryVisibility(wrapper) {
            var picker = wrapper.querySelector('.imz-geo-countries');
            if (!picker) return;
            var searchEl = picker.querySelector('.imz-geo-search input');
            var q = imzGeoNorm(searchEl ? searchEl.value.trim() : '');
            var expanded = picker.getAttribute('data-expanded') === '1';
            picker.querySelectorAll('.imz-geo-chip').forEach(function (chip) {
                var show;
                if (q !== '') {
                    show = imzGeoNorm(chip.getAttribute('data-name')).indexOf(q) !== -1;
                } else if (expanded) {
                    show = true;
                } else {
                    show = chip.getAttribute('data-keep') === '1' || chip.querySelector('input').checked;
                }
                chip.style.display = show ? '' : 'none';
            });
            picker.querySelectorAll('.imz-geo-group').forEach(function (group) {
                var any = false;
                group.querySelectorAll('.imz-geo-chip').forEach(function (c) { if (c.style.display !== 'none') any = true; });
                group.style.display = any ? '' : 'none';
            });
            var btn = picker.querySelector('.imz-geo-toggle-all');
            if (btn) btn.style.display = (q !== '') ? 'none' : '';
        }
        function imzGeoUpdateRegions(wrapper) {
            var countryPicker = wrapper.querySelector('.imz-geo-countries');
            var regionPicker = wrapper.querySelector('.imz-geo-regions');
            if (!countryPicker || !regionPicker) return;
            var selected = [];
            countryPicker.querySelectorAll('.imz-geo-chip input:checked').forEach(function (cb) { selected.push(cb.value.toUpperCase()); });
            var visible = 0;
            var changed = false;
            regionPicker.querySelectorAll('.imz-geo-chip').forEach(function (chip) {
                var cc = (chip.getAttribute('data-country') || '').toUpperCase();
                // Sem países selecionados → mostra as províncias de Moçambique (mercado base);
                // com seleção → só regiões dos países escolhidos
                var show = selected.length === 0 ? (cc === 'MZ') : (selected.indexOf(cc) !== -1);
                chip.style.display = show ? '' : 'none';
                if (show) visible++;
                var cb = chip.querySelector('input');
                if (!show && cb.checked) {
                    cb.checked = false;
                    chip.classList.remove('on');
                    changed = true;
                }
            });
            var none = regionPicker.querySelector('.imz-geo-none');
            if (none) none.style.display = (visible === 0) ? 'block' : 'none';
            if (changed) imzGeoSync(regionPicker);
        }
        document.addEventListener('change', function (e) {
            var picker = e.target.closest('.imz-geo-picker');
            if (!picker || !e.target.matches('.imz-geo-chip input')) return;
            var chip = e.target.closest('.imz-geo-chip');
            if (chip) chip.classList.toggle('on', e.target.checked);
            imzGeoSync(picker);
            var wrapper = picker.closest('.imz-geo-targeting');
            if (wrapper && picker.classList.contains('imz-geo-countries')) imzGeoUpdateRegions(wrapper);
        });
        document.addEventListener('input', function (e) {
            var picker = e.target.closest('.imz-geo-picker');
            if (!picker) return;
            if (e.target.closest('.imz-geo-extra')) imzGeoSync(picker);
            if (e.target.closest('.imz-geo-search')) imzGeoCountryVisibility(picker.closest('.imz-geo-targeting'));
        });
        document.addEventListener('click', function (e) {
            var btn = e.target.closest('.imz-geo-toggle-all');
            if (!btn) return;
            e.preventDefault();
            var picker = btn.closest('.imz-geo-countries');
            var expanded = picker.getAttribute('data-expanded') === '1';
            picker.setAttribute('data-expanded', expanded ? '0' : '1');
            btn.textContent = expanded ? '▾ Mostrar todos os países' : '▴ Mostrar menos';
            imzGeoCountryVisibility(picker.closest('.imz-geo-targeting'));
        });
        document.addEventListener('DOMContentLoaded', function () {
            document.querySelectorAll('.imz-geo-targeting').forEach(function (wrapper) {
                imzGeoCountryVisibility(wrapper);
                imzGeoUpdateRegions(wrapper);
            });
        });
        </script>
        <?php
    }
    ?>
    <div class="imz-geo-targeting">

        <?php // ----- PAÍSES ----- ?>
        <div class="imz-geo-picker imz-geo-countries" data-expanded="0">
            <span class="imz-geo-picker-label">🌍 Limitar por Países</span>
            <p class="imz-geo-hint">Clique para selecionar. Sem seleção = o anúncio aparece em todos os países.</p>
            <div class="imz-geo-search"><input type="text" placeholder="🔍 Pesquisar país…" autocomplete="off"></div>
            <?php foreach ($country_groups as $group_name => $group) : ?>
                <div class="imz-geo-group">
                    <p class="imz-geo-group-title"><?php echo esc_html($group_name); ?></p>
                    <div class="imz-geo-chips">
                        <?php foreach ($group as $code => $name) :
                            $is_on = in_array($code, $selected_countries, true);
                            $count = $observed['countries'][$code] ?? 0;
                            $keep  = ($is_on || $count > 0) ? '1' : '0';
                        ?>
                        <label class="imz-geo-chip<?php echo $is_on ? ' on' : ''; ?>" data-name="<?php echo esc_attr($name . ' ' . $code); ?>" data-keep="<?php echo $keep; ?>">
                            <input type="checkbox" value="<?php echo esc_attr($code); ?>" <?php checked($is_on); ?>>
                            <?php echo imz_country_flag($code); ?> <?php echo esc_html($name); ?>
                            <?php if ($count > 0) : ?><span class="geo-count">(<?php echo number_format($count); ?>)</span><?php endif; ?>
                        </label>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
            <?php if (!empty($extra_observed)) : ?>
                <div class="imz-geo-group">
                    <p class="imz-geo-group-title">Vistos na sua audiência</p>
                    <div class="imz-geo-chips">
                        <?php foreach ($extra_observed as $code) :
                            $is_on = in_array($code, $selected_countries, true);
                        ?>
                        <label class="imz-geo-chip<?php echo $is_on ? ' on' : ''; ?>" data-name="<?php echo esc_attr($code); ?>" data-keep="1">
                            <input type="checkbox" value="<?php echo esc_attr($code); ?>" <?php checked($is_on); ?>>
                            <?php echo imz_country_flag($code); ?> <?php echo esc_html($code); ?>
                            <span class="geo-count">(<?php echo number_format($observed['countries'][$code]); ?>)</span>
                        </label>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>
            <button type="button" class="imz-geo-toggle-all">▾ Mostrar todos os países</button>
            <div class="imz-geo-extra">
                <input type="text" value="<?php echo esc_attr(implode(', ', $orphan_codes)); ?>" placeholder="Outros códigos ISO (ex: FI, PL)">
            </div>
            <input type="hidden" name="ad_target_countries" class="imz-geo-value" value="<?php echo esc_attr(implode(', ', $selected_countries)); ?>">
            <span class="imz-geo-summary<?php echo empty($selected_countries) ? ' all' : ''; ?>" data-all-text="🌐 Todos os países">
                <?php echo empty($selected_countries) ? '🌐 Todos os países' : '🎯 ' . count($selected_countries) . ' selecionado(s): ' . esc_html(implode(', ', $selected_countries)); ?>
            </span>
        </div>

        <?php // ----- REGIÕES (dinâmicas conforme os países selecionados) ----- ?>
        <div class="imz-geo-picker imz-geo-regions">
            <span class="imz-geo-picker-label">📍 Limitar por Regiões</span>
            <p class="imz-geo-hint">Mostra as regiões dos países selecionados (províncias de Moçambique e regiões vistas na sua audiência). Sem seleção = todas.</p>
            <p class="imz-geo-none">Sem regiões conhecidas para os países selecionados — use o campo de texto abaixo se precisar.</p>
            <div class="imz-geo-chips">
                <?php foreach ($region_chips as $chip) :
                    $is_on = in_array(mb_strtolower(remove_accents($chip['value'])), $selected_regions_lc, true);
                ?>
                <label class="imz-geo-chip<?php echo $is_on ? ' on' : ''; ?>" data-country="<?php echo esc_attr($chip['country']); ?>">
                    <input type="checkbox" value="<?php echo esc_attr($chip['value']); ?>" <?php checked($is_on); ?>>
                    <?php echo esc_html($chip['label']); ?>
                    <?php if ($chip['country'] !== 'MZ') : ?><span class="geo-cc"><?php echo esc_html($chip['country']); ?></span><?php endif; ?>
                    <?php if ($chip['count'] > 0) : ?><span class="geo-count">(<?php echo number_format($chip['count']); ?>)</span><?php endif; ?>
                </label>
                <?php endforeach; ?>
            </div>
            <div class="imz-geo-extra">
                <input type="text" value="<?php echo esc_attr(implode(', ', $orphan_regions)); ?>" placeholder="Outras regiões (ex: Gauteng, Lisboa)">
            </div>
            <input type="hidden" name="ad_target_regions" class="imz-geo-value" value="<?php echo esc_attr(implode(', ', $selected_regions)); ?>">
            <span class="imz-geo-summary<?php echo empty($selected_regions) ? ' all' : ''; ?>" data-all-text="🌐 Todas as regiões">
                <?php echo empty($selected_regions) ? '🌐 Todas as regiões' : '🎯 ' . count($selected_regions) . ' selecionada(s): ' . esc_html(implode(', ', $selected_regions)); ?>
            </span>
        </div>

    </div>
    <?php
}

// =============================================================================
// 5. MODIFICAR O RENDER DO SHORTCODE PARA USAR FORMATO
// =============================================================================

/**
 * Filtro para adicionar data-format ao HTML do anúncio.
 * Usar com: add_filter('imz_ad_item_attributes', 'imz_add_format_attribute', 10, 2);
 */
add_filter('imz_ad_item_attributes', 'imz_add_format_attribute', 10, 2);
function imz_add_format_attribute($attrs_string, $ad_id) {
    $format = get_post_meta($ad_id, '_imz_ad_format', true);
    if ($format) {
        $attrs_string .= ' data-format="' . esc_attr($format) . '"';
    }
    return $attrs_string;
}


// =============================================================================
// 6. FORMULÁRIO DE EDIÇÃO COM PREVIEW (ADMIN)
// =============================================================================

function imz_render_ad_edit_form_with_preview($ad_id) {
    $formats = imz_get_ad_formats();
    $post = get_post($ad_id);
    if (!$post) return;

    // Carregar dados existentes
    $ad_title      = $post->post_title;
    $ad_type       = get_post_meta($ad_id, '_imz_ad_type', true) ?: 'banner';
    $ad_text       = get_post_meta($ad_id, '_imz_ad_text', true);
    $ad_link       = get_post_meta($ad_id, '_imz_ad_link', true);
    $ad_image      = get_post_meta($ad_id, '_imz_ad_image_url', true);
    $ad_duration   = get_post_meta($ad_id, '_imz_ad_duration', true) ?: 7;
    $ad_countries  = get_post_meta($ad_id, '_imz_ad_target_countries', true);
    $ad_regions    = get_post_meta($ad_id, '_imz_ad_target_regions', true);
    $ad_format     = get_post_meta($ad_id, '_imz_ad_format', true) ?: 'leaderboard';
    $ad_label      = get_post_meta($ad_id, '_imz_ad_label', true) ?: 'Anúncio';
    $ad_status     = get_post_meta($ad_id, '_imz_ad_status', true) ?: 'pendente';
    $ad_start      = get_post_meta($ad_id, '_imz_ad_start_date', true);
    $ad_end        = get_post_meta($ad_id, '_imz_ad_end_date', true);

    // Mesmos estilos do formulário de criação (reutiliza)
    imz_render_ad_form_styles();
    ?>
    <div class="imz-ad-create-wrap">
        <!-- FORMULÁRIO DE EDIÇÃO -->
        <div class="imz-ads-box">
            <h3>✏️ Editar Anúncio #<?php echo $ad_id; ?></h3>
            <div style="background:#f0f7ff; border:1px solid #bdd7f1; border-radius:8px; padding:10px 14px; margin-bottom:18px; font-size:13px;">
                Criado em: <strong><?php echo $ad_start ? date('d/m/Y', strtotime($ad_start)) : '—'; ?></strong>
                | Expira: <strong><?php echo $ad_end ? date('d/m/Y', strtotime($ad_end)) : '∞'; ?></strong>
                | Status: <span class="imz-badge imz-badge-<?php echo $ad_status; ?>" style="vertical-align:middle;"><?php echo ucfirst(str_replace('_', ' ', $ad_status)); ?></span>
            </div>

            <?php
            // ----- DESEMPENHO DO ANÚNCIO (dados reais da tabela de stats) -----
            if (function_exists('imz_ads_get_totals')) :
                $edit_totals = imz_ads_get_totals($ad_id);
                $edit_ctr    = $edit_totals['impressions'] > 0 ? round(($edit_totals['clicks'] / $edit_totals['impressions']) * 100, 2) . '%' : '—';
                $edit_price  = (float) get_post_meta($ad_id, '_imz_ad_price', true);
                $edit_cpm    = ($edit_totals['impressions'] > 0 && $edit_price > 0) ? number_format($edit_price / ($edit_totals['impressions'] / 1000), 2) . ' MT' : '—';
                $edit_cpc    = ($edit_totals['clicks'] > 0 && $edit_price > 0) ? number_format($edit_price / $edit_totals['clicks'], 2) . ' MT' : '—';
                $edit_devices = function_exists('imz_ads_get_device_bulk') ? (imz_ads_get_device_bulk([$ad_id])[$ad_id] ?? []) : [];
                $edit_dev_total = array_sum($edit_devices);
                $edit_paid_at  = get_post_meta($ad_id, '_imz_ad_paid_at', true);
                $edit_pay_method = get_post_meta($ad_id, '_imz_ad_payment_method', true);
                $report_url = admin_url('edit.php?post_type=impulsionamento&page=imz_ads_manager&view=reports&report_ad=' . $ad_id);
            ?>
            <div style="background:#fff; border:1px solid #e5e7eb; border-radius:8px; padding:14px 16px; margin-bottom:18px;">
                <p style="margin:0 0 10px; font-size:13px; font-weight:700; color:#374151;">📊 Desempenho desta campanha
                    <a href="<?php echo esc_url($report_url); ?>" style="font-weight:400; font-size:12px; margin-left:8px;">ver relatório completo →</a>
                </p>
                <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(110px, 1fr)); gap:8px;">
                    <div style="text-align:center; background:#f9fafb; border-radius:6px; padding:10px;"><div style="font-size:19px; font-weight:800; color:#111;"><?php echo number_format($edit_totals['impressions']); ?></div><div style="font-size:10px; color:#6b7280; text-transform:uppercase;">Impressões</div></div>
                    <div style="text-align:center; background:#f9fafb; border-radius:6px; padding:10px;"><div style="font-size:19px; font-weight:800; color:#111;"><?php echo number_format($edit_totals['clicks']); ?></div><div style="font-size:10px; color:#6b7280; text-transform:uppercase;">Cliques</div></div>
                    <div style="text-align:center; background:#f9fafb; border-radius:6px; padding:10px;"><div style="font-size:19px; font-weight:800; color:#111;"><?php echo esc_html($edit_ctr); ?></div><div style="font-size:10px; color:#6b7280; text-transform:uppercase;">CTR</div></div>
                    <div style="text-align:center; background:#f9fafb; border-radius:6px; padding:10px;"><div style="font-size:19px; font-weight:800; color:#111;"><?php echo esc_html($edit_cpm); ?></div><div style="font-size:10px; color:#6b7280; text-transform:uppercase;">CPM</div></div>
                    <div style="text-align:center; background:#f9fafb; border-radius:6px; padding:10px;"><div style="font-size:19px; font-weight:800; color:#111;"><?php echo esc_html($edit_cpc); ?></div><div style="font-size:10px; color:#6b7280; text-transform:uppercase;">CPC</div></div>
                </div>
                <?php if ($edit_dev_total > 0) : ?>
                <p style="margin:10px 0 0; font-size:12px; color:#6b7280;">
                    📱 Mobile <?php echo round(($edit_devices['mobile'] ?? 0) / $edit_dev_total * 100); ?>% ·
                    💻 Desktop <?php echo round(($edit_devices['desktop'] ?? 0) / $edit_dev_total * 100); ?>% ·
                    📟 Tablet <?php echo round(($edit_devices['tablet'] ?? 0) / $edit_dev_total * 100); ?>%
                </p>
                <?php endif; ?>
                <?php if ($edit_paid_at) : ?>
                <p style="margin:6px 0 0; font-size:12px; color:#065f46;">💳 Pago em <?php echo esc_html(date('d/m/Y H:i', strtotime($edit_paid_at))); ?> (<?php echo esc_html($edit_pay_method ?: 'M-Pesa'); ?>) — <?php echo number_format($edit_price); ?> MT</p>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <form method="post" class="imz-ad-create-form" id="imz-ad-create-form">
                <?php wp_nonce_field('imz_admin_edit_ad_action', '_imz_admin_edit_nonce'); ?>
                <input type="hidden" name="edit_ad_id" value="<?php echo $ad_id; ?>">

                <!-- 1. Formato -->
                <div class="imz-ad-form-section">
                    <h4>1. Formato</h4>
                    <div class="imz-fmt-grid">
                        <?php foreach ($formats as $key => $fmt): ?>
                        <div class="imz-fmt-card<?php echo $key === $ad_format ? ' selected' : ''; ?>" data-format="<?php echo esc_attr($key); ?>" data-width="<?php echo $fmt['width']; ?>" data-height="<?php echo $fmt['height']; ?>">
                            <span class="imz-fmt-icon"><?php echo $fmt['icon']; ?></span>
                            <p class="imz-fmt-name"><?php echo esc_html($fmt['name']); ?></p>
                            <p class="imz-fmt-dims"><?php echo esc_html($fmt['label']); ?></p>
                            <p class="imz-fmt-desc"><?php echo esc_html($fmt['description']); ?></p>
                            <div class="imz-fmt-thumb" style="aspect-ratio: <?php echo $fmt['width']; ?>/<?php echo $fmt['height']; ?>; max-height: 60px;"></div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <input type="hidden" name="ad_format" id="imz-ad-format" value="<?php echo esc_attr($ad_format); ?>">
                    <input type="hidden" name="ad_type" value="<?php echo esc_attr($ad_type); ?>">
                </div>

                <!-- 2. Conteúdo -->
                <div class="imz-ad-form-section">
                    <h4>2. Conteúdo</h4>
                    <label>Título *</label>
                    <input type="text" name="ad_title" id="imz-ad-title" required value="<?php echo esc_attr($ad_title); ?>" oninput="imzUpdatePreview()">

                    <label>Texto / Descrição</label>
                    <textarea name="ad_text" id="imz-ad-text" oninput="imzUpdatePreview()"><?php echo esc_textarea($ad_text); ?></textarea>

                    <label>URL da Imagem</label>
                    <input type="url" name="ad_image_url" id="imz-ad-image" value="<?php echo esc_attr($ad_image); ?>" oninput="imzUpdatePreview()">
                    <p class="field-hint">Dimensões recomendadas visíveis no formato selecionado.</p>

                    <label>Link de Destino</label>
                    <input type="url" name="ad_link" id="imz-ad-link" value="<?php echo esc_attr($ad_link); ?>">
                </div>

                <!-- 3. Configuração -->
                <div class="imz-ad-form-section">
                    <h4>3. Configuração</h4>

                    <label>Status</label>
                    <select name="ad_status" style="margin-bottom:14px;">
                        <option value="ativo" <?php selected($ad_status, 'ativo'); ?>>Ativo</option>
                        <option value="pausado" <?php selected($ad_status, 'pausado'); ?>>Pausado</option>
                        <option value="pendente" <?php selected($ad_status, 'pendente'); ?>>Pendente</option>
                        <option value="rejeitado" <?php selected($ad_status, 'rejeitado'); ?>>Rejeitado</option>
                    </select>

                    <label>Duração (dias desde a criação)</label>
                    <input type="number" name="ad_duration" value="<?php echo esc_attr($ad_duration); ?>" min="1" max="365" style="width:100px;">

                    <?php imz_render_geo_targeting_fields((string) $ad_countries, (string) $ad_regions); ?>

                    <label>Label do Badge</label>
                    <input type="text" name="ad_label" value="<?php echo esc_attr($ad_label); ?>" id="imz-ad-label" oninput="imzUpdatePreview()">
                </div>

                <div style="display:flex; gap:10px;">
                    <button type="submit" name="imz_admin_update_ad" class="button button-primary button-hero" style="flex:1;">
                        Guardar Alterações
                    </button>
                    <a href="<?php echo admin_url('edit.php?post_type=impulsionamento&page=imz_ads_manager&view=list'); ?>" class="button button-hero" style="flex:0 0 auto;">
                        Cancelar
                    </a>
                </div>
            </form>
        </div>

        <!-- PREVIEW (mesma estrutura do create) -->
        <div class="imz-ad-preview-panel">
            <div class="imz-ad-preview-header">
                <h4>Preview em Tempo Real</h4>
                <span id="imz-preview-dims"><?php echo isset($formats[$ad_format]) ? $formats[$ad_format]['width'] . ' × ' . $formats[$ad_format]['height'] : '728 × 90'; ?></span>
            </div>
            <div class="imz-ad-preview-body" id="imz-preview-body">
                <div class="imz-ad-preview-frame" id="imz-preview-frame">
                    <span class="imz-ad-preview-badge" id="imz-preview-badge"><?php echo esc_html($ad_label); ?></span>
                    <div class="imz-ad-preview-placeholder" id="imz-preview-placeholder" style="<?php echo $ad_image ? 'display:none;' : ''; ?>">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/></svg>
                        <span>Cole a URL da imagem</span>
                    </div>
                    <img id="imz-preview-img" src="<?php echo esc_url($ad_image); ?>" alt="" style="<?php echo $ad_image ? '' : 'display:none;'; ?>">
                    <div class="imz-ad-preview-text-overlay" id="imz-preview-overlay" style="<?php echo ($ad_title || $ad_text) ? '' : 'display:none;'; ?>">
                        <p class="ad-title" id="imz-preview-title"><?php echo esc_html($ad_title); ?></p>
                        <p class="ad-desc" id="imz-preview-desc"><?php echo esc_html($ad_text); ?></p>
                    </div>
                </div>
            </div>
            <div class="imz-ad-preview-info" id="imz-preview-info">
                <?php if (isset($formats[$ad_format])): ?>
                <strong><?php echo $formats[$ad_format]['name']; ?></strong> — <?php echo $formats[$ad_format]['label']; ?><br>
                <?php echo $formats[$ad_format]['description']; ?><br>
                Posicionamento: <?php echo $formats[$ad_format]['placement']; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
    (function() {
        var formats = <?php echo json_encode($formats); ?>;
        var currentFormat = '<?php echo esc_js($ad_format); ?>';
        var previewMaxWidth = 370;

        document.querySelectorAll('.imz-fmt-card').forEach(function(card) {
            card.addEventListener('click', function() {
                document.querySelectorAll('.imz-fmt-card').forEach(function(c) { c.classList.remove('selected'); });
                this.classList.add('selected');
                currentFormat = this.getAttribute('data-format');
                document.getElementById('imz-ad-format').value = currentFormat;
                var typeMap = { 'leaderboard':'banner', 'rectangle':'destaque', 'native_card':'destaque', 'mobile_banner':'banner', 'stories':'sidebar' };
                var typeInput = document.querySelector('input[name="ad_type"]');
                if (typeInput) typeInput.value = typeMap[currentFormat] || 'banner';
                imzUpdatePreview();
            });
        });

        window.imzUpdatePreview = function() {
            var fmt = formats[currentFormat];
            if (!fmt) return;
            var frame = document.getElementById('imz-preview-frame');
            var dims = document.getElementById('imz-preview-dims');
            var info = document.getElementById('imz-preview-info');
            var img = document.getElementById('imz-preview-img');
            var placeholder = document.getElementById('imz-preview-placeholder');
            var overlay = document.getElementById('imz-preview-overlay');
            var badge = document.getElementById('imz-preview-badge');
            var titleEl = document.getElementById('imz-preview-title');
            var descEl = document.getElementById('imz-preview-desc');

            var scale = Math.min(previewMaxWidth / fmt.width, 1);
            frame.style.width = Math.round(fmt.width * scale) + 'px';
            frame.style.height = Math.round(fmt.height * scale) + 'px';
            dims.textContent = fmt.width + ' × ' + fmt.height;
            info.innerHTML = '<strong>' + fmt.name + '</strong> — ' + fmt.label + '<br>' + fmt.description + '<br>Posicionamento: ' + fmt.placement;

            var imgUrl = document.getElementById('imz-ad-image').value.trim();
            if (imgUrl) {
                img.src = imgUrl;
                img.style.display = 'block';
                placeholder.style.display = 'none';
                img.onerror = function() { img.style.display = 'none'; placeholder.style.display = 'flex'; };
            } else {
                img.style.display = 'none';
                placeholder.style.display = 'flex';
            }

            var title = document.getElementById('imz-ad-title').value.trim();
            var desc = document.getElementById('imz-ad-text').value.trim();
            overlay.style.display = (title || desc) ? 'block' : 'none';
            titleEl.textContent = title;
            descEl.textContent = desc;

            var labelVal = document.getElementById('imz-ad-label').value.trim();
            badge.textContent = labelVal || 'Anúncio';
        };

        imzUpdatePreview();
    })();
    </script>
    <?php
}

/**
 * Renderiza os estilos partilhados pelos formulários de criação e edição.
 */
function imz_render_ad_form_styles() {
    static $rendered = false;
    if ($rendered) return;
    $rendered = true;
    // Os estilos já são injectados pelo imz_render_ad_create_form_with_preview
    // Esta função existe para o caso da edição ser carregada sem o create
    ?>
    <style>
    .imz-ad-create-wrap { display: grid; grid-template-columns: 1fr 400px; gap: 24px; align-items: start; }
    @media (max-width: 1100px) { .imz-ad-create-wrap { grid-template-columns: 1fr; } .imz-ad-preview-panel { order: -1; } }
    .imz-fmt-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 10px; margin-bottom: 20px; }
    .imz-fmt-card { border: 2px solid #e5e7eb; border-radius: 10px; padding: 14px; cursor: pointer; transition: all 0.2s; background: #fff; text-align: center; position: relative; }
    .imz-fmt-card:hover { border-color: #93c5fd; background: #f0f7ff; }
    .imz-fmt-card.selected { border-color: #2563eb; background: #eff6ff; box-shadow: 0 0 0 2px rgba(37,99,235,0.2); }
    .imz-fmt-card.selected::after { content: '✓'; position: absolute; top: 8px; right: 8px; width: 20px; height: 20px; background: #2563eb; color: #fff; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 11px; font-weight: 700; }
    .imz-fmt-icon { font-size: 24px; display: block; margin-bottom: 6px; }
    .imz-fmt-name { font-size: 13px; font-weight: 700; color: #111; margin: 0 0 2px; }
    .imz-fmt-dims { font-size: 11px; color: #6b7280; margin: 0 0 4px; font-family: monospace; }
    .imz-fmt-desc { font-size: 11px; color: #9ca3af; margin: 0; line-height: 1.3; }
    .imz-fmt-thumb { width: 100%; max-width: 120px; margin: 8px auto 0; display: block; border: 1px solid #e5e7eb; border-radius: 4px; background: #f9fafb; }
    .imz-ad-preview-panel { background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; overflow: hidden; position: sticky; top: 40px; }
    .imz-ad-preview-header { background: #f9fafb; padding: 14px 18px; border-bottom: 1px solid #e5e7eb; display: flex; align-items: center; justify-content: space-between; }
    .imz-ad-preview-header h4 { margin: 0; font-size: 14px; color: #374151; }
    .imz-ad-preview-header span { font-size: 11px; color: #9ca3af; font-family: monospace; }
    .imz-ad-preview-body { padding: 24px; display: flex; align-items: center; justify-content: center; min-height: 200px; background: #1a1a1a; }
    .imz-ad-preview-frame { border: 1px dashed #444; border-radius: 8px; overflow: hidden; position: relative; display: flex; flex-direction: column; background: #222; transition: width 0.3s, height 0.3s; }
    .imz-ad-preview-frame img { width: 100%; height: 100%; object-fit: cover; display: block; }
    .imz-ad-preview-placeholder { display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%; height: 100%; color: #555; font-size: 12px; gap: 6px; text-align: center; padding: 10px; box-sizing: border-box; }
    .imz-ad-preview-placeholder svg { width: 32px; height: 32px; stroke: #555; }
    .imz-ad-preview-badge { position: absolute; top: 6px; left: 6px; background: rgba(0,0,0,0.6); color: #9ca3af; font-size: 9px; font-weight: 600; padding: 2px 6px; border-radius: 3px; text-transform: uppercase; letter-spacing: 0.5px; backdrop-filter: blur(4px); z-index: 2; }
    .imz-ad-preview-text-overlay { position: absolute; bottom: 0; left: 0; right: 0; background: linear-gradient(transparent, rgba(0,0,0,0.8)); padding: 20px 12px 10px; }
    .imz-ad-preview-text-overlay .ad-title { color: #fff; font-size: 13px; font-weight: 700; margin: 0 0 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .imz-ad-preview-text-overlay .ad-desc { color: #aaa; font-size: 11px; margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .imz-ad-preview-info { padding: 12px 18px; background: #f9fafb; border-top: 1px solid #e5e7eb; font-size: 11px; color: #6b7280; line-height: 1.6; }
    .imz-ad-preview-info strong { color: #374151; }
    .imz-ad-create-form label { display: block; font-size: 13px; font-weight: 600; color: #374151; margin-bottom: 4px; }
    .imz-ad-create-form input[type=text], .imz-ad-create-form input[type=url], .imz-ad-create-form input[type=number], .imz-ad-create-form textarea, .imz-ad-create-form select { width: 100%; padding: 8px 10px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 13px; box-sizing: border-box; margin-bottom: 14px; }
    .imz-ad-create-form textarea { height: 60px; resize: vertical; }
    .imz-ad-create-form .field-hint { font-size: 11px; color: #9ca3af; margin: -10px 0 14px; }
    .imz-ad-form-section { margin-bottom: 20px; padding-bottom: 20px; border-bottom: 1px solid #f3f4f6; }
    .imz-ad-form-section h4 { font-size: 14px; font-weight: 700; color: #111; margin: 0 0 12px; }
    </style>
    <?php
}
