<?php
// includes/admin/admin-distribution-controller.php
//
// Controller principal da Gestão de Distribuição Digital (admin).
// 8 tabs: Visão Geral, Lançamentos, Fila de Aprovação, Serviços Exclusivos,
// Catálogo de Faixas, Splits, Importar Royalties, Não Reclamados, Auditoria.

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

require_once RMBZ_PLUGIN_PATH . 'includes/admin/admin-import-royalties.php';
require_once RMBZ_PLUGIN_PATH . 'includes/admin/admin-unclaimed-royalties.php';
if ( file_exists( RMBZ_PLUGIN_PATH . 'includes/admin/admin-exclusive-services.php' ) ) {
    require_once RMBZ_PLUGIN_PATH . 'includes/admin/admin-exclusive-services.php';
}
if ( file_exists( RMBZ_PLUGIN_PATH . 'includes/admin/admin-distribution-releases.php' ) ) {
    require_once RMBZ_PLUGIN_PATH . 'includes/admin/admin-distribution-releases.php';
}
if ( file_exists( RMBZ_PLUGIN_PATH . 'includes/admin/admin-distribution-advanced.php' ) ) {
    require_once RMBZ_PLUGIN_PATH . 'includes/admin/admin-distribution-advanced.php';
}

/**
 * [DESIGN 2.0] Camada de design Material 3 (claro) partilhada por TODAS as
 * abas da distribuição. Imprime-se uma vez no wrapper; cada vista herda-a
 * por estar dentro de .rmbz-rd2. Vence os estilos legados por especificidade
 * (.rmbz-rd2 .classe) sem tocar na lógica de nenhuma vista.
 *
 * O guard estático garante que o CSS sai só uma vez por request, mesmo que
 * uma vista de detalhe também o invoque.
 */
