<?php
if (!defined('ABSPATH')) exit;

// =============================================================================
// 1. REGISTO DO CPT DE ANÚNCIOS
// =============================================================================

add_action('init', 'imz_register_ads_cpt');
function imz_register_ads_cpt() {
    register_post_type('imz_anuncio', [
        'labels' => [
            'name'               => 'Anúncios',
            'singular_name'      => 'Anúncio',
            'add_new'            => 'Adicionar Anúncio',
            'add_new_item'       => 'Adicionar Novo Anúncio',
            'edit_item'          => 'Editar Anúncio',
            'not_found'          => 'Nenhum anúncio encontrado.',
        ],
        'public'             => false,
        'show_ui'            => false, // Gerido via submenu próprio
        'supports'           => ['title'],
        'capability_type'    => 'post',
        'has_archive'        => false,
    ]);
}

// =============================================================================
// 2. TABELA DE CLIQUES/IMPRESSÕES (ANALYTICS DE ANÚNCIOS)
// =============================================================================

function imz_install_ads_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'imz_ad_stats';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        ad_id bigint(20) NOT NULL,
        event_type varchar(20) DEFAULT 'impression' NOT NULL,
        user_ip varchar(45) DEFAULT '' NOT NULL,
        user_agent varchar(255) DEFAULT '' NOT NULL,
        device_type varchar(20) DEFAULT '' NOT NULL,
        country varchar(10) DEFAULT '' NOT NULL,
        region varchar(100) DEFAULT '' NOT NULL,
        event_date datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        INDEX ad_id (ad_id),
        INDEX event_type (event_type),
        INDEX device_type (device_type)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
register_activation_hook(IMZ_DIR . 'impulsionamento-musicas.php', 'imz_install_ads_table');

// =============================================================================
// 3. MENU ADMIN PARA GERIR ANÚNCIOS
// =============================================================================

add_action('admin_menu', 'imz_register_ads_admin_page');
function imz_register_ads_admin_page() {
    add_submenu_page(
        imz_admin_parent_slug(),
        'Gestor de Anúncios & Campanhas',
        'Anúncios & Campanhas',
        'manage_options',
        'imz_ads_manager',
        'imz_render_ads_manager_page'
    );
}