function rmbz_distro_modern_styles() {
    static $printed = false;
    if ( $printed ) return;
    $printed = true;
    ?>
    <style>
    .rmbz-rd2 {
        --rd-surface: #ffffff;
        --rd-surface-2: #f7f8fa;
        --rd-surface-3: #eef0f3;
        --rd-line: #e6e8eb;
        --rd-text: #16181d;
        --rd-text-muted: #5b6370;
        --rd-text-faint: #9aa1ad;
        --rd-accent: #6356E5;
        --rd-distro: #E37A26;
        --rd-radius: 18px;
        --rd-radius-sm: 12px;
        --rd-shadow: 0 1px 2px rgba(16,24,40,.05), 0 1px 3px rgba(16,24,40,.04);
        --rd-shadow-lift: 0 8px 28px rgba(16,24,40,.10);
        --rd-ease: cubic-bezier(.4,0,.2,1);
        color: var(--rd-text);
        animation: rd-fade .4s var(--rd-ease) both;
    }
    @keyframes rd-fade { from { opacity:0; } to { opacity:1; } }
    @keyframes rd-rise { from { opacity:0; transform: translateY(10px); } to { opacity:1; transform:none; } }

    /* Cartões */
    .rmbz-rd2 .rmbz-section,
    .rmbz-rd2 .rmbz-track-card,
    .rmbz-rd2 .rmbz-review-checklist,
    .rmbz-rd2 .rmbz-an-card,
    .rmbz-rd2 .rmbz-exc-card {
        background: var(--rd-surface) !important;
        border: 1px solid var(--rd-line) !important;
        border-radius: var(--rd-radius) !important;
        box-shadow: var(--rd-shadow) !important;
        transition: box-shadow .2s var(--rd-ease), transform .2s var(--rd-ease), border-color .2s var(--rd-ease);
    }
    .rmbz-rd2 .rmbz-track-card { animation: rd-rise .45s var(--rd-ease) both; }
    .rmbz-rd2 .rmbz-track-card:nth-child(2) { animation-delay:.04s; }
    .rmbz-rd2 .rmbz-track-card:nth-child(3) { animation-delay:.08s; }
    .rmbz-rd2 .rmbz-track-card:nth-child(4) { animation-delay:.12s; }
    .rmbz-rd2 .rmbz-track-card:hover,
    .rmbz-rd2 .rmbz-exc-card:hover {
        box-shadow: var(--rd-shadow-lift) !important;
        border-color: #d6d9de !important;
        transform: translateY(-2px);
    }

    /* Sidebar com capa */
    .rmbz-rd2 .rmbz-rel-sticky-col { padding: 16px !important; }
    .rmbz-rd2 .rmbz-rel-sticky-col img { border-radius: 14px !important; box-shadow: 0 6px 20px rgba(16,24,40,.14); transition: transform .25s var(--rd-ease); }
    .rmbz-rd2 .rmbz-rel-sticky-col a:hover img { transform: scale(1.015); }

    /* Cabeçalhos */
    .rmbz-rd2 .rmbz-section > h2,
    .rmbz-rd2 .rmbz-section > h3,
    .rmbz-rd2 .rmbz-meta-section,
    .rmbz-rd2 .rmbz-checklist-head,
    .rmbz-rd2 .rmbz-track-head { letter-spacing: -.01em; }

    /* Metadata */
    .rmbz-rd2 .rmbz-meta-item { transition: background .15s var(--rd-ease); border-radius: 10px; }
    .rmbz-rd2 .rmbz-meta-label { color: var(--rd-text-faint) !important; text-transform: uppercase; letter-spacing:.05em; font-size:10px !important; font-weight:700 !important; }
    .rmbz-rd2 .rmbz-meta-value { color: var(--rd-text) !important; font-weight:600; }
    .rmbz-rd2 .rmbz-meta-value--muted { color: var(--rd-text-muted) !important; font-weight:500; }

    /* Chips / badges / pills */
    .rmbz-rd2 .rmbz-meta-chip,
    .rmbz-rd2 .rmbz-badge {
        border-radius: 999px !important;
        font-weight: 600 !important;
        transition: transform .12s var(--rd-ease), box-shadow .12s var(--rd-ease);
    }
    .rmbz-rd2 .rmbz-meta-chip:hover { transform: translateY(-1px); }
    .rmbz-rd2 .rmbz-status-pill,
    .rmbz-rd2 .rmbz-rel-status,
    .rmbz-rd2 .rmbz-meta-status,
    .rmbz-rd2 .rmbz-tab-badge {
        border-radius: 999px !important;
        font-weight: 700 !important;
        letter-spacing: .01em;
    }

    /* Botões */
    .rmbz-rd2 .button {
        border-radius: 10px !important;
        transition: transform .1s var(--rd-ease), box-shadow .15s var(--rd-ease), filter .15s var(--rd-ease) !important;
    }
    .rmbz-rd2 .button:hover { filter: brightness(1.03); }
    .rmbz-rd2 .button:active { transform: scale(.97); }
    .rmbz-rd2 .button-primary { box-shadow: 0 2px 8px rgba(99,86,229,.22); }

    /* Player / waveform */
    .rmbz-rd2 .rmbz-track-player audio { border-radius: 12px; }
    .rmbz-rd2 .rmbz-waveform,
    .rmbz-rd2 .rmbz-waveform-load {
        border-radius: 12px !important;
        background: var(--rd-surface-2) !important;
    }

    /* Techinfo */
    .rmbz-rd2 .rmbz-track-techinfo {
        background: var(--rd-surface-2) !important;
        border-radius: 12px !important;
        overflow: hidden;
    }
    .rmbz-rd2 .rmbz-track-techinfo .ti-item strong { color: var(--rd-text) !important; font-weight:700 !important; }
    .rmbz-rd2 .rmbz-track-techinfo .ti-item span { color: var(--rd-text-faint) !important; }

    /* Número da faixa — acento da marca de distribuição */
    .rmbz-rd2 .rmbz-track-num {
        border-radius: 10px !important;
        font-variant-numeric: tabular-nums;
        background: linear-gradient(135deg, var(--rd-distro), #c4621a) !important;
        color: #fff !important;
        box-shadow: 0 2px 6px rgba(227,122,38,.28);
    }

    /* Inputs */
    .rmbz-rd2 .rmbz-rel-input,
    .rmbz-rd2 .rmbz-isrc-input,
    .rmbz-rd2 input[type="text"],
    .rmbz-rd2 input[type="url"],
    .rmbz-rd2 input[type="search"],
    .rmbz-rd2 input[type="date"],
    .rmbz-rd2 input[type="number"],
    .rmbz-rd2 textarea,
    .rmbz-rd2 select {
        border-radius: 10px !important;
        transition: border-color .15s var(--rd-ease), box-shadow .15s var(--rd-ease) !important;
    }
    .rmbz-rd2 input:focus,
    .rmbz-rd2 textarea:focus,
    .rmbz-rd2 select:focus {
        border-color: var(--rd-accent) !important;
        box-shadow: 0 0 0 3px rgba(99,86,229,.14) !important;
        outline: none !important;
    }

    /* Banners / secções internas */
    .rmbz-rd2 .rmbz-meta-section { border-radius: var(--rd-radius-sm) !important; }
    .rmbz-rd2 .rmbz-section a.button-small { border-radius: 8px !important; }

    /* Tabelas (catálogo, splits, auditoria) — cabeçalho e linhas suaves */
    .rmbz-rd2 table.wp-list-table,
    .rmbz-rd2 table.widefat {
        border-radius: var(--rd-radius-sm) !important;
        overflow: hidden;
        border-color: var(--rd-line) !important;
        box-shadow: var(--rd-shadow) !important;
    }
    .rmbz-rd2 table.wp-list-table thead th,
    .rmbz-rd2 table.widefat thead th {
        background: var(--rd-surface-2) !important;
        border-bottom: 1px solid var(--rd-line) !important;
    }
    .rmbz-rd2 table.wp-list-table tbody tr,
    .rmbz-rd2 table.widefat tbody tr { transition: background .12s var(--rd-ease); }
    .rmbz-rd2 table.wp-list-table tbody tr:hover,
    .rmbz-rd2 table.widefat tbody tr:hover { background: var(--rd-surface-2) !important; }

    /* Nav tabs da distribuição — toque moderno */
    .rmbz-rd2-tabs .rmbz-tab-badge {
        border-radius: 999px;
        font-weight: 700;
    }
    </style>
    <?php
}

function rmbz_render_admin_distribution_wrapper() {
    $active_tab = isset( $_GET['tab'] ) ? sanitize_text_field( $_GET['tab'] ) : 'dashboard';

    // Contadores para badges nas tabs
    global $wpdb;
    $t_releases = $wpdb->prefix . 'rmbz_distro_releases';
    $t_platforms = $wpdb->prefix . 'rmbz_distro_release_platforms';
    $t_unclaimed = $wpdb->prefix . 'rmbz_distro_unclaimed';

    $pending_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $t_releases WHERE status IN ('pendente','pending','submitted')" );
    $unclaimed_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $t_unclaimed WHERE status = 'pending'" );
    $royalties_pending = function_exists('rmbz_count_pending_imports') ? rmbz_count_pending_imports() : 0;

    // Releases devolvidos e com prazo vencido precisam de atenção
    $returned_overdue = 0;
    $col_exists = $wpdb->get_var( "SHOW COLUMNS FROM $t_releases LIKE 'return_deadline'" );
    if ( $col_exists ) {
        $returned_overdue = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM $t_releases WHERE status = 'returned' AND return_deadline < NOW()"
        );
    }

    $exclusive_pending = 0;
    if ( $wpdb->get_var( "SHOW TABLES LIKE '$t_platforms'" ) === $t_platforms ) {
        // [BUGFIX 1.5.12] JOIN com releases para ignorar órfãos.
        // [FEAT 1.5.14] Badge agora agrega 'requested' + 'conflict' — ambos
        // requerem atenção admin (pendentes = decidir, conflitos = resolver
        // com o artista ou recontactar distribuidor em disputa).
        $exclusive_pending = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM $t_platforms p
             JOIN $t_releases r ON p.release_id = r.id
             WHERE p.yt_content_id_status IN ('requested','conflict')
                OR p.fb_monet_status      IN ('requested','conflict')
                OR p.tt_monet_status      IN ('requested','conflict')"
        );
    }

    $pending_approvals = function_exists('rmbz_count_pending_imports') ? rmbz_count_pending_imports() : 0;

    // [1.5.120] Contar pedidos de alteração de splits pendentes
    $split_change_pending = 0;
    $t_split_req = $wpdb->prefix . 'rmbz_split_change_requests';
    if ( $wpdb->get_var( "SHOW TABLES LIKE '$t_split_req'" ) === $t_split_req ) {
        $split_change_pending = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM $t_split_req WHERE status = 'pending'"
        );
    }

    // [1.5.144] Contar pedidos pendentes de alteração de lojas
    $store_change_pending = 0;
    $t_store_req = $wpdb->prefix . 'rmbz_store_change_requests';
    if ( $wpdb->get_var( "SHOW TABLES LIKE '$t_store_req'" ) === $t_store_req ) {
        $store_change_pending = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM $t_store_req WHERE status = 'pending'"
        );
    }

    // [1.6.117.7] Contar pedidos pendentes de remoção Content ID
    $contentid_pending = 0;
    $t_cid = $wpdb->prefix . 'rmbz_contentid_requests';
    if ( $wpdb->get_var( "SHOW TABLES LIKE '$t_cid'" ) === $t_cid ) {
        $contentid_pending = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM $t_cid WHERE status = 'pendente'"
        );
    }

    $tabs = [
        'dashboard'   => [ 'label' => '📊 Visão Geral',        'badge' => 0 ],
        'releases'    => [ 'label' => '🎵 Lançamentos',        'badge' => $returned_overdue ],
        'approval'    => [ 'label' => '⚡ Fila de Aprovação',  'badge' => $pending_count ],
        'exclusives'  => [ 'label' => '🔒 Serviços Exclusivos','badge' => $exclusive_pending ],
        'contentid'   => [ 'label' => '📺 Pedidos Content ID', 'badge' => $contentid_pending ],
        'tracks'      => [ 'label' => '💿 Catálogo de Faixas', 'badge' => 0 ],
        'splits'      => [ 'label' => '🤝 Splits',             'badge' => 0 ],
        'split_requests' => [ 'label' => '📩 Pedidos Splits',  'badge' => $split_change_pending ],
        'store_requests' => [ 'label' => '🏪 Pedidos Lojas',   'badge' => $store_change_pending ],
        'stores_catalog' => [ 'label' => '📚 Catálogo Lojas',  'badge' => 0 ],
        'import'      => [ 'label' => '📥 Importar Royalties', 'badge' => 0 ],
        'royalties'   => [ 'label' => '💰 Royalties',          'badge' => $royalties_pending ],
        'unclaimed'   => [ 'label' => '⚠️ Não Reclamados',     'badge' => $unclaimed_count ],
        'match_review'=> [ 'label' => '🔍 Matches a Rever',    'badge' => function_exists('rmbz_match_review_pending_count') ? rmbz_match_review_pending_count() : 0 ],
        'isrc_mappings'=> [ 'label' => '🔗 Mapeamentos ISRC',   'badge' => 0 ],
        'diagnostics' => [ 'label' => '🩺 Diagnóstico',         'badge' => 0 ],
        'audit'       => [ 'label' => '📋 Auditoria',          'badge' => 0 ],
        'notifications' => [ 'label' => '📢 Comunicação',      'badge' => 0 ],
        'settings'    => [ 'label' => '⚙ Configurações',       'badge' => 0 ],
    ];

    ?>
    <div class="wrap rmbz-admin-distro">
        <h1 class="wp-heading-inline">Gestão de Distribuição Digital</h1>
        <hr class="wp-header-end">

        <h2 class="nav-tab-wrapper rmbz-tabs">
            <?php foreach ( $tabs as $slug => $info ): ?>
                <a href="?page=rmbz-admin-distribution&tab=<?php echo esc_attr($slug); ?>"
                   class="nav-tab <?php echo $active_tab === $slug ? 'nav-tab-active' : ''; ?>">
                    <?php echo esc_html($info['label']); ?>
                    <?php if ( $info['badge'] > 0 ): ?>
                        <span class="rmbz-tab-badge"><?php echo (int) $info['badge']; ?></span>
                    <?php endif; ?>
                </a>
            <?php endforeach; ?>
        </h2>

        <?php rmbz_distro_modern_styles(); ?>
        <div class="tab-content rmbz-rd2" style="margin-top: 20px;">
            <?php
            switch ( $active_tab ) {
                case 'releases':
                    if ( function_exists('rmbz_admin_render_releases_tab') ) rmbz_admin_render_releases_tab();
                    else echo '<p>Módulo de lançamentos não encontrado.</p>';
                    break;

                case 'approval':
                    if ( function_exists('rmbz_admin_render_approval_queue') ) rmbz_admin_render_approval_queue();
                    else echo '<p>Módulo de aprovação não encontrado.</p>';
                    break;

                case 'exclusives':
                    if ( function_exists('rmbz_render_exclusive_services_page') ) rmbz_render_exclusive_services_page();
                    elseif ( function_exists('rmbz_admin_exclusive_services_page') ) rmbz_admin_exclusive_services_page();
                    else echo '<p>Módulo de serviços exclusivos não encontrado.</p>';
                    break;

                case 'contentid':
                    // [1.6.117.7] Pedidos de remoção Content ID — integrado
                    // aqui em vez de menu separado. Vista lista ou detalhe
                    // consoante ?view=detail&id=X
                    if ( isset( $_GET['cid_msg'] ) ) {
                        $cid_msg_map = [
                            'aprovado'           => '✓ Pedido aprovado. Artista notificado.',
                            'rejeitado'          => '✗ Pedido rejeitado. Artista notificado.',
                            'already_processed'  => '⚠ Pedido já tinha sido processado.',
                        ];
                        $cid_msg = $cid_msg_map[ sanitize_key( $_GET['cid_msg'] ) ] ?? '';
                        if ( $cid_msg ) {
                            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $cid_msg ) . '</p></div>';
                        }
                    }
                    $cid_view = isset( $_GET['view'] ) ? sanitize_key( $_GET['view'] ) : 'list';
                    if ( $cid_view === 'detail' ) {
                        $cid_id = (int) ( $_GET['id'] ?? 0 );
                        if ( function_exists( 'rmbz_contentid_render_detail' ) ) {
                            rmbz_contentid_render_detail( $cid_id );
                        }
                    } else {
                        if ( function_exists( 'rmbz_contentid_render_styles' ) ) {
                            rmbz_contentid_render_styles();
                        }
                        if ( function_exists( 'rmbz_contentid_render_list' ) ) {
                            rmbz_contentid_render_list();
                        }
                    }
                    break;

                case 'tracks':
                    if ( function_exists('rmbz_admin_render_tracks_catalog') ) rmbz_admin_render_tracks_catalog();
                    else echo '<p>Módulo de catálogo não encontrado.</p>';
                    break;

                case 'splits':
                    if ( function_exists('rmbz_admin_render_splits_page') ) rmbz_admin_render_splits_page();
                    else echo '<p>Módulo de splits não encontrado.</p>';
                    break;

                case 'split_requests':
                    // [1.5.120] Pedidos de alteração de splits da Fase 3.
                    if ( function_exists('rmbz_splits_phases_render_admin_panel') ) {
                        rmbz_splits_phases_render_admin_panel();
                    } else {
                        echo '<p>Módulo de pedidos de splits não carregado.</p>';
                    }
                    break;

                /* [1.5.144] Pedidos de alteração de lojas (DSPs).
                   Sistema novo: artista pede no single-view, admin aprova/rejeita aqui. */
                case 'store_requests':
                    if ( function_exists('rmbz_store_admin_requests_page') ) {
                        rmbz_store_admin_requests_page();
                    } else {
                        echo '<p>Módulo de pedidos de lojas não carregado.</p>';
                    }
                    break;

                /* [1.5.144] Catálogo de lojas — admin pode adicionar/editar/desactivar
                   DSPs. Built-in vêm seeded; custom são adicionadas via UI. */
                case 'stores_catalog':
                    if ( function_exists('rmbz_store_admin_catalog_page') ) {
                        rmbz_store_admin_catalog_page();
                    } else {
                        echo '<p>Módulo de catálogo de lojas não carregado.</p>';
                    }
                    break;

                case 'import':
                    if ( function_exists('rmbz_render_import_royalties_page') ) rmbz_render_import_royalties_page();
                    else echo '<p>Módulo de importação não encontrado.</p>';
                    break;

                case 'unclaimed':
                    if ( function_exists('rmbz_render_unclaimed_royalties_page') ) rmbz_render_unclaimed_royalties_page();
                    else echo '<p>Módulo de não reclamados não encontrado.</p>';
                    break;

                case 'royalties':
                    if ( function_exists('rmbz_render_royalties_module') ) rmbz_render_royalties_module();
                    else echo '<p>Módulo Royalties não encontrado.</p>';
                    break;

                case 'audit':
                    if ( function_exists('rmbz_admin_render_audit_log') ) rmbz_admin_render_audit_log();
                    else echo '<p>Módulo de auditoria não encontrado.</p>';
                    break;

                case 'match_review':
                    if ( function_exists('rmbz_render_admin_match_review') ) {
                        rmbz_render_admin_match_review();
                    } else {
                        echo '<p>Módulo de revisão de matches não encontrado.</p>';
                    }
                    break;

                case 'isrc_mappings':
                    if ( function_exists('rmbz_render_isrc_mappings_page') ) {
                        rmbz_render_isrc_mappings_page();
                    } else {
                        echo '<p>Módulo de mapeamentos ISRC não carregado.</p>';
                    }
                    break;

                case 'diagnostics':
                    if ( function_exists('rmbz_render_import_diagnostics') ) {
                        rmbz_render_import_diagnostics();
                    } else {
                        echo '<p>Módulo de diagnóstico não carregado.</p>';
                    }
                    break;

                case 'settings':
                    if ( function_exists('rmbz_render_admin_distribution_settings') ) {
                        rmbz_render_admin_distribution_settings();
                    } else {
                        echo '<p>Módulo de configurações não encontrado.</p>';
                    }
                    break;

                case 'notifications':
                    // [1.5.183] Página admin de Comunicação — criar/gerir
                    // notificações inline (banners no topo das páginas dos artistas).
                    if ( function_exists('rmbz_notif_render_admin_page') ) {
                        rmbz_notif_render_admin_page();
                    } else {
                        echo '<p>Módulo de notificações não carregado.</p>';
                    }
                    break;

                case 'dashboard':
                default:
                    rmbz_render_admin_distro_dashboard_v2();
                    break;
            }
            ?>
        </div>
    </div>

    <style>
    .rmbz-admin-distro .rmbz-tabs { display: flex; flex-wrap: wrap; padding-bottom: 0; }
    .rmbz-admin-distro .rmbz-tabs .nav-tab { display: inline-flex; align-items: center; gap: 6px; }
    .rmbz-admin-distro .rmbz-tab-badge { background: #e74c3c; color: #fff; border-radius: 10px; padding: 1px 8px; font-size: 11px; font-weight: 700; min-width: 18px; text-align: center; }
    .rmbz-admin-distro .nav-tab-active .rmbz-tab-badge { background: #f0b90b; color: #000; }

    .rmbz-kpi-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 16px; margin-bottom: 24px; }
    .rmbz-kpi { background: #fff; border-radius: 8px; padding: 18px 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); border-left: 4px solid #ccc; }
    .rmbz-kpi .lbl { font-size: 11px; color: #666; text-transform: uppercase; font-weight: 600; letter-spacing: 0.4px; margin: 0 0 10px 0; }
    .rmbz-kpi .val { font-size: 28px; font-weight: 700; color: #222; margin: 0; line-height: 1.2; }
    .rmbz-kpi .sub { color: #888; font-size: 12px; margin: 8px 0 0 0; }
    .rmbz-kpi.green  { border-left-color: #2ecc71; }
    .rmbz-kpi.amber  { border-left-color: #f0b90b; }
    .rmbz-kpi.blue   { border-left-color: #3498db; }
    .rmbz-kpi.purple { border-left-color: #9b59b6; }
    .rmbz-kpi.red    { border-left-color: #e74c3c; }

    .rmbz-section { background: #fff; border: 1px solid #ccd0d4; border-radius: 6px; padding: 20px; margin-bottom: 20px; }
    .rmbz-section h3 { margin: 0 0 15px 0; font-size: 15px; }

    .rmbz-status-pill { display: inline-block; padding: 2px 10px; border-radius: 10px; font-size: 11px; font-weight: 600; }
    .rmbz-status-incomplete { background: #eee; color: #555; }
    .rmbz-status-pendente, .rmbz-status-pending, .rmbz-status-submitted { background: #fff3cd; color: #856404; }
    .rmbz-status-returned { background: #fde4e4; color: #c0392b; border: 1px solid #e74c3c; }
    .rmbz-status-live, .rmbz-status-distribuido { background: #d4edda; color: #155724; }
    .rmbz-status-rejected, .rmbz-status-rejeitado { background: #f8d7da; color: #721c24; }
    .rmbz-status-takedown_requested, .rmbz-status-taken_down { background: #fce4ec; color: #880e4f; }

    .rmbz-table-wrap { background: #fff; border: 1px solid #ccd0d4; border-radius: 6px; overflow: auto; }
    .rmbz-table { width: 100%; border-collapse: collapse; }
    .rmbz-table th { background: #f8f9fa; padding: 10px 12px; text-align: left; font-size: 12px; font-weight: 600; color: #444; text-transform: uppercase; letter-spacing: 0.3px; border-bottom: 2px solid #e5e5e5; white-space: nowrap; }
    .rmbz-table td { padding: 10px 12px; border-bottom: 1px solid #eee; font-size: 13px; vertical-align: middle; }
    .rmbz-table tr:hover td { background: #fafafa; }
    .rmbz-table .mini-cover { width: 36px; height: 36px; border-radius: 4px; object-fit: cover; display: block; }
    .rmbz-table .placeholder-cover { width: 36px; height: 36px; border-radius: 4px; background: #eee; display: flex; align-items: center; justify-content: center; color: #aaa; font-size: 16px; }

    .rmbz-filters { background: #fff; border: 1px solid #ccd0d4; border-radius: 6px; padding: 12px 16px; margin-bottom: 15px; display: flex; gap: 10px; align-items: flex-end; flex-wrap: wrap; }
    .rmbz-filters label { font-size: 11px; color: #555; text-transform: uppercase; font-weight: 600; display: block; margin-bottom: 4px; }
    .rmbz-filters input, .rmbz-filters select { min-width: 140px; }
    .rmbz-filters .filter-group { flex: 0 1 auto; }
    .rmbz-filters .filter-actions { margin-left: auto; }
    </style>
    <?php
}

/* ============================================================================
 * Dashboard v2 — Visão Geral melhorada
 * ============================================================================ */
function rmbz_render_admin_distro_dashboard_v2() {
    global $wpdb;

    $t_stats     = $wpdb->prefix . 'rmbz_distro_stats';
    $t_releases  = $wpdb->prefix . 'rmbz_distro_releases';
    $t_tracks    = $wpdb->prefix . 'rmbz_distro_tracks';
    $t_unclaimed = $wpdb->prefix . 'rmbz_distro_unclaimed';
    $t_daily     = $wpdb->prefix . 'rmbz_distro_daily_stats';
    $t_wallets   = $wpdb->prefix . 'rmbz_wallets';

    $total_distributed = (float) $wpdb->get_var( "SELECT COALESCE(SUM(total_earnings),0) FROM $t_stats" );
    $total_streams     = (int)   $wpdb->get_var( "SELECT COALESCE(SUM(total_streams),0) FROM $t_stats" );
    $total_unclaimed   = (float) $wpdb->get_var( "SELECT COALESCE(SUM(amount),0) FROM $t_unclaimed WHERE status = 'pending'" );
    $total_tracks      = (int)   $wpdb->get_var( "SELECT COUNT(id) FROM $t_tracks" );
    $total_releases    = (int)   $wpdb->get_var( "SELECT COUNT(id) FROM $t_releases" );

    $releases_by_status = $wpdb->get_results(
        "SELECT status, COUNT(*) AS n FROM $t_releases GROUP BY status", OBJECT_K
    );
    $count_incomplete = isset($releases_by_status['incomplete']) ? (int) $releases_by_status['incomplete']->n : 0;
    $count_pending    = 0;
    foreach ( ['pendente','pending','submitted'] as $s ) {
        if ( isset($releases_by_status[$s]) ) $count_pending += (int) $releases_by_status[$s]->n;
    }
    $count_live = 0;
    foreach ( ['live','distribuido'] as $s ) {
        if ( isset($releases_by_status[$s]) ) $count_live += (int) $releases_by_status[$s]->n;
    }
    $count_rejected = 0;
    foreach ( ['rejected','rejeitado'] as $s ) {
        if ( isset($releases_by_status[$s]) ) $count_rejected += (int) $releases_by_status[$s]->n;
    }

    $top_artist = $wpdb->get_row(
        "SELECT w.user_nome, s.total_earnings, s.total_streams
         FROM $t_stats s
         JOIN $t_wallets w ON s.artist_telemovel = w.user_telemovel
         ORDER BY s.total_earnings DESC LIMIT 1"
    );

    $last_releases = $wpdb->get_results(
        "SELECT r.id, r.title, r.status, r.cover_image, r.release_date, r.created_at,
                w.user_nome AS artist_name
         FROM $t_releases r
         LEFT JOIN $t_wallets w ON r.artist_telemovel = w.user_telemovel
         ORDER BY r.id DESC LIMIT 10"
    );

    $monthly_revenue = [];
    if ( $wpdb->get_var( "SHOW TABLES LIKE '$t_daily'" ) === $t_daily ) {
        $monthly_revenue = $wpdb->get_results(
            "SELECT DATE_FORMAT(report_date, '%Y-%m') AS ym,
                    SUM(streams) AS s, SUM(sales) AS e
             FROM $t_daily
             WHERE report_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
             GROUP BY ym ORDER BY ym ASC"
        );
    }

    /* ───────────────────────────────────────────────────────────────────
     * [DESIGN 2.0] CENTRO DE AÇÃO — agrega tudo o que precisa de decisão
     * em toda a distribuição, com severidade por cor. Cada query é
     * defensiva (verifica a tabela) para não partir em instalações novas.
     * ─────────────────────────────────────────────────────────────────── */
    $has_table = function( $t ) use ( $wpdb ) {
        return $wpdb->get_var( "SHOW TABLES LIKE '$t'" ) === $t;
    };

    // Black box — dinheiro retido por reclamar (urgente: é dinheiro parado)
    $unclaimed_count = (int) $wpdb->get_var( "SELECT COUNT(id) FROM $t_unclaimed WHERE status = 'pending'" );

    // Lançamentos devolvidos com prazo já vencido
    $returned_overdue = 0;
    if ( $wpdb->get_var( "SHOW COLUMNS FROM $t_releases LIKE 'return_deadline'" ) ) {
        $returned_overdue = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM $t_releases WHERE status = 'returned' AND return_deadline < NOW()"
        );
    }

    // Serviços exclusivos pendentes/conflito
    $exclusive_pending = 0;
    $t_platforms = $wpdb->prefix . 'rmbz_distro_release_platforms';
    if ( $has_table( $t_platforms ) ) {
        $exclusive_pending = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM $t_platforms p JOIN $t_releases r ON p.release_id = r.id
             WHERE p.yt_content_id_status IN ('requested','conflict')
                OR p.fb_monet_status IN ('requested','conflict')
                OR p.tt_monet_status IN ('requested','conflict')"
        );
    }

    // Pedidos Content ID, Splits, Lojas, Matches a rever
    $contentid_pending = 0;
    $t_cid = $wpdb->prefix . 'rmbz_contentid_requests';
    if ( $has_table( $t_cid ) ) $contentid_pending = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $t_cid WHERE status = 'pendente'" );

    $split_change_pending = 0;
    $t_split_req = $wpdb->prefix . 'rmbz_split_change_requests';
    if ( $has_table( $t_split_req ) ) $split_change_pending = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $t_split_req WHERE status = 'pending'" );

    $store_change_pending = 0;
    $t_store_req = $wpdb->prefix . 'rmbz_store_change_requests';
    if ( $has_table( $t_store_req ) ) $store_change_pending = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $t_store_req WHERE status = 'pending'" );

    $match_pending = function_exists('rmbz_match_review_pending_count') ? (int) rmbz_match_review_pending_count() : 0;

    // Pedidos de takedown a aguardar decisão
    $takedown_pending = (int) $wpdb->get_var(
        "SELECT COUNT(*) FROM $t_releases WHERE status = 'takedown_requested'"
    );

    // Dias desde a última importação de royalties (para o card informativo)
    $last_import_days = null;
    $t_logs = $wpdb->prefix . 'rmbz_distro_import_logs';
    if ( $has_table( $t_logs ) ) {
        $last_import = $wpdb->get_var( "SELECT MAX(imported_at) FROM $t_logs" );
        if ( $last_import ) $last_import_days = (int) floor( ( time() - strtotime($last_import) ) / 86400 );
    }

    // Montar a lista de alertas (só entram os com contagem > 0).
    $base = '?page=rmbz-admin-distribution&tab=';
    $alerts = [];
    if ( $unclaimed_count > 0 )    $alerts[] = ['danger','💰', $unclaimed_count, 'Royalties não reclamados', 'Dinheiro retido (Black Box: $' . number_format($total_unclaimed, 2) . ') à espera de ser atribuído.', $base.'unclaimed'];
    if ( $returned_overdue > 0 )   $alerts[] = ['danger','⏰', $returned_overdue, 'Devoluções fora do prazo', 'Lançamentos devolvidos cujo prazo de correção já expirou.', $base.'releases'];
    if ( $takedown_pending > 0 )   $alerts[] = ['danger','🗑', $takedown_pending, 'Pedidos de takedown', 'Artistas pediram para remover lançamentos das lojas.', $base.'releases'];
    if ( $count_pending > 0 )      $alerts[] = ['warning','⚡', $count_pending, 'Na fila de aprovação', 'Lançamentos novos à espera da tua decisão.', $base.'approval'];
    if ( $exclusive_pending > 0 )  $alerts[] = ['warning','🔒', $exclusive_pending, 'Serviços exclusivos', 'Pedidos de YT Content ID, Facebook/IG ou TikTok por decidir.', $base.'exclusives'];
    if ( $contentid_pending > 0 )  $alerts[] = ['warning','📺', $contentid_pending, 'Pedidos Content ID', 'Pedidos de remoção do Content ID a aguardar.', $base.'contentid'];
    if ( $match_pending > 0 )      $alerts[] = ['warning','🔍', $match_pending, 'Matches a rever', 'Linhas de CSV cujo ISRC não bateu automaticamente.', $base.'match_review'];
    if ( $split_change_pending > 0 ) $alerts[] = ['info','📩', $split_change_pending, 'Pedidos de splits', 'Artistas pediram alteração de divisão de royalties.', $base.'split_requests'];
    if ( $store_change_pending > 0 ) $alerts[] = ['info','🏪', $store_change_pending, 'Pedidos de lojas', 'Pedidos de alteração de plataformas/territórios.', $base.'store_requests'];

    ?>

    <div class="rmbz-kpi-grid">
        <div class="rmbz-kpi green">
            <p class="lbl">Distribuído aos artistas</p>
            <p class="val">$<?php echo number_format( $total_distributed, 2 ); ?></p>
            <p class="sub"><?php echo number_format( $total_streams ); ?> streams totais</p>
        </div>
        <div class="rmbz-kpi amber">
            <p class="lbl">Retido (Black Box)</p>
            <p class="val">$<?php echo number_format( $total_unclaimed, 2 ); ?></p>
            <p class="sub"><a href="?page=rmbz-admin-distribution&tab=unclaimed">Resolver pendências →</a></p>
        </div>
        <div class="rmbz-kpi blue">
            <p class="lbl">Lançamentos</p>
            <p class="val"><?php echo number_format( $total_releases ); ?></p>
            <p class="sub">
                <?php echo $count_live; ?> live · <?php echo $count_pending; ?> pendente(s)
                <?php if ( $count_rejected > 0 ) echo ' · ' . $count_rejected . ' rejeitado(s)'; ?>
            </p>
        </div>
        <div class="rmbz-kpi purple">
            <p class="lbl">Top Artista</p>
            <p class="val" style="font-size:20px;"><?php echo $top_artist ? esc_html( $top_artist->user_nome ) : '—'; ?></p>
            <p class="sub">
                <?php if ( $top_artist ): ?>
                    $<?php echo number_format( $top_artist->total_earnings, 2 ); ?> ·
                    <?php echo number_format( $top_artist->total_streams ); ?> streams
                <?php else: ?>
                    Ainda sem dados
                <?php endif; ?>
            </p>
        </div>
    </div>

    <?php
    $total_alerts = array_sum( array_column( $alerts, 2 ) );
    ?>
    <div class="rmbz-ac">
        <div class="rmbz-ac-head">
            <h3>
                <?php if ( empty($alerts) ): ?>
                    <span class="rmbz-ac-ok-dot"></span> Centro de ação
                <?php else: ?>
                    <span class="rmbz-ac-pulse"></span> Centro de ação
                    <span class="rmbz-ac-total"><?php echo (int) $total_alerts; ?></span>
                <?php endif; ?>
            </h3>
            <span class="rmbz-ac-sub">Tudo o que precisa da tua decisão, num só sítio.</span>
        </div>

        <?php if ( empty($alerts) ): ?>
            <div class="rmbz-ac-clear">
                <span class="rmbz-ac-clear-ico">✅</span>
                <div>
                    <strong>Tudo em dia.</strong>
                    <p>Não há nada pendente em toda a distribuição. Bom trabalho!</p>
                </div>
            </div>
        <?php else: ?>
            <div class="rmbz-ac-grid">
                <?php foreach ( $alerts as $idx => $a ):
                    list( $sev, $ico, $count, $label, $desc, $url ) = $a;
                ?>
                    <a class="rmbz-ac-card rmbz-ac-<?php echo esc_attr($sev); ?>"
                       href="<?php echo esc_attr($url); ?>"
                       style="animation-delay: <?php echo $idx * 55; ?>ms;">
                        <span class="rmbz-ac-ico"><?php echo $ico; ?></span>
                        <span class="rmbz-ac-count" data-count="<?php echo (int) $count; ?>">0</span>
                        <span class="rmbz-ac-label"><?php echo esc_html($label); ?></span>
                        <span class="rmbz-ac-desc"><?php echo esc_html($desc); ?></span>
                        <span class="rmbz-ac-go">Resolver →</span>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 20px;">

        <div class="rmbz-section">
            <h3>📈 Receita últimos 12 meses</h3>
            <?php if ( empty($monthly_revenue) ): ?>
                <p style="color:#888;">Sem dados — importe um CSV de royalties para ver o gráfico.</p>
            <?php else: ?>
                <canvas id="rmbz-monthly-chart" style="max-height:260px;"></canvas>
                <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
                <script>
                (function() {
                    var data = <?php echo wp_json_encode( array_values( array_map( fn($r) => [
                        'label' => $r->ym,
                        'streams' => (int) $r->s,
                        'earnings' => round((float) $r->e, 2),
                    ], $monthly_revenue ) ) ); ?>;
                    var ctx = document.getElementById('rmbz-monthly-chart');
                    if ( ! ctx || ! window.Chart ) return;
                    new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: data.map(d => d.label),
                            datasets: [
                                { label: 'Receita ($)', data: data.map(d => d.earnings), backgroundColor: '#2ecc71' },
                            ]
                        },
                        options: {
                            responsive: true, maintainAspectRatio: false,
                            plugins: { legend: { display: false } },
                            scales: { y: { beginAtZero: true } }
                        }
                    });
                })();
                </script>
            <?php endif; ?>
        </div>

        <div class="rmbz-section">
            <h3>🎵 Últimos lançamentos</h3>
            <?php if ( empty($last_releases) ): ?>
                <p style="color:#888;">Sem lançamentos ainda.</p>
            <?php else: ?>
                <div style="display: flex; flex-direction: column; gap: 10px;">
                    <?php foreach ( $last_releases as $r ): ?>
                        <a href="?page=rmbz-admin-distribution&tab=releases&view=detail&id=<?php echo (int) $r->id; ?>"
                           style="display: flex; align-items: center; gap: 10px; padding: 8px; border: 1px solid #eee; border-radius: 4px; text-decoration: none; color: #222;">
                            <?php if ( ! empty($r->cover_image) ): ?>
                                <img src="<?php echo esc_url($r->cover_image); ?>" style="width:38px; height:38px; border-radius:3px; object-fit:cover;">
                            <?php else: ?>
                                <div style="width:38px; height:38px; border-radius:3px; background:#eee; display:flex; align-items:center; justify-content:center;">🎵</div>
                            <?php endif; ?>
                            <div style="flex:1; min-width:0;">
                                <strong style="display:block; font-size:13px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">
                                    <?php echo esc_html( $r->title ?: '(sem título)' ); ?>
                                </strong>
                                <small style="color:#888;"><?php echo esc_html( $r->artist_name ?? '—' ); ?></small>
                            </div>
                            <span class="rmbz-status-pill rmbz-status-<?php echo esc_attr($r->status); ?>">
                                <?php echo esc_html( $r->status ); ?>
                            </span>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

    </div>

    <?php
    $flow_steps = [
        [ '⚡', 'Aprovar lançamentos', 'Decide os lançamentos pendentes na Fila de Aprovação.', $base.'approval',      ['#7c6df2','#5a4be0'] ],
        [ '🔒', 'Serviços exclusivos', 'Revê pedidos de YT Content ID, Facebook/IG e TikTok.', $base.'exclusives',     ['#e8567f','#c23d6b'] ],
        [ '📥', 'Importar royalties',  'Carrega o CSV de royalties da distribuidora.',          $base.'import',         ['#36c68c','#1f9d6b'] ],
        [ '💰', 'ISRCs não reclamados','Atribui o dinheiro retido no Black Box aos artistas.',  $base.'unclaimed',      ['#efa84b','#ce7d1e'] ],
        [ '📋', 'Auditoria',           'Confere o log de auditoria para verificação final.',     $base.'audit',          ['#5b96f5','#3568d4'] ],
    ];
    ?>
    <div class="rmbz-flow">
        <div class="rmbz-flow-head">
            <h3>💡 Fluxo mensal recomendado</h3>
            <span class="rmbz-flow-sub">A rotina ideal, passo a passo — clica em cada cartão para ir direto.</span>
        </div>
        <div class="rmbz-flow-grid">
            <?php foreach ( $flow_steps as $i => $st ):
                list( $ico, $title, $desc, $url, $grad ) = $st;
            ?>
                <a class="rmbz-flow-card" href="<?php echo esc_attr($url); ?>" style="animation-delay: <?php echo $i * 60; ?>ms;">
                    <span class="rmbz-flow-step"><?php echo $i + 1; ?></span>
                    <span class="rmbz-flow-ico" style="background: linear-gradient(135deg, <?php echo $grad[0]; ?>, <?php echo $grad[1]; ?>);">
                        <?php echo $ico; ?>
                    </span>
                    <span class="rmbz-flow-title"><?php echo esc_html($title); ?></span>
                    <span class="rmbz-flow-desc"><?php echo esc_html($desc); ?></span>
                    <span class="rmbz-flow-go" style="color: <?php echo $grad[1]; ?>;">Abrir →</span>
                </a>
            <?php endforeach; ?>
        </div>
    </div>

    <style>
    /* ════════ CENTRO DE AÇÃO — alertas semânticos animados ════════ */
    .rmbz-ac { margin: 18px 0; }
    .rmbz-ac-head { display: flex; align-items: baseline; gap: 12px; margin-bottom: 12px; flex-wrap: wrap; }
    .rmbz-ac-head h3 { margin: 0; font-size: 16px; font-weight: 800; display: flex; align-items: center; gap: 9px; color: #16181d; }
    .rmbz-ac-sub { font-size: 12px; color: #6b7280; }
    .rmbz-ac-total {
        background: #16181d; color: #fff; font-size: 12px; font-weight: 800;
        border-radius: 999px; padding: 2px 10px; min-width: 22px; text-align: center;
    }
    .rmbz-ac-pulse, .rmbz-ac-ok-dot { width: 11px; height: 11px; border-radius: 50%; flex-shrink: 0; }
    .rmbz-ac-ok-dot { background: #22c55e; }
    .rmbz-ac-pulse { background: #ef4444; position: relative; }
    .rmbz-ac-pulse::after {
        content: ''; position: absolute; inset: 0; border-radius: 50%;
        background: #ef4444; animation: rmbz-ac-ping 1.6s cubic-bezier(0,0,.2,1) infinite;
    }
    @keyframes rmbz-ac-ping { 0% { transform: scale(1); opacity: .7; } 80%,100% { transform: scale(2.6); opacity: 0; } }

    .rmbz-ac-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
        gap: 12px;
    }
    .rmbz-ac-card {
        position: relative; display: flex; flex-direction: column; gap: 2px;
        padding: 16px 16px 14px; border-radius: 16px; text-decoration: none;
        border: 1px solid; overflow: hidden;
        animation: rmbz-ac-rise .5s cubic-bezier(.4,0,.2,1) both;
        transition: transform .18s cubic-bezier(.4,0,.2,1), box-shadow .18s cubic-bezier(.4,0,.2,1);
    }
    @keyframes rmbz-ac-rise { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: none; } }
    .rmbz-ac-card:hover { transform: translateY(-3px); }
    .rmbz-ac-ico { font-size: 24px; line-height: 1; }
    .rmbz-ac-count { font-size: 32px; font-weight: 900; line-height: 1.05; margin-top: 6px; font-variant-numeric: tabular-nums; }
    .rmbz-ac-label { font-size: 13.5px; font-weight: 800; color: #16181d; }
    .rmbz-ac-desc { font-size: 11.5px; color: #5b6370; line-height: 1.45; margin-top: 2px; }
    .rmbz-ac-go { font-size: 12px; font-weight: 700; margin-top: 10px; opacity: .9; }

    /* Severidades */
    .rmbz-ac-danger  { background: #fef2f2; border-color: #fdcfcb; }
    .rmbz-ac-danger  .rmbz-ac-count, .rmbz-ac-danger .rmbz-ac-go { color: #d92d20; }
    .rmbz-ac-danger:hover  { box-shadow: 0 10px 26px rgba(217,45,32,.18); border-color: #f5a8a0; }
    .rmbz-ac-warning { background: #fffaeb; border-color: #fde29a; }
    .rmbz-ac-warning .rmbz-ac-count, .rmbz-ac-warning .rmbz-ac-go { color: #b54708; }
    .rmbz-ac-warning:hover { box-shadow: 0 10px 26px rgba(181,71,8,.16); border-color: #fac56a; }
    .rmbz-ac-info    { background: #eff6ff; border-color: #bedbff; }
    .rmbz-ac-info    .rmbz-ac-count, .rmbz-ac-info .rmbz-ac-go { color: #1849a9; }
    .rmbz-ac-info:hover    { box-shadow: 0 10px 26px rgba(24,73,169,.15); border-color: #93c0fd; }

    /* Filete de cor à esquerda */
    .rmbz-ac-card::before {
        content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 4px;
    }
    .rmbz-ac-danger::before  { background: #f04438; }
    .rmbz-ac-warning::before { background: #f79009; }
    .rmbz-ac-info::before    { background: #2e90fa; }

    /* Estado "tudo em dia" */
    .rmbz-ac-clear {
        display: flex; align-items: center; gap: 16px;
        background: linear-gradient(135deg, #ecfdf3, #f6fef9);
        border: 1px solid #a6f4c5; border-radius: 16px; padding: 18px 20px;
        animation: rmbz-ac-rise .5s cubic-bezier(.4,0,.2,1) both;
    }
    .rmbz-ac-clear-ico { font-size: 30px; }
    .rmbz-ac-clear strong { font-size: 15px; color: #08653a; }
    .rmbz-ac-clear p { margin: 2px 0 0; font-size: 12.5px; color: #3f7d5c; }

    /* KPIs — polish Material 3 */
    .rmbz-rd2 .rmbz-kpi { border-radius: 16px !important; transition: transform .18s cubic-bezier(.4,0,.2,1), box-shadow .18s cubic-bezier(.4,0,.2,1); }
    .rmbz-rd2 .rmbz-kpi:hover { transform: translateY(-2px); box-shadow: 0 8px 24px rgba(16,24,40,.10); }
    .rmbz-rd2 .rmbz-kpi .val { font-weight: 800 !important; }

    /* ════════ FLUXO MENSAL — cards visuais ════════ */
    .rmbz-flow { margin: 20px 0 8px; }
    .rmbz-flow-head { margin-bottom: 12px; }
    .rmbz-flow-head h3 { margin: 0; font-size: 16px; font-weight: 800; color: #16181d; }
    .rmbz-flow-sub { font-size: 12px; color: #6b7280; }
    .rmbz-flow-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 12px;
    }
    .rmbz-flow-card {
        position: relative; display: flex; flex-direction: column; gap: 2px;
        background: #fff; border: 1px solid #e6e8eb; border-radius: 18px;
        padding: 18px 16px 15px; text-decoration: none; overflow: hidden;
        box-shadow: 0 1px 3px rgba(16,24,40,.04);
        animation: rmbz-ac-rise .5s cubic-bezier(.4,0,.2,1) both;
        transition: transform .2s cubic-bezier(.4,0,.2,1), box-shadow .2s cubic-bezier(.4,0,.2,1), border-color .2s;
    }
    .rmbz-flow-card:hover { transform: translateY(-4px); box-shadow: 0 14px 32px rgba(16,24,40,.12); border-color: #d6d9de; }
    .rmbz-flow-step {
        position: absolute; top: 14px; right: 14px;
        width: 22px; height: 22px; border-radius: 50%;
        background: #f1f3f5; color: #6b7280; font-size: 11px; font-weight: 800;
        display: flex; align-items: center; justify-content: center;
    }
    .rmbz-flow-ico {
        width: 48px; height: 48px; border-radius: 15px;
        display: flex; align-items: center; justify-content: center;
        font-size: 24px; margin-bottom: 12px;
        box-shadow: 0 4px 12px rgba(16,24,40,.16);
        transition: transform .25s cubic-bezier(.34,1.56,.64,1);
    }
    .rmbz-flow-card:hover .rmbz-flow-ico { transform: scale(1.08) rotate(-4deg); }
    .rmbz-flow-title { font-size: 14px; font-weight: 800; color: #16181d; }
    .rmbz-flow-desc { font-size: 11.5px; color: #5b6370; line-height: 1.45; margin-top: 3px; }
    .rmbz-flow-go { font-size: 12px; font-weight: 800; margin-top: 11px; opacity: 0; transform: translateX(-4px); transition: opacity .2s, transform .2s; }
    .rmbz-flow-card:hover .rmbz-flow-go { opacity: 1; transform: none; }
    </style>

    <script>
    (function() {
        // Count-up dos números dos alertas (0 → valor real).
        var nums = document.querySelectorAll('.rmbz-ac-count');
        nums.forEach(function(el) {
            var target = parseInt(el.getAttribute('data-count'), 10) || 0;
            if (target <= 0) { el.textContent = '0'; return; }
            var dur = 700, start = null;
            function step(ts) {
                if (!start) start = ts;
                var p = Math.min((ts - start) / dur, 1);
                // easeOutCubic
                var eased = 1 - Math.pow(1 - p, 3);
                el.textContent = Math.round(eased * target);
                if (p < 1) requestAnimationFrame(step);
            }
            requestAnimationFrame(step);
        });
    })();
    </script>

    <?php
}