function imz_render_ads_manager_page() {
    global $wpdb;
    $stats_table = $wpdb->prefix . 'imz_ad_stats';
    $has_stats = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $stats_table)) === $stats_table;
    $base_url = admin_url('edit.php?post_type=impulsionamento&page=imz_ads_manager');
    $view = isset($_GET['view']) ? sanitize_key($_GET['view']) : 'dashboard';
    $sp_summary = function_exists('rmbz_sponsored_admin_summary') ? rmbz_sponsored_admin_summary() : [];

    // --- PROCESSAR AÇÕES ---
    if (isset($_GET['action']) && isset($_GET['ad_id']) && wp_verify_nonce($_GET['_wpnonce'] ?? '', 'imz_ad_action')) {
        $ad_id = absint($_GET['ad_id']);
        $action = sanitize_key($_GET['action']);
        if ($action === 'approve') update_post_meta($ad_id, '_imz_ad_status', 'ativo');
        elseif ($action === 'pause') update_post_meta($ad_id, '_imz_ad_status', 'pausado');
        elseif ($action === 'reject') update_post_meta($ad_id, '_imz_ad_status', 'rejeitado');
        elseif ($action === 'mark_paid' && function_exists('imz_ad_mark_paid')) {
            // Fallback manual: o cliente pagou por fora ou o callback falhou
            imz_ad_mark_paid($ad_id, '', get_post_meta($ad_id, '_imz_ad_price', true), 'MANUAL_' . time(), 'Manual (admin)');
        }
        elseif ($action === 'delete_ad') wp_delete_post($ad_id, true);
        echo '<div class="notice notice-success is-dismissible"><p>Ação realizada com sucesso.</p></div>';
    }

    // --- PROCESSAR CRIAÇÃO DE ANÚNCIO PELO ADMIN ---
    if (isset($_POST['imz_admin_create_ad']) && wp_verify_nonce($_POST['_imz_admin_ad_nonce'], 'imz_admin_create_ad_action')) {
        $title = sanitize_text_field($_POST['ad_title']);
        $type = sanitize_key($_POST['ad_type']);
        $text = sanitize_textarea_field($_POST['ad_text'] ?? '');
        $link = esc_url_raw($_POST['ad_link'] ?? '');
        $image_url = esc_url_raw($_POST['ad_image_url'] ?? '');
        $duration = absint($_POST['ad_duration'] ?? 7);
        $target_countries = sanitize_text_field($_POST['ad_target_countries'] ?? '');
        $target_regions = sanitize_text_field($_POST['ad_target_regions'] ?? '');
        $ad_format = sanitize_key($_POST['ad_format'] ?? 'leaderboard');
        $ad_label = sanitize_text_field($_POST['ad_label'] ?? 'Anúncio');
        $start = current_time('Y-m-d');
        $end = date('Y-m-d', strtotime("+{$duration} days"));

        // Obter dimensões do formato
        $formats = function_exists('imz_get_ad_formats') ? imz_get_ad_formats() : [];
        $fmt_width = isset($formats[$ad_format]) ? $formats[$ad_format]['width'] : 728;
        $fmt_height = isset($formats[$ad_format]) ? $formats[$ad_format]['height'] : 90;

        if (!empty($title)) {
            $ad_id = wp_insert_post([
                'post_type' => 'imz_anuncio', 'post_title' => $title,
                'post_status' => 'publish', 'post_author' => get_current_user_id(),
                'meta_input' => [
                    '_imz_ad_status' => 'ativo', '_imz_ad_type' => $type,
                    '_imz_ad_text' => $text, '_imz_ad_link' => $link,
                    '_imz_ad_image_url' => $image_url, '_imz_ad_start_date' => $start,
                    '_imz_ad_end_date' => $end, '_imz_ad_duration' => $duration,
                    '_imz_ad_label' => $ad_label, '_imz_ad_target_countries' => $target_countries,
                    '_imz_ad_target_regions' => $target_regions,
                    '_imz_ad_format' => $ad_format,
                    '_imz_ad_format_width' => $fmt_width,
                    '_imz_ad_format_height' => $fmt_height,
                ],
            ]);
            echo '<div class="notice notice-success"><p>Anúncio "<strong>' . esc_html($title) . '</strong>" criado e ativado!</p></div>';
        }
    }

    // --- PROCESSAR EDIÇÃO DE ANÚNCIO EXISTENTE ---
    if (isset($_POST['imz_admin_update_ad']) && wp_verify_nonce($_POST['_imz_admin_edit_nonce'], 'imz_admin_edit_ad_action')) {
        $edit_id = absint($_POST['edit_ad_id']);
        if ($edit_id && get_post_type($edit_id) === 'imz_anuncio') {
            $title = sanitize_text_field($_POST['ad_title']);
            $type = sanitize_key($_POST['ad_type']);
            $text = sanitize_textarea_field($_POST['ad_text'] ?? '');
            $link = esc_url_raw($_POST['ad_link'] ?? '');
            $image_url = esc_url_raw($_POST['ad_image_url'] ?? '');
            $duration = absint($_POST['ad_duration'] ?? 7);
            $target_countries = sanitize_text_field($_POST['ad_target_countries'] ?? '');
            $target_regions = sanitize_text_field($_POST['ad_target_regions'] ?? '');
            $ad_format = sanitize_key($_POST['ad_format'] ?? 'leaderboard');
            $ad_label = sanitize_text_field($_POST['ad_label'] ?? 'Anúncio');
            $ad_status = sanitize_key($_POST['ad_status'] ?? 'ativo');

            $formats = function_exists('imz_get_ad_formats') ? imz_get_ad_formats() : [];
            $fmt_width = isset($formats[$ad_format]) ? $formats[$ad_format]['width'] : 728;
            $fmt_height = isset($formats[$ad_format]) ? $formats[$ad_format]['height'] : 90;

            // Recalcular data de fim
            $start_date = get_post_meta($edit_id, '_imz_ad_start_date', true) ?: current_time('Y-m-d');
            $end_date = date('Y-m-d', strtotime($start_date . " +{$duration} days"));

            wp_update_post(['ID' => $edit_id, 'post_title' => $title]);

            $meta_updates = [
                '_imz_ad_type' => $type, '_imz_ad_text' => $text,
                '_imz_ad_link' => $link, '_imz_ad_image_url' => $image_url,
                '_imz_ad_duration' => $duration, '_imz_ad_end_date' => $end_date,
                '_imz_ad_label' => $ad_label, '_imz_ad_target_countries' => $target_countries,
                '_imz_ad_target_regions' => $target_regions,
                '_imz_ad_format' => $ad_format, '_imz_ad_format_width' => $fmt_width,
                '_imz_ad_format_height' => $fmt_height, '_imz_ad_status' => $ad_status,
            ];
            foreach ($meta_updates as $key => $val) {
                update_post_meta($edit_id, $key, $val);
            }
            echo '<div class="notice notice-success"><p>Anúncio "<strong>' . esc_html($title) . '</strong>" atualizado com sucesso!</p></div>';
        }
    }

    // --- PROCESSAR IMPULSIONAR MÚSICA PELO ADMIN ---
    if (isset($_POST['imz_admin_boost_music']) && wp_verify_nonce($_POST['_imz_admin_boost_nonce'], 'imz_admin_boost_music_action')) {
        $music_id = absint($_POST['boost_music_id']);
        $boost_days = absint($_POST['boost_days'] ?? 3);
        $boost_format = sanitize_key($_POST['boost_format'] ?? 'rectangle');
        if ($music_id && get_post($music_id)) {
            remove_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);
            $music_title = get_the_title($music_id);
            add_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);
            $now = current_time('Y-m-d H:i:s');

            $formats = function_exists('imz_get_ad_formats') ? imz_get_ad_formats() : [];
            $fmt_width = isset($formats[$boost_format]) ? $formats[$boost_format]['width'] : 300;
            $fmt_height = isset($formats[$boost_format]) ? $formats[$boost_format]['height'] : 250;

            wp_insert_post([
                'post_type' => 'impulsionamento', 'post_title' => 'Boost Admin - ' . $music_title,
                'post_status' => 'publish',
                'meta_input' => [
                    'post_id_original' => $music_id, 'valor' => 0, 'nome' => 'Admin',
                    'metodo_pagamento' => 'Admin', 'telefone_pagador' => '', 'status' => 'aprovado',
                    '_boost_duracao_dias' => $boost_days,
                    '_boost_data_inicio' => $now,
                    '_boost_data_fim' => date('Y-m-d H:i:s', strtotime("+{$boost_days} days")),
                    '_boost_format' => $boost_format,
                    '_boost_format_width' => $fmt_width,
                    '_boost_format_height' => $fmt_height,
                ],
            ]);
            echo '<div class="notice notice-success"><p>Música "<strong>' . esc_html($music_title) . '</strong>" impulsionada por ' . $boost_days . ' dias no formato ' . esc_html($formats[$boost_format]['name'] ?? $boost_format) . '!</p></div>';
        }
    }

    // --- KPIs ---
    $total_ads = (new WP_Query(['post_type' => 'imz_anuncio', 'posts_per_page' => -1, 'post_status' => 'publish']))->found_posts;
    $active_ads = (new WP_Query(['post_type' => 'imz_anuncio', 'posts_per_page' => -1, 'meta_query' => [['key' => '_imz_ad_status', 'value' => 'ativo']]]))->found_posts;
    $pending_ads = (new WP_Query(['post_type' => 'imz_anuncio', 'posts_per_page' => -1, 'meta_query' => [['key' => '_imz_ad_status', 'value' => 'pendente']]]))->found_posts;
    $awaiting_payment_ads = (new WP_Query(['post_type' => 'imz_anuncio', 'posts_per_page' => -1, 'meta_query' => [['key' => '_imz_ad_status', 'value' => 'aguardando_pagamento']]]))->found_posts;
    $total_impressions = $has_stats ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $stats_table WHERE event_type='impression'") : 0;
    $total_clicks = $has_stats ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $stats_table WHERE event_type='click'") : 0;
    $global_ctr = $total_impressions > 0 ? round(($total_clicks / $total_impressions) * 100, 1) : 0;

    ?>
    <style>
    .imz-ads-wrap { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
    .imz-ads-wrap h1 { font-size: 26px; font-weight: 700; margin-bottom: 4px; }
    .imz-ads-subtitle { color: #6b7280; margin-top: 0; font-size: 14px; margin-bottom: 20px; }
    .imz-ads-nav { display: flex; gap: 0; background: #f3f4f6; border-radius: 8px; padding: 3px; margin-bottom: 24px; display: inline-flex; }
    .imz-ads-nav a { padding: 8px 18px; text-decoration: none; font-size: 13px; font-weight: 600; color: #6b7280; border-radius: 6px; transition: all 0.2s; }
    .imz-ads-nav a.active { background: #fff; color: #111; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
    .imz-ads-nav a:hover:not(.active) { color: #111; }
    .imz-ads-kpi { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 14px; margin-bottom: 28px; }
    .imz-ads-kpi-card { background: #fff; border: 1px solid #e5e7eb; border-radius: 10px; padding: 18px; text-align: center; }
    .imz-ads-kpi-card .kpi-val { font-size: 28px; font-weight: 800; color: #111; }
    .imz-ads-kpi-card .kpi-label { font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.5px; margin-top: 4px; }
    .imz-ads-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 24px; }
    @media(max-width:900px) { .imz-ads-grid-2 { grid-template-columns: 1fr; } }
    .imz-ads-box { background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; padding: 24px; }
    .imz-ads-box h3 { font-size: 16px; font-weight: 700; margin: 0 0 16px; display: flex; align-items: center; gap: 8px; }
    .imz-ads-box label { display: block; font-size: 13px; font-weight: 600; color: #374151; margin-bottom: 4px; }
    .imz-ads-box input[type=text], .imz-ads-box input[type=url], .imz-ads-box input[type=number],
    .imz-ads-box textarea, .imz-ads-box select { width: 100%; padding: 8px 10px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 13px; box-sizing: border-box; margin-bottom: 12px; }
    .imz-ads-box textarea { height: 60px; resize: vertical; }
    .imz-ads-table { width: 100%; border-collapse: collapse; }
    .imz-ads-table th { background: #f9fafb; text-align: left; padding: 8px 12px; font-size: 11px; text-transform: uppercase; color: #6b7280; border-bottom: 1px solid #e5e7eb; }
    .imz-ads-table td { padding: 10px 12px; border-bottom: 1px solid #f3f4f6; font-size: 13px; }
    .imz-ads-table tr:last-child td { border-bottom: none; }
    .imz-badge { padding: 3px 10px; border-radius: 50px; font-size: 11px; font-weight: 700; display: inline-block; }
    .imz-badge-ativo { background: #d1fae5; color: #065f46; }
    .imz-badge-pendente { background: #fef3c7; color: #92400e; }
    .imz-badge-pausado { background: #e0e7ff; color: #3730a3; }
    .imz-badge-rejeitado { background: #fee2e2; color: #991b1b; }
    .imz-badge-expirado { background: #f3f4f6; color: #6b7280; }
    .imz-badge-aguardando_pagamento { background: #fce7f3; color: #9d174d; }
    .imz-report-card { background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; padding: 24px; margin-bottom: 20px; }
    .imz-report-card h3 { margin: 0 0 16px; font-size: 16px; }
    .imz-report-grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px; margin-bottom: 16px; }
    .imz-report-stat { text-align: center; padding: 14px; background: #f9fafb; border-radius: 8px; }
    .imz-report-stat .val { font-size: 24px; font-weight: 800; color: #111; }
    .imz-report-stat .lbl { font-size: 11px; color: #6b7280; text-transform: uppercase; }
    .imz-device-bar { display: flex; height: 8px; border-radius: 4px; overflow: hidden; margin: 8px 0; }
    .imz-device-legend { display: flex; gap: 16px; font-size: 12px; color: #6b7280; flex-wrap: wrap; }
    .imz-device-legend span::before { content: ''; display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 4px; vertical-align: middle; }
    .imz-device-legend .mobile::before { background: #3b82f6; }
    .imz-device-legend .desktop::before { background: #10b981; }
    .imz-device-legend .tablet::before { background: #f59e0b; }
    .imz-ads-wrap{--ads-primary:#146c43;--ads-gold:#efb700;--ads-bg:#f7f7f2;--ads-surface:#fff;--ads-soft:#f0f2ed;--ads-line:#dfe4dd;--ads-text:#1a1f1b;--ads-muted:#667069;max-width:none;margin:0 20px 0 2px;padding:26px 24px 70px;min-height:100vh;background:var(--ads-bg);color:var(--ads-text)}
    .imz-ads-hero{display:flex;align-items:center;gap:14px;margin-bottom:16px}
    .imz-ads-hero-icon{width:52px;height:52px;display:grid;place-items:center;border-radius:17px;background:#d8f2e4;color:var(--ads-primary)}
    .imz-ads-hero-icon .dashicons{width:24px;height:24px;font-size:24px}
    .imz-ads-wrap h1{margin:0 0 4px;font-size:30px;letter-spacing:-.03em}
    .imz-ads-wrap .imz-ads-subtitle{margin:0;color:var(--ads-muted)}
    .imz-ads-wrap .imz-ads-nav{display:flex;max-width:100%;overflow:auto;gap:6px;margin:0 0 18px;padding:7px;border:1px solid var(--ads-line);border-radius:18px;background:var(--ads-surface)}
    .imz-ads-wrap .imz-ads-nav a{display:inline-flex;align-items:center;gap:7px;min-height:40px;padding:0 13px;border-radius:12px;white-space:nowrap}
    .imz-ads-wrap .imz-ads-nav a.active{background:var(--ads-primary);color:#fff;box-shadow:none}
    .imz-ads-wrap .imz-ads-nav a:hover:not(.active){background:var(--ads-soft)}
    .imz-ads-nav .dashicons{width:17px;height:17px;font-size:17px}
    .imz-ads-nav-count{min-width:20px;height:20px;display:grid;place-items:center;padding:0 5px;border-radius:999px;background:#f4c84a;color:#201a00;font-size:10px}
    .imz-ads-wrap .imz-ads-kpi{gap:10px;margin-bottom:16px}
    .imz-ads-wrap .imz-ads-kpi-card{min-height:98px;padding:17px;border-color:var(--ads-line);border-radius:19px;text-align:left}
    .imz-ads-wrap .imz-ads-kpi-card .kpi-val{font-size:27px}
    .imz-ads-wrap .imz-ads-kpi-card.sponsored{background:#e8f4ee}
    .imz-ads-wrap .imz-ads-box,.imz-ads-wrap .imz-report-card{border-color:var(--ads-line);border-radius:21px;box-shadow:none}
    .imz-ads-wrap .imz-ads-table{border-color:var(--ads-line)!important}
    .imz-ads-wrap .imz-ads-table th{background:#f2f4ef}
    .imz-ads-sponsored-summary{display:flex;align-items:center;justify-content:space-between;gap:18px;margin:0 0 24px;padding:17px 19px;border:1px solid #b8d7c7;border-radius:20px;background:#e8f4ee}
    .imz-ads-sponsored-summary>div{display:flex;align-items:center;gap:13px}
    .imz-ads-sponsored-summary>div>.dashicons{width:42px;height:42px;padding-top:11px;border-radius:14px;background:#cce9da;color:var(--ads-primary);font-size:20px;text-align:center}
    .imz-ads-sponsored-summary strong{font-size:14px}
    .imz-ads-sponsored-summary p{margin:4px 0 0;color:#53645b;font-size:12px}
    .imz-ads-modern-btn{min-height:40px;display:inline-flex;align-items:center;gap:7px;padding:0 15px;border-radius:999px;background:var(--ads-primary);color:#fff;text-decoration:none;font-size:12px;font-weight:800;white-space:nowrap}
    .imz-ads-modern-btn:hover{background:#0e5838;color:#fff}
    .imz-ads-section-title{display:flex;align-items:center;gap:8px;font-size:18px}
    .imz-ads-section-title .dashicons{color:var(--ads-primary)}
    @media(max-width:782px){.imz-ads-wrap{margin:0;padding:18px 10px 55px}.imz-ads-sponsored-summary{align-items:flex-start;display:grid}.imz-ads-modern-btn{justify-self:start}.imz-ads-wrap .imz-ads-kpi{grid-template-columns:1fr 1fr}}
    @media(max-width:520px){.imz-ads-wrap .imz-ads-kpi{grid-template-columns:1fr}}
    </style>

    <div class="wrap imz-ads-wrap">
        <div class="imz-ads-hero">
            <span class="imz-ads-hero-icon"><span class="dashicons dashicons-megaphone" aria-hidden="true"></span></span>
            <div>
                <h1>Gestor de Anúncios &amp; Campanhas</h1>
                <p class="imz-ads-subtitle">Anúncios, impulsionamentos e músicas patrocinadas numa única operação.</p>
            </div>
        </div>

        <nav class="imz-ads-nav" aria-label="Áreas do gestor de campanhas">
            <a href="<?php echo esc_url($base_url); ?>" class="<?php echo $view === 'dashboard' ? 'active' : ''; ?>"><span class="dashicons dashicons-dashboard"></span>Visão geral</a>
            <a href="<?php echo esc_url($base_url . '&view=create'); ?>" class="<?php echo $view === 'create' ? 'active' : ''; ?>"><span class="dashicons dashicons-plus-alt2"></span>Criar anúncio</a>
            <a href="<?php echo esc_url($base_url . '&view=boost'); ?>" class="<?php echo $view === 'boost' ? 'active' : ''; ?>"><span class="dashicons dashicons-chart-line"></span>Impulsionar música</a>
            <a href="<?php echo esc_url($base_url . '&view=boosts_list'); ?>" class="<?php echo ($view === 'boosts_list' || $view === 'boost_detail') ? 'active' : ''; ?>"><span class="dashicons dashicons-controls-repeat"></span>Impulsionamentos</a>
            <a href="<?php echo esc_url($base_url . '&view=sponsored'); ?>" class="<?php echo $view === 'sponsored' ? 'active' : ''; ?>"><span class="dashicons dashicons-playlist-audio"></span>Músicas patrocinadas<?php if (!empty($sp_summary['pending_payouts'])) : ?><span class="imz-ads-nav-count"><?php echo (int) $sp_summary['pending_payouts']; ?></span><?php endif; ?></a>
            <a href="<?php echo esc_url($base_url . '&view=reports'); ?>" class="<?php echo $view === 'reports' ? 'active' : ''; ?>"><span class="dashicons dashicons-chart-bar"></span>Relatórios</a>
            <a href="<?php echo esc_url($base_url . '&view=list'); ?>" class="<?php echo $view === 'list' ? 'active' : ''; ?>"><span class="dashicons dashicons-megaphone"></span>Anúncios</a>
        </nav>

        <?php if ($view === 'dashboard') : ?>
        <!-- ============ DASHBOARD ============ -->
        <div class="imz-ads-kpi">
            <div class="imz-ads-kpi-card"><div class="kpi-val"><?php echo $total_ads; ?></div><div class="kpi-label">Total de Anúncios</div></div>
            <div class="imz-ads-kpi-card"><div class="kpi-val" style="color:#059669;"><?php echo $active_ads; ?></div><div class="kpi-label">Ativos</div></div>
            <div class="imz-ads-kpi-card"><div class="kpi-val" style="color:#f59e0b;"><?php echo $pending_ads; ?></div><div class="kpi-label">Pendentes</div></div>
            <?php if ($awaiting_payment_ads > 0) : ?>
            <div class="imz-ads-kpi-card"><div class="kpi-val" style="color:#9d174d;"><?php echo $awaiting_payment_ads; ?></div><div class="kpi-label">Aguardam Pagamento</div></div>
            <?php endif; ?>
            <div class="imz-ads-kpi-card"><div class="kpi-val"><?php echo number_format($total_impressions); ?></div><div class="kpi-label">Impressões</div></div>
            <div class="imz-ads-kpi-card"><div class="kpi-val"><?php echo number_format($total_clicks); ?></div><div class="kpi-label">Cliques</div></div>
            <div class="imz-ads-kpi-card"><div class="kpi-val"><?php echo $global_ctr; ?>%</div><div class="kpi-label">CTR Médio</div></div>
            <?php if (!empty($sp_summary['ready'])) : ?>
            <div class="imz-ads-kpi-card sponsored"><div class="kpi-val" style="color:#146c43;"><?php echo (int) $sp_summary['active_tracks']; ?></div><div class="kpi-label">Faixas patrocinadas ativas</div></div>
            <?php endif; ?>
        </div>

        <?php if (!empty($sp_summary['ready'])) : ?>
        <section class="imz-ads-sponsored-summary">
            <div>
                <span class="dashicons dashicons-playlist-audio" aria-hidden="true"></span>
                <span><strong>Programa de Músicas Patrocinadas</strong><p><?php echo (int) $sp_summary['active_tracks']; ?> faixa(s) ativa(s), <?php echo (int) $sp_summary['pending_payouts']; ?> pagamento(s) pendente(s) e US$ <?php echo esc_html(number_format_i18n((float) $sp_summary['budget_remaining'], 2)); ?> de orçamento disponível.</p></span>
            </div>
            <a class="imz-ads-modern-btn" href="<?php echo esc_url($base_url . '&view=sponsored'); ?>"><span class="dashicons dashicons-arrow-right-alt2"></span>Abrir operação</a>
        </section>
        <?php endif; ?>

        <!-- Relatórios por campanha (top 10 anúncios ativos) -->
        <h2 class="imz-ads-section-title"><span class="dashicons dashicons-chart-bar" aria-hidden="true"></span>Relatório por campanha</h2>
        <?php
        $active_campaigns = new WP_Query(['post_type' => 'imz_anuncio', 'posts_per_page' => 10, 'meta_query' => [['key' => '_imz_ad_status', 'value' => ['ativo', 'pausado', 'expirado'], 'compare' => 'IN']], 'orderby' => 'date', 'order' => 'DESC']);

        // Agregações em lote (4 queries no total, em vez de 7+ por campanha)
        $campaign_ids   = wp_list_pluck($active_campaigns->posts, 'ID');
        $bulk_totals    = function_exists('imz_ads_get_totals_bulk') ? imz_ads_get_totals_bulk($campaign_ids) : [];
        $bulk_devices   = function_exists('imz_ads_get_device_bulk') ? imz_ads_get_device_bulk($campaign_ids) : [];
        $bulk_countries = function_exists('imz_ads_get_geo_breakdown_bulk') ? imz_ads_get_geo_breakdown_bulk($campaign_ids, 'country') : [];
        $bulk_regions   = function_exists('imz_ads_get_geo_breakdown_bulk') ? imz_ads_get_geo_breakdown_bulk($campaign_ids, 'region') : [];

        if ($active_campaigns->have_posts()) : while ($active_campaigns->have_posts()) : $active_campaigns->the_post();
            $cid = get_the_ID();
            $c_status = get_post_meta($cid, '_imz_ad_status', true);
            $c_totals = $bulk_totals[$cid] ?? ['impressions' => 0, 'clicks' => 0];
            $c_impressions = $c_totals['impressions'];
            $c_clicks = $c_totals['clicks'];
            $c_ctr = $c_impressions > 0 ? round(($c_clicks / $c_impressions) * 100, 1) : 0;

            // Device breakdown
            $c_devices = $bulk_devices[$cid] ?? ['mobile' => 0, 'desktop' => 0, 'tablet' => 0];
            $c_total_device = array_sum($c_devices);
            $pct_m = $c_total_device > 0 ? round($c_devices['mobile'] / $c_total_device * 100) : 0;
            $pct_d = $c_total_device > 0 ? round($c_devices['desktop'] / $c_total_device * 100) : 0;
            $pct_t = $c_total_device > 0 ? round($c_devices['tablet'] / $c_total_device * 100) : 0;

            // Top countries / regions (objetos com ->k e ->total)
            $c_countries = $bulk_countries[$cid] ?? [];
            $c_regions   = $bulk_regions[$cid] ?? [];
        ?>
        <div class="imz-report-card">
            <h3>
                <?php the_title(); ?>
                <span class="imz-badge imz-badge-<?php echo $c_status; ?>"><?php echo ucfirst($c_status); ?></span>
            </h3>
            <div class="imz-report-grid-3">
                <div class="imz-report-stat"><div class="val"><?php echo number_format($c_impressions); ?></div><div class="lbl">Impressões</div></div>
                <div class="imz-report-stat"><div class="val"><?php echo number_format($c_clicks); ?></div><div class="lbl">Cliques</div></div>
                <div class="imz-report-stat"><div class="val"><?php echo $c_ctr; ?>%</div><div class="lbl">CTR</div></div>
            </div>
            <?php if ($c_total_device > 0) : ?>
            <p style="font-size:12px; font-weight:600; color:#374151; margin:0 0 4px;">Dispositivos:</p>
            <div class="imz-device-bar">
                <?php if ($pct_m > 0) : ?><div style="width:<?php echo $pct_m; ?>%; background:#3b82f6;"></div><?php endif; ?>
                <?php if ($pct_d > 0) : ?><div style="width:<?php echo $pct_d; ?>%; background:#10b981;"></div><?php endif; ?>
                <?php if ($pct_t > 0) : ?><div style="width:<?php echo $pct_t; ?>%; background:#f59e0b;"></div><?php endif; ?>
            </div>
            <div class="imz-device-legend">
                <span class="mobile">Mobile <?php echo $pct_m; ?>%</span>
                <span class="desktop">Desktop <?php echo $pct_d; ?>%</span>
                <span class="tablet">Tablet <?php echo $pct_t; ?>%</span>
            </div>
            <?php endif; ?>
            <?php if (!empty($c_countries) || !empty($c_regions)) : ?>
            <div style="display:flex; gap:20px; margin-top:12px; flex-wrap:wrap;">
                <?php if (!empty($c_countries)) : ?>
                <div style="flex:1; min-width:150px;">
                    <p style="font-size:12px; font-weight:600; color:#374151; margin:0 0 6px;">Países:</p>
                    <?php foreach ($c_countries as $cc) : ?>
                        <span style="font-size:12px; color:#6b7280; margin-right:10px;"><?php echo esc_html($cc->k); ?> (<?php echo $cc->total; ?>)</span>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
                <?php if (!empty($c_regions)) : ?>
                <div style="flex:1; min-width:150px;">
                    <p style="font-size:12px; font-weight:600; color:#374151; margin:0 0 6px;">Províncias:</p>
                    <?php foreach ($c_regions as $cr) : ?>
                        <span style="font-size:12px; color:#6b7280; margin-right:10px;"><?php echo esc_html($cr->k); ?> (<?php echo $cr->total; ?>)</span>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
        <?php endwhile; wp_reset_postdata(); else : ?>
        <p style="color:#9ca3af;">Nenhuma campanha encontrada.</p>
        <?php endif; ?>

        <?php elseif ($view === 'reports') : ?>
        <!-- ============ RELATÓRIOS PROFISSIONAIS ============ -->
        <?php
        if (function_exists('imz_render_ads_reports_view')) {
            imz_render_ads_reports_view($base_url);
        } else {
            echo '<p>Erro: módulo de relatórios não carregado.</p>';
        }
        ?>

        <?php elseif ($view === 'create') : ?>
        <!-- ============ CRIAR ANÚNCIO (com Formatos + Preview) ============ -->
        <?php
        if (function_exists('imz_render_ad_create_form_with_preview')) {
            imz_render_ad_create_form_with_preview();
        } else {
            echo '<p>Erro: Sistema de formatos não carregado.</p>';
        }
        ?>

        <?php elseif ($view === 'edit') : ?>
        <!-- ============ EDITAR ANÚNCIO ============ -->
        <?php
        $edit_id = absint($_GET['ad_id'] ?? 0);
        if ($edit_id && get_post_type($edit_id) === 'imz_anuncio') {
            if (function_exists('imz_render_ad_edit_form_with_preview')) {
                imz_render_ad_edit_form_with_preview($edit_id);
            } else {
                echo '<p>Erro: Sistema de formatos não carregado.</p>';
            }
        } else {
            echo '<div class="notice notice-error"><p>Anúncio não encontrado.</p></div>';
        }
        ?>

        <?php elseif ($view === 'boost') : ?>
        <!-- ============ IMPULSIONAR MÚSICA (com Formato) ============ -->
        <?php $formats = function_exists('imz_get_ad_formats') ? imz_get_ad_formats() : []; ?>
        <style>
        .imz-boost-wrap { display: grid; grid-template-columns: 1fr 380px; gap: 24px; align-items: start; }
        @media (max-width: 1000px) { .imz-boost-wrap { grid-template-columns: 1fr; } }
        /* Pesquisa de música */
        .imz-music-search { position: relative; margin-bottom: 16px; }
        .imz-music-search > input[type=text] { width: 100%; padding: 10px 14px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 14px; box-sizing: border-box; }
        .imz-music-results { position: absolute; top: 100%; left: 0; right: 0; z-index: 50; background: #fff; border: 1px solid #d1d5db; border-radius: 8px; box-shadow: 0 8px 24px rgba(0,0,0,0.12); max-height: 340px; overflow-y: auto; display: none; }
        .imz-music-results.open { display: block; }
        .imz-music-result { display: flex; align-items: center; gap: 10px; padding: 8px 12px; cursor: pointer; border-bottom: 1px solid #f3f4f6; }
        .imz-music-result:last-child { border-bottom: none; }
        .imz-music-result:hover { background: #eff6ff; }
        .imz-music-result img, .imz-music-result .no-thumb { width: 42px; height: 42px; border-radius: 6px; object-fit: cover; flex: 0 0 42px; }
        .imz-music-result .no-thumb { background: linear-gradient(135deg,#374151,#1f2937); display: flex; align-items: center; justify-content: center; color: #9ca3af; font-size: 18px; }
        .imz-music-result .mr-info { min-width: 0; }
        .imz-music-result .mr-title { font-size: 13px; font-weight: 600; color: #111; margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .imz-music-result .mr-meta { font-size: 11.5px; color: #6b7280; margin: 2px 0 0; }
        .imz-music-result-empty { padding: 14px; font-size: 13px; color: #9ca3af; text-align: center; }
        .imz-music-selected { display: none; margin-top: 10px; border: 1px solid #bfdbfe; background: #eff6ff; border-radius: 10px; padding: 12px; }
        .imz-music-selected.on { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
        .imz-music-selected img, .imz-music-selected .no-thumb { width: 64px; height: 64px; border-radius: 8px; object-fit: cover; flex: 0 0 64px; }
        .imz-music-selected .no-thumb { background: linear-gradient(135deg,#374151,#1f2937); display: flex; align-items: center; justify-content: center; color: #9ca3af; font-size: 24px; }
        .imz-music-selected .ms-info { flex: 1; min-width: 180px; }
        .imz-music-selected .ms-title { font-size: 14px; font-weight: 700; color: #111; margin: 0; }
        .imz-music-selected .ms-artist { font-size: 12.5px; color: #2563eb; font-weight: 600; margin: 2px 0; }
        .imz-music-selected .ms-stats { font-size: 12px; color: #6b7280; margin: 4px 0 0; }
        .imz-music-selected .ms-change { font-size: 12px; color: #2563eb; cursor: pointer; background: none; border: none; padding: 0; text-decoration: underline; }
        /* Preview horizontal (banner): capa quadrada à esquerda, sem corte */
        .imz-boost-card-preview.horizontal { display: flex; flex-direction: row; align-items: center; }
        .imz-boost-card-preview.horizontal .boost-cover-wrap { flex: 0 0 auto; width: 84px; }
        .imz-boost-card-preview.horizontal .boost-cover-wrap img,
        .imz-boost-card-preview.horizontal #imz-boost-preview-placeholder { width: 84px !important; aspect-ratio: 1 / 1 !important; }
        .imz-boost-card-preview.horizontal .boost-info { flex: 1; min-width: 0; padding: 10px 14px; }
        .imz-boost-preview { background: #1a1a1a; border-radius: 12px; overflow: hidden; border: 1px solid #e5e7eb; position: sticky; top: 40px; }
        .imz-boost-preview-header { background: #f9fafb; padding: 12px 16px; border-bottom: 1px solid #e5e7eb; font-size: 13px; font-weight: 600; color: #374151; }
        .imz-boost-preview-body { padding: 20px; display: flex; justify-content: center; }
        .imz-boost-card-preview { border-radius: 10px; overflow: hidden; background: #222; border: 1px dashed #444; transition: all 0.3s; }
        .imz-boost-card-preview img { width: 100%; display: block; object-fit: cover; }
        .imz-boost-card-preview .boost-info { padding: 14px; }
        .imz-boost-card-preview .boost-badge { display: inline-block; background: rgba(245,158,11,0.85); color: #fff; font-size: 9px; font-weight: 700; padding: 2px 8px; border-radius: 4px; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 10px; }
        .imz-boost-card-preview .boost-title { color: #fff; font-size: 14px; font-weight: 700; margin: 0 0 4px; }
        .imz-boost-card-preview .boost-artist { color: #f59e0b; font-size: 12px; margin: 0 0 4px; font-weight: 600; }
        .imz-boost-card-preview .boost-meta { color: #888; font-size: 11px; margin: 0; }
        .imz-boost-card-preview .boost-play { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); width: 44px; height: 44px; background: rgba(0,0,0,0.6); border-radius: 50%; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.2s; }
        .imz-boost-card-preview:hover .boost-play { opacity: 1; }
        .imz-boost-card-preview .boost-cover-wrap { position: relative; }
        .imz-boost-fmt-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 8px; margin-bottom: 16px; }
        .imz-boost-fmt-card { border: 2px solid #e5e7eb; border-radius: 8px; padding: 10px; cursor: pointer; background: #fff; text-align: center; transition: all 0.2s; position: relative; }
        .imz-boost-fmt-card:hover { border-color: #fbbf24; }
        .imz-boost-fmt-card.selected { border-color: #f59e0b; background: #fffbeb; box-shadow: 0 0 0 2px rgba(245,158,11,0.2); }
        .imz-boost-fmt-card.selected::after { content: '✓'; position: absolute; top: 6px; right: 6px; width: 18px; height: 18px; background: #f59e0b; color: #fff; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 10px; font-weight: 700; }
        .imz-boost-fmt-card .fmt-icon { font-size: 20px; }
        .imz-boost-fmt-card .fmt-name { font-size: 11px; font-weight: 700; color: #111; margin: 4px 0 0; }
        .imz-boost-fmt-card .fmt-dims { font-size: 10px; color: #9ca3af; font-family: monospace; }
        </style>

        <div class="imz-boost-wrap">
            <div class="imz-ads-box">
                <h3>🔥 Impulsionar uma Música</h3>
                <p style="color:#6b7280; font-size:13px; margin-top:0;">A música aparecerá como "Música Destacada" com o mesmo formato visual dos anúncios.</p>
                <form method="post" id="imz-boost-form">
                    <?php wp_nonce_field('imz_admin_boost_music_action', '_imz_admin_boost_nonce'); ?>

                    <label style="font-size:13px; font-weight:600; color:#374151; display:block; margin-bottom:4px;">Selecione a Música</label>
                    <div class="imz-music-search" id="imz-music-search">
                        <input type="text" id="imz-music-search-input" placeholder="🔍 Pesquisar música por título… (clique para ver as recentes)" autocomplete="off">
                        <div class="imz-music-results" id="imz-music-results"></div>
                        <input type="hidden" name="boost_music_id" id="imz-boost-music-id" value="">
                        <div class="imz-music-selected" id="imz-music-selected"></div>
                    </div>

                    <label style="font-size:13px; font-weight:600; color:#374151; display:block; margin-bottom:6px;">Formato de Exibição</label>
                    <div class="imz-boost-fmt-grid">
                        <?php $first = true; foreach ($formats as $key => $fmt): ?>
                        <div class="imz-boost-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="fmt-icon"><?php echo $fmt['icon']; ?></span>
                            <p class="fmt-name"><?php echo esc_html($fmt['name']); ?></p>
                            <p class="fmt-dims"><?php echo esc_html($fmt['label']); ?></p>
                        </div>
                        <?php $first = false; endforeach; ?>
                    </div>
                    <input type="hidden" name="boost_format" id="imz-boost-format" value="leaderboard">

                    <label style="font-size:13px; font-weight:600; color:#374151; display:block; margin-bottom:4px;">Duração</label>
                    <select name="boost_days" style="width:100%; padding:8px; border:1px solid #d1d5db; border-radius:6px; margin-bottom:16px;">
                        <option value="1">24 Horas</option>
                        <option value="3" selected>3 Dias</option>
                        <option value="7">7 Dias</option>
                        <option value="14">14 Dias</option>
                        <option value="30">30 Dias</option>
                    </select>
                    <br>
                    <button type="submit" name="imz_admin_boost_music" class="button button-primary button-hero" style="width:100%;">🚀 Impulsionar Agora</button>
                </form>
            </div>

            <!-- Preview do card de música -->
            <div class="imz-boost-preview">
                <div class="imz-boost-preview-header">Preview — <span id="imz-boost-dims">728 × 90</span></div>
                <div class="imz-boost-preview-body">
                    <div class="imz-boost-card-preview" id="imz-boost-preview-card" style="width:300px;">
                        <div class="boost-cover-wrap">
                            <img id="imz-boost-preview-img" src="" alt="" style="display:none; aspect-ratio:1/1;">
                            <div id="imz-boost-preview-placeholder" style="width:100%; aspect-ratio:1/1; background:linear-gradient(135deg,#374151,#1f2937); display:flex; align-items:center; justify-content:center;">
                                <svg viewBox="0 0 24 24" fill="none" stroke="#555" stroke-width="1.5" width="40" height="40"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
                            </div>
                            <div class="boost-play">
                                <svg viewBox="0 0 24 24" fill="#fff" width="22" height="22"><path d="M8 5v14l11-7z"/></svg>
                            </div>
                        </div>
                        <div class="boost-info">
                            <span class="boost-badge">🔥 Música Destacada</span>
                            <p class="boost-title" id="imz-boost-preview-title">Selecione uma música...</p>
                            <p class="boost-artist" id="imz-boost-preview-artist"></p>
                            <p class="boost-meta" id="imz-boost-preview-cats"></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <script>
        (function() {
            var formats = <?php echo json_encode($formats); ?>;
            var searchNonce = '<?php echo wp_create_nonce('imz_admin_search_music'); ?>';
            var ajaxUrl = '<?php echo esc_js(admin_url('admin-ajax.php')); ?>';
            var currentFormat = 'leaderboard';
            var previewMaxWidth = 340;
            var selectedMusic = null;

            // Format selection
            document.querySelectorAll('.imz-boost-fmt-card').forEach(function(card) {
                card.addEventListener('click', function() {
                    document.querySelectorAll('.imz-boost-fmt-card').forEach(function(c) { c.classList.remove('selected'); });
                    this.classList.add('selected');
                    currentFormat = this.getAttribute('data-format');
                    document.getElementById('imz-boost-format').value = currentFormat;
                    updateBoostPreview();
                });
            });

            // ----- PESQUISA DE MÚSICA -----
            var searchInput = document.getElementById('imz-music-search-input');
            var resultsBox = document.getElementById('imz-music-results');
            var hiddenId = document.getElementById('imz-boost-music-id');
            var selectedBox = document.getElementById('imz-music-selected');
            var searchTimer = null;
            var lastQuery = null;

            function fmtNum(n) { return Number(n || 0).toLocaleString('pt'); }

            function doSearch(q) {
                if (q === lastQuery) { resultsBox.classList.add('open'); return; }
                lastQuery = q;
                var fd = new FormData();
                fd.append('action', 'imz_admin_search_music');
                fd.append('q', q);
                fd.append('nonce', searchNonce);
                fetch(ajaxUrl, { method: 'POST', body: fd })
                    .then(function(r) { return r.json(); })
                    .then(function(result) {
                        if (!result.success) return;
                        renderResults(result.data.results, q);
                    });
            }

            function renderResults(items, q) {
                resultsBox.innerHTML = '';
                if (!items.length) {
                    resultsBox.innerHTML = '<div class="imz-music-result-empty">Nenhuma música encontrada para "' + q + '".</div>';
                } else {
                    items.forEach(function(m) {
                        var row = document.createElement('div');
                        row.className = 'imz-music-result';
                        var thumbHtml = m.thumb
                            ? '<img src="' + m.thumb + '" alt="">'
                            : '<div class="no-thumb">🎵</div>';
                        row.innerHTML = thumbHtml +
                            '<div class="mr-info"><p class="mr-title"></p>' +
                            '<p class="mr-meta">' + (m.artist ? '<strong></strong> · ' : '') + '▶ ' + fmtNum(m.plays) + ' plays · ⬇ ' + fmtNum(m.downloads) + ' downloads · ' + m.date + '</p></div>';
                        row.querySelector('.mr-title').textContent = m.title;
                        if (m.artist) row.querySelector('.mr-meta strong').textContent = m.artist;
                        row.addEventListener('click', function() { selectMusic(m); });
                        resultsBox.appendChild(row);
                    });
                }
                resultsBox.classList.add('open');
            }

            function selectMusic(m) {
                selectedMusic = m;
                hiddenId.value = m.id;
                searchInput.value = m.title;
                resultsBox.classList.remove('open');

                var thumbHtml = m.thumb_md
                    ? '<img src="' + m.thumb_md + '" alt="">'
                    : '<div class="no-thumb">🎵</div>';
                selectedBox.innerHTML = thumbHtml +
                    '<div class="ms-info"><p class="ms-title"></p><p class="ms-artist"></p>' +
                    '<p class="ms-stats">▶ ' + fmtNum(m.plays) + ' plays · ⬇ ' + fmtNum(m.downloads) + ' downloads · 📅 ' + m.date + (m.cats ? ' · 🏷 ' + m.cats : '') + '</p>' +
                    '<button type="button" class="ms-change">trocar música</button> · <a href="' + m.url + '" target="_blank" style="font-size:12px;">ver post →</a></div>';
                selectedBox.querySelector('.ms-title').textContent = m.title;
                selectedBox.querySelector('.ms-artist').textContent = m.artist || '';
                selectedBox.querySelector('.ms-change').addEventListener('click', function() {
                    selectedMusic = null;
                    hiddenId.value = '';
                    searchInput.value = '';
                    selectedBox.classList.remove('on');
                    searchInput.focus();
                });
                selectedBox.classList.add('on');
                updateBoostPreview();
            }

            if (searchInput) {
                searchInput.addEventListener('input', function() {
                    clearTimeout(searchTimer);
                    var q = this.value.trim();
                    searchTimer = setTimeout(function() { doSearch(q); }, 300);
                });
                searchInput.addEventListener('focus', function() {
                    doSearch(this.value.trim());
                });
                document.addEventListener('click', function(e) {
                    if (!e.target.closest('#imz-music-search')) resultsBox.classList.remove('open');
                });
            }

            // Validação: não submeter sem música escolhida
            var boostForm = document.getElementById('imz-boost-form');
            if (boostForm) {
                boostForm.addEventListener('submit', function(e) {
                    if (!hiddenId.value) {
                        e.preventDefault();
                        searchInput.focus();
                        searchInput.style.borderColor = '#ef4444';
                        setTimeout(function() { searchInput.style.borderColor = ''; }, 1500);
                    }
                });
            }

            function updateBoostPreview() {
                var fmt = formats[currentFormat];
                if (!fmt) return;

                var card = document.getElementById('imz-boost-preview-card');
                var dims = document.getElementById('imz-boost-dims');
                var img = document.getElementById('imz-boost-preview-img');
                var placeholder = document.getElementById('imz-boost-preview-placeholder');
                var titleEl = document.getElementById('imz-boost-preview-title');
                var artistEl = document.getElementById('imz-boost-preview-artist');
                var catsEl = document.getElementById('imz-boost-preview-cats');

                // Scale card to fit
                var scale = Math.min(previewMaxWidth / fmt.width, 1);
                card.style.width = Math.round(fmt.width * scale) + 'px';
                dims.textContent = fmt.width + ' × ' + fmt.height;

                // Capas das músicas são 1:1 — nos formatos horizontais o card passa
                // a linha (capa quadrada à esquerda, sem corte); nos restantes a capa
                // mantém-se quadrada completa
                var isHorizontal = (fmt.slug === 'leaderboard' || fmt.slug === 'mobile_banner');
                card.classList.toggle('horizontal', isHorizontal);
                img.style.aspectRatio = '1/1';
                placeholder.style.aspectRatio = '1/1';

                // Dados da música selecionada (via pesquisa)
                if (selectedMusic) {
                    titleEl.textContent = selectedMusic.title;
                    artistEl.textContent = selectedMusic.artist || '';
                    catsEl.textContent = selectedMusic.cats || '';

                    if (selectedMusic.thumb_md) {
                        img.src = selectedMusic.thumb_md;
                        img.style.display = 'block';
                        placeholder.style.display = 'none';
                    } else {
                        img.style.display = 'none';
                        placeholder.style.display = 'flex';
                    }
                } else {
                    titleEl.textContent = 'Selecione uma música...';
                    artistEl.textContent = '';
                    catsEl.textContent = '';
                    img.style.display = 'none';
                    placeholder.style.display = 'flex';
                }
            }

            updateBoostPreview();
        })();
        </script>

        <?php elseif ($view === 'boosts_list') : ?>
        <!-- ============ LISTA DE BOOSTS ============ -->
        <?php
        if (function_exists('imz_render_boosts_list_page')) {
            imz_render_boosts_list_page();
        } else {
            echo '<p>Erro: Sistema de analytics de boosts não carregado. Verifique se <code>boost-analytics.php</code> está incluído.</p>';
        }
        ?>

        <?php elseif ($view === 'boost_detail') : ?>
        <!-- ============ DETALHES DO BOOST ============ -->
        <?php
        $boost_id = absint($_GET['boost_id'] ?? 0);
        if ($boost_id && function_exists('imz_render_boost_detail_page')) {
            imz_render_boost_detail_page($boost_id);
        } else {
            echo '<div class="notice notice-error"><p>Boost não encontrado ou sistema de analytics não carregado.</p></div>';
        }
        ?>

        <?php elseif ($view === 'sponsored') : ?>
        <!-- ============ MÚSICAS PATROCINADAS ============ -->
        <?php
        if (function_exists('rmbz_render_sponsored_campaigns_admin')) {
            rmbz_render_sponsored_campaigns_admin();
        } else {
            echo '<div class="notice notice-error"><p>A central de músicas patrocinadas não foi carregada.</p></div>';
        }
        ?>

        <?php elseif ($view === 'list') : ?>
        <!-- ============ LISTA COMPLETA ============ -->
        <?php
        $filter_status = isset($_GET['status_filter']) ? sanitize_key($_GET['status_filter']) : '';
        $args = ['post_type' => 'imz_anuncio', 'posts_per_page' => 30, 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC', 'paged' => max(1, absint($_GET['paged'] ?? 1))];
        if (!empty($filter_status)) $args['meta_query'] = [['key' => '_imz_ad_status', 'value' => $filter_status]];
        $ads_query = new WP_Query($args);
        ?>
        <ul class="subsubsub" style="margin-bottom:10px;">
            <li><a href="<?php echo $base_url . '&view=list'; ?>" class="<?php echo empty($filter_status) ? 'current' : ''; ?>">Todos</a> |</li>
            <li><a href="<?php echo $base_url . '&view=list&status_filter=pendente'; ?>" class="<?php echo $filter_status === 'pendente' ? 'current' : ''; ?>">Pendentes</a> |</li>
            <li><a href="<?php echo $base_url . '&view=list&status_filter=aguardando_pagamento'; ?>" class="<?php echo $filter_status === 'aguardando_pagamento' ? 'current' : ''; ?>">Aguardam Pagamento</a> |</li>
            <li><a href="<?php echo $base_url . '&view=list&status_filter=ativo'; ?>" class="<?php echo $filter_status === 'ativo' ? 'current' : ''; ?>">Ativos</a> |</li>
            <li><a href="<?php echo $base_url . '&view=list&status_filter=pausado'; ?>" class="<?php echo $filter_status === 'pausado' ? 'current' : ''; ?>">Pausados</a> |</li>
            <li><a href="<?php echo $base_url . '&view=list&status_filter=expirado'; ?>" class="<?php echo $filter_status === 'expirado' ? 'current' : ''; ?>">Expirados</a></li>
        </ul>
        <table class="imz-ads-table" style="background:#fff; border:1px solid #e5e7eb; border-radius:10px; overflow:hidden;">
            <thead><tr><th>ID</th><th>Título</th><th>Formato</th><th>Status</th><th>Período</th><th>Impressões</th><th>Cliques</th><th>CTR</th><th>Ações</th></tr></thead>
            <tbody>
            <?php if ($ads_query->have_posts()) : while ($ads_query->have_posts()) : $ads_query->the_post();
                $ad_id = get_the_ID();
                $status = get_post_meta($ad_id, '_imz_ad_status', true) ?: 'pendente';
                $type = get_post_meta($ad_id, '_imz_ad_type', true) ?: 'banner';
                $ad_format = get_post_meta($ad_id, '_imz_ad_format', true);
                $end_date = get_post_meta($ad_id, '_imz_ad_end_date', true);
                if ($status === 'ativo' && !empty($end_date) && strtotime($end_date) < current_time('timestamp')) {
                    update_post_meta($ad_id, '_imz_ad_status', 'expirado'); $status = 'expirado';
                }
                $imp = $has_stats ? (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $stats_table WHERE ad_id=%d AND event_type='impression'", $ad_id)) : 0;
                $clk = $has_stats ? (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $stats_table WHERE ad_id=%d AND event_type='click'", $ad_id)) : 0;
                $ctr = $imp > 0 ? round(($clk / $imp) * 100, 1) : 0;
                $start_date = get_post_meta($ad_id, '_imz_ad_start_date', true);

                // Nome do formato
                $format_display = '—';
                if ($ad_format && function_exists('imz_get_ad_formats')) {
                    $all_formats = imz_get_ad_formats();
                    if (isset($all_formats[$ad_format])) {
                        $format_display = $all_formats[$ad_format]['icon'] . ' ' . $all_formats[$ad_format]['label'];
                    }
                }
            ?>
            <tr>
                <td><?php echo $ad_id; ?></td>
                <td><a href="<?php echo $base_url . '&view=edit&ad_id=' . $ad_id; ?>" style="font-weight:700; text-decoration:none;"><?php the_title(); ?></a></td>
                <td style="font-size:12px;"><?php echo $format_display; ?></td>
                <td><span class="imz-badge imz-badge-<?php echo $status; ?>"><?php echo ucfirst($status); ?></span></td>
                <td style="font-size:12px;"><?php echo $start_date ? date('d/m', strtotime($start_date)) : '—'; ?> → <?php echo $end_date ? date('d/m', strtotime($end_date)) : '∞'; ?></td>
                <td><?php echo number_format($imp); ?></td>
                <td><?php echo number_format($clk); ?></td>
                <td><?php echo $ctr; ?>%</td>
                <td>
                    <?php
                    $action_url = $base_url . '&view=list';
                    echo '<a href="' . $base_url . '&view=edit&ad_id=' . $ad_id . '" class="button button-small" style="margin-right:4px;">Editar</a>';
                    if ($status === 'pendente') {
                        echo '<a href="' . wp_nonce_url($action_url . '&action=approve&ad_id=' . $ad_id, 'imz_ad_action') . '" class="button button-primary button-small">Aprovar</a> ';
                        echo '<a href="' . wp_nonce_url($action_url . '&action=reject&ad_id=' . $ad_id, 'imz_ad_action') . '" class="button button-small">Rejeitar</a>';
                    } elseif ($status === 'aguardando_pagamento') {
                        echo '<a href="' . wp_nonce_url($action_url . '&action=mark_paid&ad_id=' . $ad_id, 'imz_ad_action') . '" class="button button-primary button-small" onclick="return confirm(\'Confirmar que este anúncio foi pago (fora da API)?\');">Marcar como Pago</a>';
                    } elseif ($status === 'ativo') {
                        echo '<a href="' . wp_nonce_url($action_url . '&action=pause&ad_id=' . $ad_id, 'imz_ad_action') . '" class="button button-small">Pausar</a>';
                    } elseif ($status === 'pausado') {
                        echo '<a href="' . wp_nonce_url($action_url . '&action=approve&ad_id=' . $ad_id, 'imz_ad_action') . '" class="button button-small">Reativar</a>';
                    }
                    echo ' <a href="' . wp_nonce_url($action_url . '&action=delete_ad&ad_id=' . $ad_id, 'imz_ad_action') . '" class="button button-small" onclick="return confirm(\'Apagar?\');" style="color:#991b1b;">Apagar</a>';
                    ?>
                </td>
            </tr>
            <?php endwhile; wp_reset_postdata(); else : ?>
            <tr><td colspan="9" style="text-align:center; color:#9ca3af; padding:20px;">Nenhum anúncio encontrado.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
    <?php
}

// =============================================================================
// 4. SHORTCODE PARA EXIBIR ANÚNCIOS NO FRONTEND [imz_anuncios]
// =============================================================================

/**
 * Filtra IDs de anúncios pelo targeting geográfico vs geo do visitante.
 *
 * Fail-open: anúncio sem targeting é sempre elegível; se a geo do visitante
 * for desconhecida, todos os anúncios são elegíveis.
 *
 * @param int[] $ad_ids
 * @param array{country: string, region: string} $geo
 * @return int[]
 */
function imz_ads_filter_by_targeting(array $ad_ids, array $geo): array {
    $visitor_country = strtoupper(trim($geo['country'] ?? ''));
    $visitor_region  = trim($geo['region'] ?? '');

    return array_values(array_filter($ad_ids, function ($ad_id) use ($visitor_country, $visitor_region) {
        $target_countries = trim((string) get_post_meta($ad_id, '_imz_ad_target_countries', true));
        $target_regions   = trim((string) get_post_meta($ad_id, '_imz_ad_target_regions', true));

        // Sem targeting definido → sempre elegível
        if ($target_countries === '' && $target_regions === '') return true;

        // País definido no anúncio: exige correspondência (se conhecermos o país do visitante)
        if ($target_countries !== '' && $visitor_country !== '') {
            $countries = array_map('trim', explode(',', strtoupper($target_countries)));
            if (!in_array($visitor_country, $countries, true)) return false;
        }

        // Região definida: match flexível e insensível a acentos
        // ("Maputo" ↔ "Maputo City", "Zambezia" ↔ "Zambézia Province")
        if ($target_regions !== '' && $visitor_region !== '') {
            $visitor_norm = remove_accents($visitor_region);
            $regions = array_filter(array_map('trim', explode(',', $target_regions)));
            $matched = false;
            foreach ($regions as $target) {
                $target_norm = remove_accents($target);
                if (mb_stripos($visitor_norm, $target_norm) !== false || mb_stripos($target_norm, $visitor_norm) !== false) {
                    $matched = true;
                    break;
                }
            }
            if (!$matched) return false;
        }

        return true;
    }));
}

/**
 * Fator de adequação do formato ao dispositivo do visitante.
 *
 * Num telemóvel, formatos pensados para mobile (banner mobile, stories,
 * card nativo) ganham prioridade na rotação; o leaderboard de 728px perde.
 * No desktop é o inverso, mais suave. Nunca exclui — só pondera, por isso
 * um anúncio leaderboard ainda pode aparecer em mobile (adaptado pelo CSS).
 */
function imz_ads_format_device_factor(?string $format): float {
    $is_mobile = wp_is_mobile();
    $factors = $is_mobile
        ? ['mobile_banner' => 3.0, 'stories' => 2.0, 'native_card' => 2.0, 'rectangle' => 1.5, 'leaderboard' => 0.5]
        : ['leaderboard' => 1.5, 'rectangle' => 1.2, 'native_card' => 1.0, 'stories' => 0.8, 'mobile_banner' => 0.6];
    return $factors[$format] ?? 1.0;
}

/**
 * Amostragem ponderada sem reposição: anúncios com preço maior aparecem mais vezes,
 * ajustado pela adequação do formato ao dispositivo (mobile vs desktop).
 * Peso = max(1, _imz_ad_price) × fator de dispositivo. Devolve até $slots IDs.
 *
 * @param int[] $ad_ids
 * @return int[]
 */
function imz_ads_weighted_pick(array $ad_ids, int $slots): array {
    if (empty($ad_ids) || $slots <= 0) return [];

    $weights = [];
    foreach ($ad_ids as $id) {
        $base   = max(1.0, (float) get_post_meta($id, '_imz_ad_price', true));
        $factor = imz_ads_format_device_factor(get_post_meta($id, '_imz_ad_format', true) ?: null);
        $weights[$id] = $base * $factor;
    }

    $picked = [];
    while (count($picked) < $slots && !empty($weights)) {
        $total = array_sum($weights);
        $roll = (mt_rand() / mt_getrandmax()) * $total;
        $running = 0.0;
        foreach ($weights as $id => $weight) {
            $running += $weight;
            if ($roll <= $running) {
                $picked[] = $id;
                unset($weights[$id]);
                break;
            }
        }
    }
    return $picked;
}

add_shortcode('imz_anuncios', 'imz_render_ads_shortcode');
function imz_render_ads_shortcode($atts) {
    $atts = shortcode_atts([
        'tipo'  => 'banner',
        'max'   => 3,
        'layout' => 'horizontal',
        'incluir_musicas' => 'sim',
        'excluir_musica' => 0,
    ], $atts);

    $max = absint($atts['max']);
    $excluir_musica_id = absint($atts['excluir_musica']);
    $items_html = [];

    // =========================================================================
    // 1. ANÚNCIOS NORMAIS (CPT imz_anuncio)
    // Seleção em 3 passos: candidatos elegíveis → filtro de targeting geográfico
    // → rotação ponderada por preço (substitui o antigo orderby=rand).
    // =========================================================================
    $args = [
        'post_type'      => 'imz_anuncio',
        'posts_per_page' => 50,
        'post_status'    => 'publish',
        'fields'         => 'ids',
        'no_found_rows'  => true,
        'meta_query'     => [
            ['key' => '_imz_ad_status', 'value' => 'ativo'],
            [
                'relation' => 'OR',
                ['key' => '_imz_ad_end_date', 'value' => current_time('Y-m-d'), 'compare' => '>=', 'type' => 'DATE'],
                ['key' => '_imz_ad_end_date', 'value' => '', 'compare' => '='],
            ],
        ],
    ];

    if ($atts['tipo'] !== 'todos') {
        $args['meta_query'][] = ['key' => '_imz_ad_type', 'value' => sanitize_key($atts['tipo'])];
    }

    $candidate_ids = (new WP_Query($args))->posts;
    $visitor_geo   = function_exists('imz_ads_get_visitor_geo') ? imz_ads_get_visitor_geo() : ['country' => '', 'region' => ''];
    $eligible_ids  = imz_ads_filter_by_targeting($candidate_ids, $visitor_geo);
    $picked_ids    = imz_ads_weighted_pick($eligible_ids, $max);

    $ads = new WP_Query([
        'post_type'      => 'imz_anuncio',
        'post_status'    => 'publish',
        'posts_per_page' => $max,
        'post__in'       => !empty($picked_ids) ? $picked_ids : [0],
        'orderby'        => 'post__in',
        'no_found_rows'  => true,
    ]);
    if ($ads->have_posts()) {
        while ($ads->have_posts()) {
            $ads->the_post();
            $ad_id = get_the_ID();
            $image_url = get_post_meta($ad_id, '_imz_ad_image_url', true);
            $link_url = get_post_meta($ad_id, '_imz_ad_link', true);
            $ad_text = get_post_meta($ad_id, '_imz_ad_text', true);
            $ad_type = get_post_meta($ad_id, '_imz_ad_type', true) ?: 'banner';
            $ad_label = get_post_meta($ad_id, '_imz_ad_label', true) ?: 'Anúncio';
            
            ob_start();
            $ad_format = get_post_meta($ad_id, '_imz_ad_format', true);
            ?>
            <div class="imz-ad-item imz-ad-type-<?php echo esc_attr($ad_type); ?>" 
                 data-ad-id="<?php echo $ad_id; ?>"<?php if ($ad_format) echo ' data-format="' . esc_attr($ad_format) . '"'; ?>>
                <span class="imz-ad-badge"><?php echo esc_html($ad_label); ?></span>
                <?php if ($link_url) : ?>
                    <a href="<?php echo esc_url($link_url); ?>" target="_blank" rel="noopener noreferrer nofollow" class="imz-ad-link" data-ad-id="<?php echo $ad_id; ?>">
                <?php endif; ?>
                
                <?php if ($image_url) : ?>
                    <img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr(get_the_title()); ?>" class="imz-ad-image" loading="lazy">
                <?php endif; ?>
                
                <?php if ($ad_text) : ?>
                    <div class="imz-ad-text-content">
                        <p class="imz-ad-title"><?php the_title(); ?></p>
                        <p class="imz-ad-description"><?php echo esc_html($ad_text); ?></p>
                    </div>
                <?php endif; ?>
                
                <?php if ($link_url) : ?>
                    </a>
                <?php endif; ?>
            </div>
            <?php
            $items_html[] = ob_get_clean();
        }
        wp_reset_postdata();
    }

    // =========================================================================
    // 2. MÚSICAS IMPULSIONADAS (como "Música Destacada")
    // =========================================================================
    if ($atts['incluir_musicas'] === 'sim') {
        // Buscar impulsionamentos aprovados que ainda não expiraram
        $current_post_id = get_the_ID();
        
        $boosted_query = new WP_Query([
            'post_type'      => 'impulsionamento',
            'post_status'    => 'publish',
            'posts_per_page' => 20,
            'orderby'        => 'rand',
            'meta_query'     => [
                'relation' => 'AND',
                ['key' => 'status', 'value' => 'aprovado'],
                [
                    'relation' => 'OR',
                    // Boost com data de fim definida e ainda não expirado
                    [
                        'key' => '_boost_data_fim',
                        'value' => current_time('Y-m-d H:i:s'),
                        'compare' => '>=',
                        'type' => 'DATETIME',
                    ],
                    // Boost sem data de fim (boosts antigos sem duração)
                    [
                        'key' => '_boost_data_fim',
                        'value' => '',
                        'compare' => '=',
                    ],
                    [
                        'key' => '_boost_data_fim',
                        'compare' => 'NOT EXISTS',
                    ],
                ],
            ],
        ]);

        if ($boosted_query->have_posts()) {
            $shown_music_ids = [];
            $music_slots = max(1, $max - count($items_html)); // Preencher slots restantes

            while ($boosted_query->have_posts() && count($shown_music_ids) < $music_slots) {
                $boosted_query->the_post();
                $boost_post_id = get_the_ID();
                $boost_placement = is_page('processar-download') ? 'downloads' : 'sponsored_posts';
                if (function_exists('imz_boost_is_active') && !imz_boost_is_active($boost_post_id, $boost_placement)) continue;
                $music_id = get_post_meta($boost_post_id, 'post_id_original', true);
                
                // Evitar duplicados e a música actual
                if (empty($music_id) || in_array($music_id, $shown_music_ids) || $music_id == $current_post_id || $music_id == $excluir_musica_id) continue;
                
                $music_post = get_post($music_id);
                if (!$music_post || $music_post->post_status !== 'publish') continue;
                
                $shown_music_ids[] = $music_id;
                
                $boost_post_id = get_the_ID(); // ID do post de impulsionamento
                $music_link = get_permalink($music_id);
                $thumbnail = get_the_post_thumbnail_url($music_id, 'large');
                $boost_valor = (int) get_post_meta($boost_post_id, 'valor', true);
                $boost_format = get_post_meta($boost_post_id, '_boost_format', true) ?: '';
                
                // Obter o artista (do CPT vinculado ou author)
                $artist_name = '';
                $artista_cpt_id = get_post_meta($music_id, '_imz_artista_id', true);
                if ($artista_cpt_id) {
                    $artist_name = get_post_field('post_title', $artista_cpt_id);
                }
                if (!$artist_name) {
                    $artist_name = get_the_author_meta('display_name', $music_post->post_author);
                }

                // Categorias/género
                $categories = wp_list_pluck(get_the_category($music_id), 'name');
                $genre_text = !empty($categories) ? implode(', ', $categories) : '';
                
                // Título limpo
                remove_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);
                $music_title = get_the_title($music_id);
                add_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);

                // Contagem de downloads
                $dl_count = (int) get_post_meta($music_id, '_imz_download_count', true);
                $dl_text = $dl_count > 0 ? number_format($dl_count) . ' downloads' : '';

                ob_start();
                ?>
                <div class="imz-ad-item imz-ad-type-musica" data-ad-id="boost-<?php echo $boost_post_id; ?>" data-boost-id="<?php echo $boost_post_id; ?>"<?php if ($boost_format) echo ' data-format="' . esc_attr($boost_format) . '"'; ?>>
                    <a href="<?php echo esc_url($music_link); ?>" class="imz-ad-link imz-ad-music-link">
                        <div class="imz-ad-music-card">
                            <?php if ($thumbnail) : ?>
                                <img src="<?php echo esc_url($thumbnail); ?>" alt="<?php echo esc_attr($music_title); ?>" class="imz-ad-music-cover" loading="lazy">
                            <?php else : ?>
                                <div class="imz-ad-music-cover-placeholder">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="28" height="28"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
                                </div>
                            <?php endif; ?>
                            <div class="imz-ad-music-info">
                                <span class="imz-ad-badge-musica">🔥 Música Destacada</span>
                                <p class="imz-ad-music-title"><?php echo esc_html($music_title); ?></p>
                                <p class="imz-ad-music-artist"><?php echo esc_html($artist_name); ?></p>
                                <?php if ($genre_text || $dl_text): ?>
                                <div class="imz-ad-music-meta">
                                    <?php if ($genre_text): ?>
                                    <span class="imz-ad-music-genre">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="12" height="12" style="flex-shrink:0;"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
                                        <?php echo esc_html($genre_text); ?>
                                    </span>
                                    <?php endif; ?>
                                    <?php if ($dl_text): ?>
                                    <span class="imz-ad-music-downloads">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="12" height="12" style="flex-shrink:0;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                                        <?php echo esc_html($dl_text); ?>
                                    </span>
                                    <?php endif; ?>
                                </div>
                                <?php endif; ?>
                            </div>
                            <div class="imz-ad-music-play">
                                <svg viewBox="0 0 24 24" fill="currentColor" width="20" height="20"><path d="M8 5v14l11-7z"/></svg>
                            </div>
                        </div>
                    </a>
                </div>
                <?php
                $items_html[] = ob_get_clean();
            }
            wp_reset_postdata();
        }
    }

    if (empty($items_html)) return '';

    // Baralhar para misturar anúncios e músicas
    shuffle($items_html);

    $layout_class = 'imz-ads-layout-' . sanitize_html_class($atts['layout']);
    
    ob_start();
    ?>
    <style>
    .imz-ad-item a, .imz-ad-item a:link, .imz-ad-item a:visited, .imz-ad-item a:hover, .imz-ad-item a:active, .imz-ad-item a:focus,
    .imz-ad-link, .imz-ad-link:link, .imz-ad-link:visited, .imz-ad-link:hover, .imz-ad-link:active,
    .imz-ad-music-link, .imz-ad-music-link:link, .imz-ad-music-link:visited, .imz-ad-music-link:hover, .imz-ad-music-link:active {
        text-decoration: none !important;
        border-bottom: none !important;
        box-shadow: none !important;
        outline: none !important;
        color: inherit !important;
        -webkit-tap-highlight-color: transparent;
    }
    .imz-ad-title, .imz-ad-description, .imz-ad-music-title, .imz-ad-music-artist {
        text-decoration: none !important;
        border-bottom: none !important;
    }
    /* Badges Material 3 — usam as variáveis --m3-* (cor dinâmica da imagem),
       com !important apenas para vencer estilos do tema dentro dos posts */
    .imz-ad-badge {
        background: rgba(0, 0, 0, 0.55) !important;
        color: var(--m3-accent, #d1a954) !important;
        border: 1px solid var(--m3-accent-border, rgba(255, 255, 255, 0.18)) !important;
    }
    .imz-ad-badge-musica {
        background: var(--m3-accent-soft, rgba(245, 158, 11, 0.14)) !important;
        color: var(--m3-accent, #f59e0b) !important;
        border: 1px solid var(--m3-accent-border, rgba(245, 158, 11, 0.30)) !important;
    }
    /* Meta info: pills de categoria e downloads */
    .imz-ad-music-meta {
        display: flex;
        align-items: center;
        gap: 6px;
        margin: 8px 0 0;
        flex-wrap: wrap;
    }
    .imz-ad-music-genre {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        background: var(--m3-accent-soft, rgba(245, 158, 11, 0.15));
        color: var(--m3-accent, #fbbf24);
        padding: 3px 10px;
        border-radius: 20px;
        font-size: 10px;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.3px;
        border: 1px solid var(--m3-accent-border, rgba(245, 158, 11, 0.25));
    }
    .imz-ad-music-downloads {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        background: rgba(255, 255, 255, 0.08);
        color: #ccc;
        padding: 3px 10px;
        border-radius: 20px;
        font-size: 10px;
        font-weight: 600;
        border: 1px solid rgba(255, 255, 255, 0.1);
    }
    </style>
    <div class="imz-ads-container <?php echo $layout_class; ?>">
        <?php echo implode('', $items_html); ?>
    </div>
    <?php
    return ob_get_clean();
}

// Auto-inserir anúncios no conteúdo dos posts (entre conteúdo e botão impulsionar)
add_filter('the_content', 'imz_auto_insert_ads_in_content', 3);
function imz_auto_insert_ads_in_content($content) {
    if (!is_singular('post') || !in_the_loop() || !is_main_query()) return $content;
    
    $show_ads = get_option('imz_enable_frontend_ads', '1');
    if ($show_ads !== '1') return $content;
    
    $ad_html = do_shortcode('[imz_anuncios tipo="todos" max="2" layout="horizontal"]');
    if (!empty(trim($ad_html))) {
        $content = $content . $ad_html;
    }
    return $content;
}

// =============================================================================
// 4a-1. PESQUISA DE MÚSICAS NO ADMIN (para o seletor do Impulsionar)
// =============================================================================

/**
 * AJAX: pesquisa músicas por título e devolve dados ricos (capa, artista,
 * plays, downloads, data) para o seletor com pesquisa do gestor de anúncios.
 * Sem termo de pesquisa devolve as 10 mais recentes.
 */
add_action('wp_ajax_imz_admin_search_music', 'imz_ajax_admin_search_music');
function imz_ajax_admin_search_music() {
    check_ajax_referer('imz_admin_search_music', 'nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Sem permissão.']);
    }

    $q = sanitize_text_field($_POST['q'] ?? '');
    $args = [
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => $q !== '' ? 20 : 10,
        'no_found_rows'  => true,
    ];
    if ($q !== '') {
        $args['s'] = $q;
    } else {
        $args['orderby'] = 'date';
        $args['order']   = 'DESC';
    }

    $query = new WP_Query($args);
    $ids = wp_list_pluck($query->posts, 'ID');

    // Stats em lote (2 queries, independentemente do nº de resultados)
    global $wpdb;
    $downloads_map = [];
    $plays_map = [];
    if (!empty($ids)) {
        $placeholders = implode(',', array_fill(0, count($ids), '%d'));
        $analytics_table = $wpdb->prefix . 'imz_analytics';
        if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $analytics_table)) === $analytics_table) {
            foreach ($wpdb->get_results($wpdb->prepare("SELECT music_id, COUNT(*) AS total FROM $analytics_table WHERE music_id IN ($placeholders) GROUP BY music_id", $ids)) as $row) {
                $downloads_map[(int) $row->music_id] = (int) $row->total;
            }
        }
        $plays_table = $wpdb->prefix . 'imz_plays';
        if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $plays_table)) === $plays_table) {
            foreach ($wpdb->get_results($wpdb->prepare("SELECT music_id, COUNT(*) AS total FROM $plays_table WHERE music_id IN ($placeholders) GROUP BY music_id", $ids)) as $row) {
                $plays_map[(int) $row->music_id] = (int) $row->total;
            }
        }
    }

    // O texto segue em JSON e é inserido no DOM via textContent (sem parse de HTML),
    // por isso as entidades do WordPress (ex: &#8211; do travessão) têm de ser
    // descodificadas aqui, senão aparecem cruas na interface.
    $decode = function ($text) {
        return html_entity_decode(wp_strip_all_tags((string) $text), ENT_QUOTES | ENT_HTML5, 'UTF-8');
    };

    remove_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);
    $results = [];
    foreach ($query->posts as $p) {
        $mid = $p->ID;
        $artist = '';
        $artista_cpt_id = get_post_meta($mid, '_imz_artista_id', true);
        if ($artista_cpt_id) {
            $artist = get_post_field('post_title', $artista_cpt_id);
        }
        if (!$artist) {
            $artist = get_the_author_meta('display_name', $p->post_author);
        }
        $results[] = [
            'id'        => $mid,
            'title'     => $decode(get_the_title($mid)),
            'artist'    => $decode($artist),
            'thumb'     => get_the_post_thumbnail_url($mid, 'thumbnail') ?: '',
            'thumb_md'  => get_the_post_thumbnail_url($mid, 'medium') ?: '',
            'cats'      => $decode(implode(', ', wp_list_pluck(get_the_category($mid), 'name'))),
            'plays'     => $plays_map[$mid] ?? 0,
            'downloads' => $downloads_map[$mid] ?? 0,
            'date'      => get_the_date('d/m/Y', $mid),
            'url'       => get_permalink($mid),
        ];
    }
    add_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);

    wp_send_json_success(['results' => $results]);
}

// =============================================================================
// 4a-2. PAGAMENTO M-PESA DE ANÚNCIOS
// =============================================================================

/**
 * Passo de pagamento mostrado após a submissão (ou no painel do anunciante).
 */
function imz_render_ad_payment_step(int $ad_id): string {
    $title    = get_the_title($ad_id);
    $price    = (float) get_post_meta($ad_id, '_imz_ad_price', true);
    $duration = (int) get_post_meta($ad_id, '_imz_ad_duration', true);

    ob_start();
    ?>
    <div class="imz-ad-payment-step" id="imz-ad-payment-step" data-ad-id="<?php echo esc_attr($ad_id); ?>">
        <div class="imz-message imz-message-success"><strong>Anúncio criado!</strong> Falta só o pagamento para seguir para aprovação.</div>
        <div class="imz-ad-payment-summary">
            <p><strong>Anúncio:</strong> <?php echo esc_html($title); ?></p>
            <p><strong>Duração:</strong> <?php echo esc_html($duration); ?> dias</p>
            <p class="imz-ad-payment-total"><strong>Total a pagar:</strong> <span><?php echo esc_html(number_format($price)); ?> MT</span></p>
        </div>
        <div class="imz-form-group">
            <label for="imz-ad-pay-phone">Número M-Pesa (9 dígitos):</label>
            <input type="tel" id="imz-ad-pay-phone" pattern="[0-9]{9}" maxlength="9" placeholder="84xxxxxxx" inputmode="numeric">
        </div>
        <button type="button" class="imz-botao-principal imz-mt0" id="imz-ad-pay-btn">Pagar <?php echo esc_html(number_format($price)); ?> MT com M-Pesa</button>
        <div id="imz-ad-pay-messages" class="imz-form-messages" aria-live="polite"></div>
    </div>
    <?php
    return ob_get_clean();
}

/**
 * Marca um anúncio como pago e envia-o para aprovação do admin.
 * Idempotente: só atua se o estado ainda for 'aguardando_pagamento'
 * (cobre a corrida entre a resposta síncrona da API e o callback REST).
 */
function imz_ad_mark_paid(int $ad_id, string $msisdn, $amount, string $ref, string $method): bool {
    if (!$ad_id || get_post_type($ad_id) !== 'imz_anuncio') return false;
    if (get_post_meta($ad_id, '_imz_ad_status', true) !== 'aguardando_pagamento') return false;

    update_post_meta($ad_id, '_imz_ad_status', 'pendente');
    update_post_meta($ad_id, '_imz_ad_paid_at', current_time('mysql'));
    update_post_meta($ad_id, '_imz_ad_payment_ref', sanitize_text_field($ref));
    update_post_meta($ad_id, '_imz_ad_payment_msisdn', sanitize_text_field($msisdn));
    update_post_meta($ad_id, '_imz_ad_payment_amount', (float) $amount);
    update_post_meta($ad_id, '_imz_ad_payment_method', sanitize_text_field($method));

    delete_transient('imz_pending_counts');
    return true;
}

/**
 * AJAX: inicia o pagamento C2B M-Pesa de um anúncio (apenas utilizadores logados).
 * O montante é SEMPRE lido do servidor (_imz_ad_price), nunca do POST.
 */
add_action('wp_ajax_imz_ad_initiate_payment', 'imz_ajax_ad_initiate_payment');
function imz_ajax_ad_initiate_payment() {
    check_ajax_referer('imz_ad_payment_nonce', 'nonce');

    if (!get_option('imz_enable_mpesa_api')) {
        wp_send_json_error(['message' => 'O pagamento automático não está disponível de momento.']);
    }

    $ad_id = absint($_POST['ad_id'] ?? 0);
    $phone = sanitize_text_field($_POST['phone'] ?? '');

    if (!$ad_id || get_post_type($ad_id) !== 'imz_anuncio') {
        wp_send_json_error(['message' => 'Anúncio inválido.']);
    }
    if ((int) get_post_field('post_author', $ad_id) !== get_current_user_id()) {
        wp_send_json_error(['message' => 'Não tem permissão para pagar este anúncio.']);
    }
    if (get_post_meta($ad_id, '_imz_ad_status', true) !== 'aguardando_pagamento') {
        wp_send_json_error(['message' => 'Este anúncio não está a aguardar pagamento.']);
    }
    if (strlen($phone) !== 9 || !ctype_digit($phone)) {
        wp_send_json_error(['message' => 'Número inválido. Use 9 dígitos (ex: 84xxxxxxx).']);
    }

    $amount = (int) round((float) get_post_meta($ad_id, '_imz_ad_price', true));
    if ($amount <= 0) {
        wp_send_json_error(['message' => 'Preço do anúncio inválido. Contacte o suporte.']);
    }

    $third_party_ref = 'AD' . $ad_id . '_' . time();
    $transaction_ref = 'IMZ' . time() . rand(10, 99);

    $mpesa = new IMZ_Mpesa_API();
    $result = $mpesa->initiate_c2b_payment($amount, '258' . $phone, $transaction_ref, $third_party_ref);

    if (is_null($result) || !is_array($result)) {
        wp_send_json_error(['message' => 'Falha na M-Pesa: resposta inválida do servidor. Tente novamente.']);
    }
    if (isset($result['error'])) {
        wp_send_json_error(['message' => 'Falha na M-Pesa: ' . $result['error']]);
    }

    if (isset($result['output_ResponseCode']) && $result['output_ResponseCode'] === 'INS-0') {
        imz_ad_mark_paid($ad_id, '258' . $phone, $amount, $third_party_ref, 'M-Pesa API');
        wp_send_json_success([
            'message' => 'Pagamento confirmado! O seu anúncio seguiu para aprovação e será ativado em breve.',
            'paid'    => true,
        ]);
    }

    $error_message = $result['output_ResponseDesc'] ?? 'Pagamento não concluído. Verifique o saldo e tente novamente.';
    wp_send_json_error(['message' => 'Falha na M-Pesa: ' . $error_message]);
}

// =============================================================================
// 4b. ASSETS DO ADMIN (Chart.js para a tab Relatórios)
// =============================================================================

add_action('admin_enqueue_scripts', 'imz_ads_admin_assets');
function imz_ads_admin_assets($hook_suffix) {
    if (strpos((string) $hook_suffix, 'imz_ads_manager') === false) return;
    wp_enqueue_script('chartjs', 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js', [], '4.4.1', true);
}

// =============================================================================
// 5. TRACKING DE IMPRESSÕES E CLIQUES (AJAX)
// =============================================================================

add_action('wp_ajax_imz_track_ad_event', 'imz_track_ad_event');
add_action('wp_ajax_nopriv_imz_track_ad_event', 'imz_track_ad_event');
function imz_track_ad_event() {
    $raw_id = sanitize_text_field($_POST['ad_id'] ?? '');
    $event_type = sanitize_key($_POST['event_type'] ?? 'impression');
    
    // Suportar IDs de boost (formato "boost-123") e anúncios normais
    $is_boost = strpos($raw_id, 'boost-') === 0;
    $ad_id = $is_boost ? absint(str_replace('boost-', '', $raw_id)) : absint($raw_id);
    
    if ($ad_id === 0 || !in_array($event_type, ['impression', 'click'])) {
        wp_send_json_error();
    }

    global $wpdb;
    $table = $wpdb->prefix . 'imz_ad_stats';
    $ip = imz_get_user_ip();
    
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) !== $table) {
        imz_install_ads_table();
    }

    // Verificar se a coluna source_type existe, se não, adicionar
    $col_exists = $wpdb->get_var("SHOW COLUMNS FROM $table LIKE 'source_type'");
    if (!$col_exists) {
        $wpdb->query("ALTER TABLE $table ADD COLUMN source_type varchar(20) DEFAULT 'ad' NOT NULL AFTER event_type");
    }

    // Rate limit: máx 1 impressão por IP por item por hora
    if ($event_type === 'impression') {
        $recent = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table WHERE ad_id = %d AND user_ip = %s AND event_type = 'impression' AND source_type = %s AND event_date > DATE_SUB(NOW(), INTERVAL 1 HOUR)",
            $ad_id, $ip, $is_boost ? 'boost' : 'ad'
        ));
        if ($recent > 0) {
            wp_send_json_success(['tracked' => false]);
            return;
        }
    }

    // Detectar dispositivo a partir do User-Agent
    $ua = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '';
    $device_type = 'desktop';
    $ua_lower = strtolower($ua);
    if (preg_match('/(android|iphone|ipod|mobile|opera mini|iemobile|blackberry)/i', $ua_lower)) {
        $device_type = 'mobile';
    } elseif (preg_match('/(ipad|tablet|kindle|silk|playbook)/i', $ua_lower)) {
        $device_type = 'tablet';
    }

    // Geolocalização — helper partilhado com cache por IP (ads-geo.php)
    $geo = function_exists('imz_ads_get_visitor_geo') ? imz_ads_get_visitor_geo($ip) : ['country' => '', 'region' => ''];
    $country = $geo['country'];
    $region  = $geo['region'];

    $wpdb->insert($table, [
        'ad_id'       => $ad_id,
        'event_type'  => $event_type,
        'source_type' => $is_boost ? 'boost' : 'ad',
        'user_ip'     => $ip,
        'user_agent'  => substr($ua, 0, 255),
        'device_type' => $device_type,
        'country'     => $country,
        'region'      => $region,
    ], ['%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s']);

    wp_send_json_success(['tracked' => true]);
}

// =============================================================================
// 6. FORMULÁRIO DE SUBMISSÃO DE ANÚNCIO (FRONTEND - ARTISTA/FÃ)
// =============================================================================

add_shortcode('imz_submeter_anuncio', 'imz_render_submit_ad_form');
function imz_render_submit_ad_form() {
    $account_logged_in = defined('RMBZ_ARTISTS_EMBEDDED')
        ? (function_exists('imz_rmbz_is_artist_logged_in') && imz_rmbz_is_artist_logged_in())
        : is_user_logged_in();
    if (!$account_logged_in) {
        $login_url = function_exists('imz_rmbz_account_url') ? imz_rmbz_account_url() : wp_login_url(get_permalink());
        return '<div class="imz-message imz-message-warning">Entra na tua <a href="' . esc_url($login_url) . '">conta 1MZ For Artists</a> para submeter um anúncio.</div>';
    }

    $user_id = function_exists('imz_get_current_artist_user_id') ? imz_get_current_artist_user_id() : get_current_user_id();
    $ad_prices = get_option('imz_ad_prices', [
        'banner'   => 200,
        'destaque' => 500,
        'sidebar'  => 150,
    ]);

    // Processar submissão
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['imz_submit_ad'])) {
        if (!wp_verify_nonce($_POST['imz_ad_nonce_field'], 'imz_submit_ad_action')) {
            wp_die('Verificação de segurança falhou.');
        }

        $title = sanitize_text_field($_POST['ad_title'] ?? '');
        $text = sanitize_textarea_field($_POST['ad_text'] ?? '');
        $link = esc_url_raw($_POST['ad_link'] ?? '');
        $type = sanitize_key($_POST['ad_type'] ?? 'banner');
        $duration = absint($_POST['ad_duration'] ?? 7);
        $image_id = absint($_POST['ad_image_attachment_id'] ?? 0);

        if (empty($title)) {
            return '<div class="imz-message imz-message-error">O título do anúncio é obrigatório.</div>' . imz_render_ad_form_content($ad_prices);
        }

        $image_url = $image_id ? wp_get_attachment_url($image_id) : '';
        $start_date = current_time('Y-m-d');
        $end_date = date('Y-m-d', strtotime("+{$duration} days"));
        $price = ($ad_prices[$type] ?? 200) * ceil($duration / 7);

        $ad_post_id = wp_insert_post([
            'post_type'   => 'imz_anuncio',
            'post_title'  => $title,
            'post_status' => 'publish',
            'post_author' => $user_id,
            'meta_input'  => [
                '_imz_ad_status'     => 'pendente',
                '_imz_ad_type'       => $type,
                '_imz_ad_text'       => $text,
                '_imz_ad_link'       => $link,
                '_imz_ad_image_url'  => $image_url,
                '_imz_ad_image_id'   => $image_id,
                '_imz_ad_start_date' => $start_date,
                '_imz_ad_end_date'   => $end_date,
                '_imz_ad_duration'   => $duration,
                '_imz_ad_price'      => $price,
                '_imz_ad_label'      => 'Anúncio',
                '_imz_ad_target_countries' => sanitize_text_field($_POST['ad_target_countries'] ?? ''),
                '_imz_ad_target_regions'   => sanitize_text_field($_POST['ad_target_regions'] ?? ''),
            ],
        ]);

        if ($ad_post_id) {
            // Com a API M-Pesa ativa, o anúncio só segue para aprovação depois de pago
            if (get_option('imz_enable_mpesa_api')) {
                update_post_meta($ad_post_id, '_imz_ad_status', 'aguardando_pagamento');
                return imz_render_ad_payment_step($ad_post_id);
            }
            return '<div class="imz-message imz-message-success"><strong>Anúncio submetido com sucesso!</strong><br>O seu anúncio "' . esc_html($title) . '" foi enviado para aprovação. Receberá uma notificação quando for aprovado. Valor: <strong>' . number_format($price) . ' MT</strong></div>';
        }
    }

    return imz_render_ad_form_content($ad_prices);
}

function imz_render_ad_form_content($ad_prices) {
    ob_start();
    ?>
    <style>
    .imz-ad-submission-page { max-width: 720px; margin: 0 auto; }
    .imz-ad-submission-page h2 { font-size: 26px; font-weight: 700; margin: 0 0 6px 0; }
    .imz-ad-submission-page .imz-form-description { margin-bottom: 28px; }
    .imz-ad-pricing-cards {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 14px;
        margin-bottom: 32px;
    }
    .imz-ad-pricing-card {
        background: var(--imz-color-background-soft, #1a1a1a);
        border: 2px solid var(--imz-border-color, #2a2a2a);
        border-radius: 14px;
        padding: 22px 16px;
        text-align: center;
        cursor: pointer;
        transition: border-color 0.2s, box-shadow 0.2s, transform 0.15s;
        position: relative;
    }
    .imz-ad-pricing-card:hover {
        border-color: #10b981;
        transform: translateY(-2px);
    }
    .imz-ad-pricing-card.active {
        border-color: #10b981;
        box-shadow: 0 0 0 2px rgba(16,185,129,0.25), 0 8px 24px rgba(16,185,129,0.10);
    }
    .imz-ad-pricing-card.active::after {
        content: '✓';
        position: absolute;
        top: 10px;
        right: 12px;
        width: 22px;
        height: 22px;
        background: #10b981;
        color: #fff;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: 700;
    }
    .imz-ad-pricing-icon {
        font-size: 32px;
        display: block;
        margin-bottom: 10px;
        line-height: 1;
    }
    .imz-ad-pricing-card h4 {
        margin: 0 0 8px 0;
        font-size: 17px;
        font-weight: 700;
        color: var(--imz-color-text, #fff);
    }
    .imz-ad-pricing-price {
        font-size: 24px;
        font-weight: 800;
        color: #10b981;
        margin: 0 0 10px 0;
        line-height: 1.2;
    }
    .imz-ad-pricing-price span {
        font-size: 12px;
        font-weight: 400;
        color: var(--imz-color-text-light, #888);
        display: block;
        margin-top: 2px;
    }
    .imz-ad-pricing-desc {
        font-size: 12px;
        color: var(--imz-color-text-light, #888);
        margin: 0;
        line-height: 1.45;
    }
    .imz-ad-form .imz-form-group {
        margin-bottom: 20px;
    }
    .imz-ad-form .imz-form-group label {
        display: block;
        font-size: 14px;
        font-weight: 600;
        margin-bottom: 6px;
        color: var(--imz-color-text, #fff);
    }
    .imz-ad-form input[type="text"],
    .imz-ad-form input[type="url"],
    .imz-ad-form textarea,
    .imz-ad-form select {
        width: 100%;
        padding: 10px 14px;
        border-radius: 8px;
        border: 1px solid var(--imz-border-color, #2a2a2a);
        background: var(--imz-color-background, #141414);
        color: var(--imz-color-text, #fff);
        font-size: 14px;
        box-sizing: border-box;
        transition: border-color 0.2s;
    }
    .imz-ad-form input:focus,
    .imz-ad-form textarea:focus,
    .imz-ad-form select:focus {
        outline: none;
        border-color: #10b981;
        box-shadow: 0 0 0 2px rgba(16,185,129,0.15);
    }
    .imz-ad-price-preview {
        background: linear-gradient(135deg, rgba(16,185,129,0.08), rgba(16,185,129,0.03));
        border: 1px solid rgba(16,185,129,0.2);
        border-radius: 10px;
        padding: 16px 20px;
        margin-bottom: 22px;
        text-align: center;
    }
    .imz-ad-price-preview p {
        margin: 0;
        font-size: 15px;
        color: var(--imz-color-text-light, #888);
    }
    .imz-ad-price-preview strong {
        color: #10b981;
        font-size: 22px;
        font-weight: 800;
    }
    @media (max-width: 600px) {
        .imz-ad-pricing-cards { grid-template-columns: 1fr; }
    }
    </style>

    <div class="imz-form-container imz-ad-submission-page">
        <h2>Criar Anúncio</h2>
        <p class="imz-form-description">Promova a sua música, evento ou marca para milhares de fãs na plataforma 1MusicMoz.</p>

        <div class="imz-ad-pricing-cards">
            <?php
            $type_labels = [
                'destaque' => ['nome' => 'Destaque', 'desc' => 'Aparece no meio do conteúdo das músicas. Máxima visibilidade.', 'icon' => '⭐'],
                'banner'   => ['nome' => 'Banner', 'desc' => 'Banner visual no topo ou entre secções do site.', 'icon' => '🖼️'],
                'sidebar'  => ['nome' => 'Lateral', 'desc' => 'Aparece na barra lateral das páginas.', 'icon' => '📌'],
            ];
            $first = true;
            foreach ($type_labels as $key => $info) :
                $price = $ad_prices[$key] ?? 200;
            ?>
            <div class="imz-ad-pricing-card<?php echo $first ? ' active' : ''; ?>" data-type="<?php echo $key; ?>">
                <span class="imz-ad-pricing-icon"><?php echo $info['icon']; ?></span>
                <h4><?php echo $info['nome']; ?></h4>
                <p class="imz-ad-pricing-price"><?php echo number_format($price); ?> MT<span>por semana</span></p>
                <p class="imz-ad-pricing-desc"><?php echo $info['desc']; ?></p>
            </div>
            <?php $first = false; endforeach; ?>
        </div>

        <form method="post" class="imz-boost-form imz-ad-form" enctype="multipart/form-data">
            <?php wp_nonce_field('imz_submit_ad_action', 'imz_ad_nonce_field'); ?>

            <div class="imz-form-group">
                <label for="ad_type">Tipo de Anúncio:</label>
                <select name="ad_type" id="ad_type" required>
                    <option value="destaque">⭐ Destaque (no conteúdo)</option>
                    <option value="banner">🖼️ Banner</option>
                    <option value="sidebar">📌 Lateral</option>
                </select>
            </div>

            <div class="imz-form-group">
                <label for="ad_title">Título do Anúncio:</label>
                <input type="text" name="ad_title" id="ad_title" maxlength="80" required placeholder="Ex: Novo álbum disponível!">
            </div>

            <div class="imz-form-group">
                <label for="ad_text">Texto / Descrição (opcional):</label>
                <textarea name="ad_text" id="ad_text" rows="3" maxlength="200" placeholder="Uma breve descrição do seu anúncio..."></textarea>
            </div>

            <div class="imz-form-group">
                <label for="ad_link">Link de Destino (URL):</label>
                <input type="url" name="ad_link" id="ad_link" placeholder="https://exemplo.com/minha-musica">
            </div>

            <div class="imz-form-group">
                <label>Imagem do Anúncio (recomendado: 728x90 para banner, 600x300 para destaque):</label>
                <label for="ad_image_upload" class="imz-file-uploader">
                    <div class="imz-file-uploader-label">Clique para selecionar a imagem<span>JPG, PNG ou GIF, até 2MB</span></div>
                </label>
                <input type="file" id="ad_image_upload" accept=".jpg,.jpeg,.png,.gif">
                <div class="imz-progress-container"><div class="imz-progress-bar"></div><span class="imz-progress-text">0%</span></div>
                <p class="imz-file-notice"></p>
                <input type="hidden" name="ad_image_attachment_id" id="ad_image_attachment_id" value="">
            </div>

            <div class="imz-form-group">
                <label for="ad_duration">Duração (dias):</label>
                <select name="ad_duration" id="ad_duration">
                    <option value="7">7 dias (1 semana)</option>
                    <option value="14">14 dias (2 semanas)</option>
                    <option value="30">30 dias (1 mês)</option>
                </select>
            </div>

            <div class="imz-form-group">
                <?php if (function_exists('imz_render_geo_targeting_fields')) {
                    imz_render_geo_targeting_fields('', '');
                } ?>
            </div>

            <div class="imz-ad-price-preview">
                <p>Custo estimado: <strong id="imz-ad-estimated-price">—</strong></p>
            </div>

            <button type="submit" name="imz_submit_ad" class="imz-botao-principal">Submeter Anúncio para Aprovação</button>
        </form>
    </div>
    <?php
    return ob_get_clean();
}

// =============================================================================
// 7. CONFIGURAÇÕES DE ANÚNCIOS (Adicionadas à aba Geral)
// =============================================================================

add_action('admin_init', 'imz_register_ads_settings');
function imz_register_ads_settings() {
    // Adiciona uma secção na aba de integrações (ou criar nova aba)
    add_settings_section(
        'imz_ads_section',
        'Sistema de Anúncios',
        function() { echo '<p>Configure o sistema de anúncios do frontend.</p>'; },
        'imz_config_seccao_integracoes'
    );

    register_setting('imz_config_group_integracoes', 'imz_enable_frontend_ads');
    add_settings_field(
        'imz_enable_frontend_ads',
        'Ativar Anúncios no Frontend',
        function() {
            $val = get_option('imz_enable_frontend_ads', '1');
            echo '<input type="checkbox" name="imz_enable_frontend_ads" value="1" ' . checked($val, '1', false) . '> Mostrar anúncios automaticamente nas páginas de músicas';
        },
        'imz_config_seccao_integracoes',
        'imz_ads_section'
    );
}

// =============================================================================
// 8. ENQUEUE DO JS DE TRACKING
// =============================================================================

add_action('wp_footer', 'imz_ads_tracking_script');
function imz_ads_tracking_script() {
    if (is_admin()) return;
    ?>
    <script>
    (function() {
        var ads = document.querySelectorAll('.imz-ad-item[data-ad-id]');
        if (!ads.length) return;

        // Track impressions via IntersectionObserver
        var tracked = {};
        var observer = new IntersectionObserver(function(entries) {
            entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                    var adId = entry.target.getAttribute('data-ad-id');
                    if (tracked[adId]) return;
                    tracked[adId] = true;
                    imzTrackAd(adId, 'impression');
                }
            });
        }, { threshold: 0.5 });

        ads.forEach(function(ad) { observer.observe(ad); });

        // Track clicks
        document.addEventListener('click', function(e) {
            var link = e.target.closest('.imz-ad-link[data-ad-id]');
            if (link) {
                imzTrackAd(link.getAttribute('data-ad-id'), 'click');
            }
        });

        function imzTrackAd(adId, eventType) {
            var fd = new FormData();
            fd.append('action', 'imz_track_ad_event');
            fd.append('ad_id', adId);
            fd.append('event_type', eventType);
            fetch('<?php echo admin_url('admin-ajax.php'); ?>', { method: 'POST', body: fd });
        }

        // =====================================================================
        // MATERIAL 3 DINÂMICO para todos os cards de anúncio/música:
        // 1) Proporção inteligente: anúncios com texto mostram o criativo na
        //    sua proporção natural (limitada entre 1:1 e 2.35:1) em vez do
        //    corte fixo do formato — um criativo vertical nunca vira "tira".
        // 2) Cor dominante extraída da imagem aplicada nas variáveis --m3-*.
        // Fail-open: se a imagem bloquear o canvas (CORS), mantém o padrão.
        // =====================================================================
        document.querySelectorAll('.imz-ad-item').forEach(function(card) {
            var cover = card.querySelector('.imz-ad-music-cover, .imz-ad-image');
            if (!cover || !cover.src) return;

            // 1) Proporção inteligente (não depende de CORS — lê da própria imagem):
            //    só para anúncios normais com bloco de texto, onde a imagem é
            //    "media" e não o banner inteiro
            function imzSmartAspect() {
                if (!cover.classList.contains('imz-ad-image')) return;
                if (!card.querySelector('.imz-ad-text-content')) return;
                if (!cover.naturalWidth || !cover.naturalHeight) return;
                var natural = cover.naturalWidth / cover.naturalHeight;
                var smart = Math.max(1, Math.min(2.35, natural));
                cover.style.aspectRatio = String(smart);
            }
            if (cover.complete) { imzSmartAspect(); } else { cover.addEventListener('load', imzSmartAspect); }

            // 2) Cor dominante (precisa de canvas; pode falhar por CORS — fail-open)
            var probe = new Image();
            probe.crossOrigin = 'anonymous';
            probe.onload = function() {
                try {
                    var size = 12;
                    var canvas = document.createElement('canvas');
                    canvas.width = size;
                    canvas.height = size;
                    var ctx = canvas.getContext('2d');
                    ctx.drawImage(probe, 0, 0, size, size);
                    var data = ctx.getImageData(0, 0, size, size).data;

                    // Média ponderada: ignora pixels quase pretos/brancos e prefere os saturados
                    var r = 0, g = 0, b = 0, weight = 0;
                    for (var i = 0; i < data.length; i += 4) {
                        var pr = data[i], pg = data[i + 1], pb = data[i + 2];
                        var max = Math.max(pr, pg, pb), min = Math.min(pr, pg, pb);
                        var lum = (max + min) / 2;
                        if (lum < 28 || lum > 235) continue;       // quase preto/branco
                        var sat = max - min;                        // saturação aproximada
                        var w = 1 + sat / 64;                       // pixels coloridos pesam mais
                        r += pr * w; g += pg * w; b += pb * w; weight += w;
                    }
                    if (weight < 6) return; // capa praticamente monocromática — manter padrão

                    r = Math.round(r / weight); g = Math.round(g / weight); b = Math.round(b / weight);

                    // Realce: garantir cor viva e legível sobre fundo escuro
                    var maxc = Math.max(r, g, b);
                    if (maxc < 140 && maxc > 0) {
                        var boost = 150 / maxc;
                        r = Math.min(255, Math.round(r * boost));
                        g = Math.min(255, Math.round(g * boost));
                        b = Math.min(255, Math.round(b * boost));
                    }

                    card.style.setProperty('--m3-accent', 'rgb(' + r + ',' + g + ',' + b + ')');
                    card.style.setProperty('--m3-accent-soft', 'rgba(' + r + ',' + g + ',' + b + ',0.14)');
                    card.style.setProperty('--m3-accent-border', 'rgba(' + r + ',' + g + ',' + b + ',0.32)');
                } catch (e) {
                    // Canvas bloqueado por CORS — fica a cor padrão
                }
            };
            probe.src = cover.src;
        });
    })();
    </script>
    <?php
}

// Script para calcular preço estimado no formulário
add_action('wp_footer', 'imz_ad_form_price_script');
function imz_ad_form_price_script() {
    $ad_prices = get_option('imz_ad_prices', ['banner' => 200, 'destaque' => 500, 'sidebar' => 150]);
    if (!is_page() && !is_singular()) return;
    ?>
    <script>
    (function() {
        var typeSelect = document.getElementById('ad_type');
        var durationSelect = document.getElementById('ad_duration');
        var priceDisplay = document.getElementById('imz-ad-estimated-price');
        var prices = <?php echo json_encode($ad_prices); ?>;

        if (!typeSelect || !durationSelect || !priceDisplay) return;

        function updatePrice() {
            var type = typeSelect.value;
            var days = parseInt(durationSelect.value) || 7;
            var weeks = Math.ceil(days / 7);
            var pricePerWeek = prices[type] || 200;
            priceDisplay.textContent = (pricePerWeek * weeks).toLocaleString() + ' MT';
        }

        typeSelect.addEventListener('change', updatePrice);
        durationSelect.addEventListener('change', updatePrice);
        updatePrice();

        // Pricing cards click-to-select
        document.querySelectorAll('.imz-ad-pricing-card').forEach(function(card) {
            card.addEventListener('click', function() {
                var type = this.getAttribute('data-type');
                typeSelect.value = type;
                updatePrice();
                document.querySelectorAll('.imz-ad-pricing-card').forEach(function(c) { c.classList.remove('active'); });
                this.classList.add('active');
            });
        });
    })();
    </script>
    <?php
}
