<?php
// includes/admin/royalties/royalties-dashboard.php

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


function rmbz_render_royalties_dashboard() {
    global $wpdb;

    $t_comm      = $wpdb->prefix . 'rmbz_distro_platform_commissions';
    $t_ledger    = $wpdb->prefix . 'rmbz_distro_ledger';
    $t_unclaimed = $wpdb->prefix . 'rmbz_distro_unclaimed';
    $t_payouts   = $wpdb->prefix . 'rmbz_distro_payouts';
    $t_stats     = $wpdb->prefix . 'rmbz_distro_stats';
    $t_logs      = $wpdb->prefix . 'rmbz_distro_import_logs';

    // KPIs — resistir a tabelas em falta
    $kpi_gross = 0; $kpi_artists = 0; $kpi_margin = 0; $kpi_unclaimed = 0; $kpi_paid = 0;
    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_comm'") === $t_comm ) {
        $kpi_gross   = (float) $wpdb->get_var("SELECT COALESCE(SUM(gross_amount_usd),0)  FROM $t_comm WHERE reverted_at IS NULL");
        $kpi_artists = (float) $wpdb->get_var("SELECT COALESCE(SUM(artist_total_usd),0)  FROM $t_comm WHERE reverted_at IS NULL");
        $kpi_margin  = (float) $wpdb->get_var("SELECT COALESCE(SUM(onemz_margin_usd),0)  FROM $t_comm WHERE reverted_at IS NULL");
    }
    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_unclaimed'") === $t_unclaimed ) {
        $kpi_unclaimed = (float) $wpdb->get_var("SELECT COALESCE(SUM(amount),0) FROM $t_unclaimed WHERE status = 'pending'");
    }
    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_payouts'") === $t_payouts ) {
        $kpi_paid = (float) $wpdb->get_var("SELECT COALESCE(SUM(amount_usd),0) FROM $t_payouts WHERE status = 'completed' AND reverted_at IS NULL");
    }

    // [1.5.177] PENDENTE SAQUE — baseado em pedidos reais (não saldo dormente)
    //
    // ANTES: $kpi_pending = total_credited - $kpi_paid
    //        Isto dava o saldo TOTAL não-pago — incluindo saldo dormente de
    //        artistas que nunca pediram nada. O label dizia "artistas aguardam
    //        pagamento" mas não correspondia à realidade.
    //
    // AGORA: soma valor de pedidos com status='pendente' em rmbz_withdrawal_requests.
    // Coluna `amount` está em MT. Convertemos para USD:
    //   - Pedidos de royalties: têm exchange_rate gravado no pedido → usar esse
    //   - Pedidos de wallet: amount já é MT, usamos taxa actual para converter
    //
    // Também contamos quantos artistas estão à espera (count distinct).
    $t_withdrawals = $wpdb->prefix . 'rmbz_withdrawal_requests';
    $kpi_pending           = 0.0;
    $kpi_pending_count     = 0;
    $kpi_pending_artists   = 0;
    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_withdrawals'") === $t_withdrawals ) {
        // Pedidos pendentes — soma MT dividido pela taxa de cada pedido (se existir)
        // Para pedidos sem exchange_rate (wallet), usamos taxa actual.
        $rate_now = function_exists('rmbz_get_exchange_rate')
            ? (float) rmbz_get_exchange_rate()
            : 63.50;
        if ( $rate_now <= 0 ) $rate_now = 63.50;

        $pending_rows = $wpdb->get_results(
            "SELECT amount, exchange_rate, source, user_telemovel
             FROM $t_withdrawals
             WHERE status = 'pendente'"
        );
        $unique_artists = [];
        foreach ( (array) $pending_rows as $pr ) {
            $kpi_pending_count++;
            $unique_artists[ $pr->user_telemovel ] = true;
            $amount_mt = (float) $pr->amount;
            // Taxa: usar a do pedido (se tiver) senão actual
            $rate = ! empty( $pr->exchange_rate ) ? (float) $pr->exchange_rate : $rate_now;
            if ( $rate > 0 ) {
                $kpi_pending += $amount_mt / $rate;
            }
        }
        $kpi_pending_artists = count( $unique_artists );
    }

    // Gráfico mensal (últimos 12 meses) — volume bruto + margem
    $monthly = [];
    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_comm'") === $t_comm ) {
        $rows = $wpdb->get_results(
            "SELECT reporting_period,
                    SUM(gross_amount_usd) AS gross,
                    SUM(artist_total_usd) AS artists,
                    SUM(onemz_margin_usd) AS margin
             FROM $t_comm
             WHERE reverted_at IS NULL
             GROUP BY reporting_period
             ORDER BY reporting_period DESC
             LIMIT 12"
        );
        foreach ( $rows as $r ) {
            $monthly[$r->reporting_period] = [
                'gross'   => (float) $r->gross,
                'artists' => (float) $r->artists,
                'margin'  => (float) $r->margin,
            ];
        }
        $monthly = array_reverse($monthly, true);
    }
    $max_monthly = 0;
    foreach ( $monthly as $m ) $max_monthly = max($max_monthly, $m['gross']);

    // Top 10 artistas por ganho acumulado
    $top_artists = [];
    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_stats'") === $t_stats ) {
        $t_wallets = $wpdb->prefix . 'rmbz_wallets';
        $top_artists = $wpdb->get_results(
            "SELECT s.artist_telemovel, s.total_earnings, s.total_streams, w.user_nome
             FROM $t_stats s
             LEFT JOIN $t_wallets w ON s.artist_telemovel = w.user_telemovel
             WHERE s.total_earnings > 0
             ORDER BY s.total_earnings DESC
             LIMIT 10"
        );
    }

    // ────────────────────────────────────────────────────────────────────────
    // [FEAT 1.6.25] TRENDS — top crescimento + top quedas
    //
    // Compara receita do MÊS ANTERIOR completo vs MÉDIA dos 3 meses
    // anteriores a esse. Excluí o mês actual (ainda em curso).
    //
    // Critérios:
    //   - Histórico ≥ 2 meses (caso contrário não há comparação fiável)
    //   - Média histórica ≥ $1 USD (estatisticamente relevante)
    //   - Para "crescimento": variação positiva ≥ +20%
    //   - Para "queda": variação negativa ≤ -20%
    // ────────────────────────────────────────────────────────────────────────
    $trends_growth = []; // top que cresceram
    $trends_drop   = []; // top que cairam
    $t_ledger_trd  = $wpdb->prefix . 'rmbz_distro_ledger';

    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_ledger_trd'") === $t_ledger_trd ) {
        // Período de referência = mês passado (completo)
        $ref_period = date('Y-m', strtotime('-1 month'));
        // Janela de comparação = 3 meses ANTES do ref_period
        $cmp_end   = date('Y-m', strtotime('-2 months'));
        $cmp_start = date('Y-m', strtotime('-4 months'));

        // Query agregada: para cada artista, valor no ref_period + sum/count no cmp range
        $t_wallets_trd = $wpdb->prefix . 'rmbz_wallets';
        $trd_rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT l.artist_telemovel,
                    w.user_nome,
                    SUM(CASE WHEN l.reporting_period = %s THEN l.amount ELSE 0 END) AS ref_amount,
                    SUM(CASE WHEN l.reporting_period BETWEEN %s AND %s THEN l.amount ELSE 0 END) AS cmp_total,
                    COUNT(DISTINCT CASE WHEN l.reporting_period BETWEEN %s AND %s THEN l.reporting_period END) AS cmp_months
               FROM $t_ledger_trd l
          LEFT JOIN $t_wallets_trd w ON w.user_telemovel = l.artist_telemovel
              WHERE l.reverted_at IS NULL
                AND l.reporting_period >= %s
                AND l.reporting_period <= %s
              GROUP BY l.artist_telemovel
              HAVING ref_amount > 0 OR cmp_total > 0",
            $ref_period,
            $cmp_start, $cmp_end,
            $cmp_start, $cmp_end,
            $cmp_start, $ref_period
        ) );

        $candidates_growth = [];
        $candidates_drop   = [];
        foreach ( $trd_rows as $r ) {
            $months_in_cmp = (int) $r->cmp_months;
            $cmp_total     = (float) $r->cmp_total;
            $ref_amount    = (float) $r->ref_amount;

            if ( $months_in_cmp < 2 ) continue; // pouco histórico
            $avg = $cmp_total / $months_in_cmp;
            if ( $avg < 1.0 ) continue; // irrelevante

            if ( $avg > 0 ) {
                $pct_change = ( ( $ref_amount - $avg ) / $avg ) * 100;
            } else {
                $pct_change = 0;
            }

            $item = [
                'telemovel'   => $r->artist_telemovel,
                'name'        => $r->user_nome ?: $r->artist_telemovel,
                'avg'         => $avg,
                'ref'         => $ref_amount,
                'pct'         => $pct_change,
                'ratio'       => $avg > 0 ? $ref_amount / $avg : 0,
                'cmp_months'  => $months_in_cmp,
            ];

            if ( $pct_change >= 20.0 && $ref_amount >= 1.0 ) {
                $candidates_growth[] = $item;
            } elseif ( $pct_change <= -20.0 ) {
                $candidates_drop[] = $item;
            }
        }
        // Ordenar
        usort( $candidates_growth, function ($a, $b) { return $b['pct'] <=> $a['pct']; } );
        usort( $candidates_drop,   function ($a, $b) { return $a['pct'] <=> $b['pct']; } );
        $trends_growth = array_slice( $candidates_growth, 0, 10 );
        $trends_drop   = array_slice( $candidates_drop,   0, 10 );

        // Label PT do mês de referência (para o cabeçalho)
        $months_pt_trd = ['', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho',
                          'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
        [$ry, $rm] = explode('-', $ref_period);
        $ref_period_label = ($months_pt_trd[(int)$rm] ?? '') . ' ' . $ry;
        [$cy_s, $cm_s] = explode('-', $cmp_start);
        [$cy_e, $cm_e] = explode('-', $cmp_end);
        $cmp_label = ($months_pt_trd[(int)$cm_s] ?? '') . ' ' . $cy_s . ' → ' .
                     ($months_pt_trd[(int)$cm_e] ?? '') . ' ' . $cy_e;
    } else {
        $ref_period_label = '';
        $cmp_label = '';
    }

    // Actividade recente — últimas 5 importações + 5 pagamentos
    $recent = [];
    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_logs'") === $t_logs ) {
        $imps = $wpdb->get_results("SELECT * FROM $t_logs ORDER BY imported_at DESC LIMIT 5");
        foreach ( $imps as $i ) {
            $recent[] = [
                'type' => 'import',
                'date' => $i->imported_at,
                'label' => '📥 Importação ' . $i->source_name,
                'sub' => $i->reporting_period . ( ! empty($i->status) && $i->status === 'reverted' ? ' · anulada' : '' ),
                'hash' => $i->file_hash,
            ];
        }
    }
    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_payouts'") === $t_payouts ) {
        $pays = $wpdb->get_results("SELECT * FROM $t_payouts ORDER BY paid_at DESC LIMIT 5");
        foreach ( $pays as $p ) {
            $recent[] = [
                'type' => 'payout',
                'date' => $p->paid_at,
                'label' => '💸 Pagamento ' . number_format($p->amount_usd, 2) . ' USD',
                'sub' => $p->artist_telemovel . ' · ' . $p->method,
                'hash' => null,
            ];
        }
    }
    usort($recent, function($a, $b){ return strcmp($b['date'], $a['date']); });
    $recent = array_slice($recent, 0, 8);

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

    /* ============================================================================
     * 5 GRÁFICOS BREAKDOWN — products/tracks/stores/countries/genres
     * Apenas dados aprovados. Filtro opcional por período (últimos 90 dias default).
     * ============================================================================ */
    $t_daily    = $wpdb->prefix . 'rmbz_distro_daily_stats';
    $t_tracks   = $wpdb->prefix . 'rmbz_distro_tracks';
    $t_releases = $wpdb->prefix . 'rmbz_distro_releases';

    $pa_filter = function_exists('rmbz_approval_clause') ? rmbz_approval_clause($t_daily, 'd.') : '';
    $range_days = isset($_GET['rod_days']) ? max(7, min(365, (int)$_GET['rod_days'])) : 90;
    $date_from = date('Y-m-d', strtotime("-$range_days days"));

    $top_products = $top_tracks = $top_stores = $top_countries = $top_genres = [];

    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_daily'") === $t_daily ) {
        // TOP 5 PRODUCTS (releases/álbuns)
        $top_products = $wpdb->get_results( $wpdb->prepare(
            "SELECT r.title AS name, r.cover_image, SUM(d.sales) AS total
             FROM $t_daily d
             LEFT JOIN $t_releases r ON d.release_id = r.id
             WHERE d.report_date >= %s AND d.release_id IS NOT NULL $pa_filter
             GROUP BY d.release_id
             HAVING total > 0
             ORDER BY total DESC
             LIMIT 5",
            $date_from
        ) );

        // TOP 5 TRACKS
        $top_tracks = $wpdb->get_results( $wpdb->prepare(
            "SELECT t.track_title AS name, SUM(d.sales) AS total
             FROM $t_daily d
             LEFT JOIN $t_tracks t ON d.track_id = t.id
             WHERE d.report_date >= %s AND d.track_id IS NOT NULL $pa_filter
             GROUP BY d.track_id
             HAVING total > 0
             ORDER BY total DESC
             LIMIT 5",
            $date_from
        ) );

        // TOP 5 STORES (+ Others)
        $all_stores = $wpdb->get_results( $wpdb->prepare(
            "SELECT d.store AS name, SUM(d.sales) AS total
             FROM $t_daily d
             WHERE d.report_date >= %s AND d.store IS NOT NULL AND d.store != '' $pa_filter
             GROUP BY d.store HAVING total > 0 ORDER BY total DESC",
            $date_from
        ) );
        $top_stores = array_slice($all_stores, 0, 5);
        $others_stores = array_slice($all_stores, 5);
        $others_stores_total = array_sum(array_map(fn($r) => (float)$r->total, $others_stores));
        if ( $others_stores_total > 0 ) {
            $o = new stdClass(); $o->name = 'Outros'; $o->total = $others_stores_total; $o->is_others = true;
            $top_stores[] = $o;
        }

        // TOP 5 COUNTRIES (+ Others)
        $all_countries = $wpdb->get_results( $wpdb->prepare(
            "SELECT d.country_code AS name, SUM(d.sales) AS total
             FROM $t_daily d
             WHERE d.report_date >= %s AND d.country_code IS NOT NULL AND d.country_code != '' $pa_filter
             GROUP BY d.country_code HAVING total > 0 ORDER BY total DESC",
            $date_from
        ) );
        $top_countries = array_slice($all_countries, 0, 5);
        $others_c = array_slice($all_countries, 5);
        $others_c_total = array_sum(array_map(fn($r) => (float)$r->total, $others_c));
        if ( $others_c_total > 0 ) {
            $o = new stdClass(); $o->name = 'Outros'; $o->total = $others_c_total; $o->is_others = true;
            $top_countries[] = $o;
        }

        // TOP 5 GENRES (via releases.primary_genre)
        $top_genres = $wpdb->get_results( $wpdb->prepare(
            "SELECT r.primary_genre AS name, SUM(d.sales) AS total
             FROM $t_daily d
             JOIN $t_releases r ON d.release_id = r.id
             WHERE d.report_date >= %s AND r.primary_genre IS NOT NULL AND r.primary_genre != '' $pa_filter
             GROUP BY r.primary_genre
             HAVING total > 0
             ORDER BY total DESC
             LIMIT 5",
            $date_from
        ) );
    }

    $rod_iso_to_name = [
        'PT' => 'Portugal', 'BR' => 'Brasil', 'US' => 'Estados Unidos', 'GB' => 'Reino Unido',
        'FR' => 'França', 'DE' => 'Alemanha', 'ES' => 'Espanha', 'IT' => 'Itália',
        'NL' => 'Holanda', 'BE' => 'Bélgica', 'CA' => 'Canadá', 'AU' => 'Austrália',
        'MX' => 'México', 'AR' => 'Argentina', 'JP' => 'Japão', 'AO' => 'Angola',
        'MZ' => 'Moçambique', 'ZA' => 'África do Sul', 'CH' => 'Suíça', 'LU' => 'Luxemburgo',
        'IE' => 'Irlanda', 'NO' => 'Noruega', 'SE' => 'Suécia', 'DK' => 'Dinamarca',
    ];
    $country_name = function($code) use ($rod_iso_to_name) {
        return $rod_iso_to_name[strtoupper($code)] ?? $code;
    };

    ?>

    <?php if ( $pending_count > 0 ): ?>
        <div class="rod-pending-banner">
            <div class="banner-icon">⏳</div>
            <div class="banner-body">
                <strong><?php echo $pending_count; ?> importaç<?php echo $pending_count === 1 ? 'ão aguarda' : 'ões aguardam'; ?> aprovação</strong>
                <p>Enquanto pendentes, os artistas não vêem o dinheiro nas suas wallets. Reveja e aprove ou rejeite cada importação para libertar os valores.</p>
            </div>
            <a href="?page=rmbz-admin-distribution&tab=royalties&rsub=imports&rim_status=pending" class="button button-primary" style="background:var(--rmbz-brand, #f0b90b); border-color:var(--rmbz-brand-strong, #d4a309); color:var(--rmbz-text-strong, #222);">
                Ver pendentes →
            </a>
        </div>
    <?php endif; ?>

    <div class="rod-kpis">
        <div class="rod-kpi big">
            <div class="lbl">Volume total (bruto)</div>
            <div class="val">$<?php echo number_format($kpi_gross, 2); ?></div>
            <div class="sub">todas as importações · USD</div>
        </div>
        <div class="rod-kpi green">
            <div class="lbl">Pago/creditado a artistas</div>
            <div class="val">$<?php echo number_format($kpi_artists, 2); ?></div>
            <div class="sub"><?php echo $kpi_gross > 0 ? number_format($kpi_artists / $kpi_gross * 100, 1) : 0; ?>% do bruto</div>
        </div>
        <div class="rod-kpi blue">
            <div class="lbl">Margem 1MZ</div>
            <div class="val">$<?php echo number_format($kpi_margin, 2); ?></div>
            <div class="sub"><?php echo $kpi_gross > 0 ? number_format($kpi_margin / $kpi_gross * 100, 1) : 0; ?>% comissão plataforma</div>
        </div>
        <div class="rod-kpi amber">
            <div class="lbl">Pendente saque</div>
            <div class="val">$<?php echo number_format($kpi_pending, 2); ?></div>
            <div class="sub">
                <?php if ( $kpi_pending_count > 0 ): ?>
                    <strong><?php echo (int) $kpi_pending_count; ?></strong> pedido<?php echo $kpi_pending_count !== 1 ? 's' : ''; ?>
                    de <strong><?php echo (int) $kpi_pending_artists; ?></strong> artista<?php echo $kpi_pending_artists !== 1 ? 's' : ''; ?>
                <?php else: ?>
                    sem pedidos pendentes
                <?php endif; ?>
            </div>
        </div>
        <div class="rod-kpi red">
            <div class="lbl">Black Box</div>
            <div class="val">$<?php echo number_format($kpi_unclaimed, 2); ?></div>
            <div class="sub">retidos · sem dono</div>
        </div>
    </div>

    <?php if ( ! empty($monthly) ): ?>
        <div class="rod-card">
            <div class="rod-card-head">
                <strong>📊 Volume mensal (últimos 12 meses)</strong>
                <span>bruto · pago a artistas · margem 1MZ</span>
            </div>
            <div class="rod-chart">
                <?php foreach ( $monthly as $period => $m ):
                    $pct_g = $max_monthly > 0 ? ($m['gross']   / $max_monthly * 100) : 0;
                    $pct_a = $max_monthly > 0 ? ($m['artists'] / $max_monthly * 100) : 0;
                    $pct_x = $max_monthly > 0 ? ($m['margin']  / $max_monthly * 100) : 0;
                ?>
                    <div class="rod-bar">
                        <div class="stack">
                            <div class="seg g" style="height: <?php echo number_format($pct_g, 1); ?>%;"
                                 title="Bruto: $<?php echo number_format($m['gross'], 2); ?>"></div>
                            <div class="seg m" style="height: <?php echo number_format($pct_x, 1); ?>%;"
                                 title="Margem 1MZ: $<?php echo number_format($m['margin'], 2); ?>"></div>
                        </div>
                        <div class="lbl"><?php echo esc_html($period); ?></div>
                        <div class="val">$<?php echo number_format($m['gross'], 0); ?></div>
                    </div>
                <?php endforeach; ?>
            </div>
            <div class="rod-chart-legend">
                <span><span class="swatch g"></span> Bruto importado</span>
                <span><span class="swatch m"></span> Margem 1MZ</span>
            </div>
        </div>
    <?php endif; ?>

    <?php // [FEAT 1.6.25] TRENDS — Top crescimento / quedas ?>
    <?php if ( ! empty($trends_growth) || ! empty($trends_drop) ): ?>
        <div class="rod-trends-card">
            <div class="rod-card-head">
                <strong>📈 Tendências por artista</strong>
                <span><?php echo esc_html( $ref_period_label ); ?> vs média de <?php echo esc_html( $cmp_label ); ?></span>
            </div>
            <div class="rod-trends-grid">

                <div class="rod-trends-col">
                    <div class="rod-trends-col-head growth">
                        <strong>⬆ Top crescimento</strong>
                        <small><?php echo count($trends_growth); ?> artista(s) acima de +20%</small>
                    </div>
                    <?php if ( empty($trends_growth) ): ?>
                        <div class="rod-trends-empty">
                            Nenhum artista com crescimento ≥ 20% neste período.
                        </div>
                    <?php else: foreach ( $trends_growth as $i => $t ):
                        $summary_url = add_query_arg([
                            'page'   => 'rmbz-admin-distribution',
                            'tab'    => 'royalties',
                            'rsub'   => 'artist_summary',
                            'artist' => $t['telemovel'],
                            'period' => $ref_period,
                        ], admin_url('admin.php'));
                        $rank_label = $i === 0 ? '🥇' : ($i === 1 ? '🥈' : ($i === 2 ? '🥉' : '#' . ($i+1)));
                    ?>
                        <a href="<?php echo esc_url($summary_url); ?>" class="rod-trends-row">
                            <span class="rod-trends-rank"><?php echo $rank_label; ?></span>
                            <span class="rod-trends-info">
                                <strong><?php echo esc_html($t['name']); ?></strong>
                                <small>$<?php echo number_format($t['avg'], 2); ?> → $<?php echo number_format($t['ref'], 2); ?></small>
                            </span>
                            <span class="rod-trends-pct growth">
                                +<?php echo number_format($t['pct'], 0); ?>%
                            </span>
                        </a>
                    <?php endforeach; endif; ?>
                </div>

                <div class="rod-trends-col">
                    <div class="rod-trends-col-head drop">
                        <strong>⬇ Top quedas</strong>
                        <small><?php echo count($trends_drop); ?> artista(s) abaixo de −20%</small>
                    </div>
                    <?php if ( empty($trends_drop) ): ?>
                        <div class="rod-trends-empty">
                            Nenhum artista com queda ≥ 20% neste período.
                        </div>
                    <?php else: foreach ( $trends_drop as $i => $t ):
                        $summary_url = add_query_arg([
                            'page'   => 'rmbz-admin-distribution',
                            'tab'    => 'royalties',
                            'rsub'   => 'artist_summary',
                            'artist' => $t['telemovel'],
                            'period' => $ref_period,
                        ], admin_url('admin.php'));
                        $rank_label = '#' . ($i+1);
                    ?>
                        <a href="<?php echo esc_url($summary_url); ?>" class="rod-trends-row">
                            <span class="rod-trends-rank"><?php echo $rank_label; ?></span>
                            <span class="rod-trends-info">
                                <strong><?php echo esc_html($t['name']); ?></strong>
                                <small>$<?php echo number_format($t['avg'], 2); ?> → $<?php echo number_format($t['ref'], 2); ?></small>
                            </span>
                            <span class="rod-trends-pct drop">
                                <?php echo number_format($t['pct'], 0); ?>%
                            </span>
                        </a>
                    <?php endforeach; endif; ?>
                </div>

            </div>
            <div class="rod-trends-foot">
                💡 Clica num artista para ver o resumo financeiro detalhado.
                Quedas podem indicar problemas de import; crescimentos podem ser hits ou ISRCs mal mapeados.
            </div>
        </div>
    <?php endif; ?>

    <div class="rod-split">
        <div class="rod-card">
            <div class="rod-card-head">
                <strong>🏆 Top 10 artistas</strong>
                <span>por ganhos acumulados</span>
            </div>
            <?php if ( empty($top_artists) ): ?>
                <p style="color:var(--rmbz-text-faint, #888);">Nenhum artista com ganhos ainda.</p>
            <?php else: ?>
                <table class="rod-table">
                    <tbody>
                    <?php foreach ( $top_artists as $i => $a ): ?>
                        <tr>
                            <td class="rank">#<?php echo $i + 1; ?></td>
                            <td>
                                <strong><?php echo esc_html($a->user_nome ?: '—'); ?></strong>
                                <div class="muted"><?php echo esc_html($a->artist_telemovel); ?></div>
                            </td>
                            <td style="text-align:right;">
                                <strong>$<?php echo number_format($a->total_earnings, 2); ?></strong>
                                <div class="muted"><?php echo number_format($a->total_streams); ?> streams</div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

        <div class="rod-card">
            <div class="rod-card-head">
                <strong>🕐 Actividade recente</strong>
                <span>últimas 8 operações</span>
            </div>
            <?php if ( empty($recent) ): ?>
                <p style="color:var(--rmbz-text-faint, #888);">Sem actividade.</p>
            <?php else: ?>
                <div class="rod-activity">
                    <?php foreach ( $recent as $r ): ?>
                        <div class="act-item <?php echo $r['type']; ?>">
                            <div class="act-main">
                                <strong><?php echo esc_html($r['label']); ?></strong>
                                <div class="muted"><?php echo esc_html($r['sub']); ?></div>
                            </div>
                            <div class="act-date"><?php echo esc_html(date('d/m H:i', strtotime($r['date']))); ?></div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <?php
    // Max total para normalizar alturas
    $_maxes = [
        'products' => max(array_map(fn($r) => (float)$r->total, $top_products) ?: [0]),
        'tracks'   => max(array_map(fn($r) => (float)$r->total, $top_tracks)   ?: [0]),
        'stores'   => max(array_map(fn($r) => (float)$r->total, $top_stores)   ?: [0]),
        'countries'=> max(array_map(fn($r) => (float)$r->total, $top_countries)?: [0]),
        'genres'   => max(array_map(fn($r) => (float)$r->total, $top_genres)   ?: [0]),
    ];
    $_sums = [
        'stores'   => array_sum(array_map(fn($r) => (float)$r->total, $top_stores)),
        'countries'=> array_sum(array_map(fn($r) => (float)$r->total, $top_countries)),
        'genres'   => array_sum(array_map(fn($r) => (float)$r->total, $top_genres)),
    ];
    // Paleta gradiente (roxo → rosa) — igual à imagem do Amadea
    $palette = ['#3d0c5e', '#6c2d9c', '#a64dc9', '#d94b9b', '#ef6c8f', '#f5a3a3'];

    // [DESIGN 2.0] Ranking horizontal: cada linha = nome + barra + valor.
    // Muito mais legível que barras verticais finas (resolve o "gráficos
    // confusos sem saber o que representam"). Barras animam ao carregar.
    $render_chart = function( $title, $rows, $max, $mode, $palette, $country_name ) {
        $total_sum = array_sum(array_map(fn($r) => (float)$r->total, $rows));
        ?>
        <div class="rod-mini-chart">
            <div class="rod-mc-title"><?php echo esc_html($title); ?></div>
            <?php if ( empty($rows) ): ?>
                <div class="rod-mc-empty">
                    <span class="rod-mc-empty-ico">📭</span>
                    Sem dados neste período.
                </div>
            <?php else: ?>
                <div class="rod-mc-rows">
                    <?php foreach ( $rows as $i => $r ):
                        $amount = (float) $r->total;
                        $pct_of_total = $total_sum > 0 ? round( $amount / $total_sum * 100, 1 ) : 0;
                        // Largura da barra é sempre relativa ao maior (max) para
                        // dar a noção de ranking; o rótulo mostra $ ou %.
                        $width_pct = $max > 0 ? max( 2, round( $amount / $max * 100 ) ) : 0;
                        $label_txt = $mode === 'pct'
                            ? $pct_of_total . '%'
                            : '$' . number_format( $amount, 2 );
                        $color = $palette[ min($i, count($palette) - 1) ];
                        $name = $r->name;
                        if ( $title === 'Países' ) $name = $country_name( $name );
                        $is_others = ! empty( $r->is_others );
                    ?>
                        <div class="rod-mc-row<?php echo $is_others ? ' is-others' : ''; ?>">
                            <span class="rod-mc-name" title="<?php echo esc_attr($name); ?>">
                                <span class="rod-mc-dot" style="background: <?php echo $color; ?>;"></span>
                                <?php echo esc_html( mb_strlen($name) > 26 ? mb_substr($name, 0, 25) . '…' : ( $name !== '' ? $name : '—' ) ); ?>
                            </span>
                            <span class="rod-mc-track">
                                <span class="rod-mc-fill" style="width: <?php echo $width_pct; ?>%; background: <?php echo $color; ?>; animation-delay: <?php echo ($i * 60); ?>ms;"></span>
                            </span>
                            <span class="rod-mc-amount"><?php echo esc_html($label_txt); ?></span>
                        </div>
                    <?php endforeach; ?>
                </div>
                <?php if ( $mode === 'abs' && $total_sum > 0 ): ?>
                    <div class="rod-mc-foot">Total no período: <strong>$<?php echo number_format($total_sum, 2); ?></strong></div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
        <?php
    };
    ?>

    <div class="rod-breakdowns-head">
        <div>
            <h3>📊 Breakdown do catálogo</h3>
            <p class="rod-breakdowns-sub">De onde vêm os teus royalties no período — os que mais renderam em cada categoria. Valores em $ (receita); Lojas, Países e Géneros mostram a % do total.</p>
        </div>
        <form method="get" style="display:flex; gap:8px; align-items:center;">
            <input type="hidden" name="page" value="rmbz-admin-distribution">
            <input type="hidden" name="tab" value="royalties">
            <input type="hidden" name="rsub" value="dashboard">
            <label style="font-size:11px; color:var(--rmbz-text-muted, #666);">Período:</label>
            <select name="rod_days" onchange="this.form.submit();" style="padding:4px 28px 4px 8px; font-size:12px;">
                <?php /* [1.5.179] padding-right extra (28px) para o chevron nativo
                   do browser não sobrepor o texto "90 dias", "180 dias", etc. */ ?>
                <option value="30"  <?php selected($range_days, 30);  ?>>30 dias</option>
                <option value="90"  <?php selected($range_days, 90);  ?>>90 dias</option>
                <option value="180" <?php selected($range_days, 180); ?>>180 dias</option>
                <option value="365" <?php selected($range_days, 365); ?>>1 ano</option>
            </select>
        </form>
    </div>

    <div class="rod-breakdowns-top">
        <?php $render_chart('Produtos',  $top_products, $_maxes['products'], 'abs', $palette, $country_name); ?>
        <?php $render_chart('Faixas',    $top_tracks,   $_maxes['tracks'],   'abs', $palette, $country_name); ?>
    </div>

    <div class="rod-breakdowns-bottom">
        <?php $render_chart('Lojas',    $top_stores,    $_maxes['stores'],    'pct', $palette, $country_name); ?>
        <?php $render_chart('Países',   $top_countries, $_maxes['countries'], 'pct', $palette, $country_name); ?>
        <?php $render_chart('Géneros',  $top_genres,    $_maxes['genres'],    'pct', $palette, $country_name); ?>
    </div>

    <style>
    .rod-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; margin-bottom: 16px; }
    .rod-pending-banner { background: #fff9e6; border: 1px solid var(--rmbz-brand, #f0b90b); border-left: 4px solid var(--rmbz-brand, #f0b90b); border-radius: 8px; padding: 14px 18px; margin-bottom: 16px; display: flex; gap: 14px; align-items: center; }
    .rod-pending-banner .banner-icon { font-size: 28px; }
    .rod-pending-banner .banner-body { flex: 1; }
    .rod-pending-banner .banner-body strong { font-size: 14px; color: #856404; display: block; margin-bottom: 4px; }
    .rod-pending-banner .banner-body p { font-size: 12px; color: #664d00; margin: 0; line-height: 1.5; }
    .rod-kpi { background: var(--rmbz-bg-card, #fff); border: 1px solid var(--rmbz-border-light, #e5e5e5); border-left: 3px solid var(--rmbz-accent, #9b59b6); border-radius: 8px; padding: 12px 16px; }
    .rod-kpi.big    { border-left-color: var(--rmbz-accent, #a855f7); }
    .rod-kpi.green  { border-left-color: var(--rmbz-success, #10b981); }
    .rod-kpi.blue   { border-left-color: var(--rmbz-info, #3b82f6); }
    .rod-kpi.amber  { border-left-color: var(--rmbz-brand, #f0b90b); }
    .rod-kpi.red    { border-left-color: var(--rmbz-danger, #ef4444); }
    .rod-kpi .lbl { font-size: 10px; color: var(--rmbz-text-faint, #888); text-transform: uppercase; letter-spacing: 0.3px; font-weight: 600; }
    .rod-kpi .val { font-size: 22px; font-weight: 500; color: var(--rmbz-text-strong, #222); margin: 4px 0 2px 0; line-height: 1.1; }
    .rod-kpi.green .val  { color: var(--rmbz-success-strong, #059669); }
    .rod-kpi.blue .val   { color: var(--rmbz-info-strong, #2563eb); }
    .rod-kpi.amber .val  { color: #856404; }
    .rod-kpi.red .val    { color: var(--rmbz-danger-strong, #b91c1c); }
    .rod-kpi .sub { font-size: 11px; color: var(--rmbz-text-muted, #666); }

    .rod-card { background: var(--rmbz-bg-card, #fff); border: 1px solid #e5e5e5; border-radius: 8px; padding: 14px 16px; margin-bottom: 12px; }
    .rod-card-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; padding-bottom: 8px; border-bottom: 1px solid var(--rmbz-border-light, #f0f0f0); }
    .rod-card-head strong {
        font-size: 13px;
        color: var(--rmbz-text-strong, #222);
        /* [1.5.166] Font display para identidade visual nos títulos das secções */
        font-family: var(--rmbz-font-display, inherit);
        font-weight: 600;
    }
    .rod-card-head span { font-size: 11px; color: var(--rmbz-text-faint, #888); }

    .rod-chart { display: flex; align-items: flex-end; gap: 8px; height: 180px; padding: 10px 0; }
    .rod-bar { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: flex-end; min-width: 0; }
    .rod-bar .stack { width: 100%; max-width: 40px; display: flex; flex-direction: column; justify-content: flex-end; height: 120px; position: relative; }
    .rod-bar .stack .seg { width: 100%; transition: height 0.3s; }
    .rod-bar .stack .seg.g { background: var(--rmbz-accent, #a855f7); border-radius: 3px 3px 0 0; }
    .rod-bar .stack .seg.m { background: var(--rmbz-info, #3b82f6); position: absolute; bottom: 0; }
    .rod-bar .lbl { font-size: 9px; color: var(--rmbz-text-faint, #888); margin-top: 6px; text-align: center; font-family: monospace; }
    .rod-bar .val { font-size: 10px; color: var(--rmbz-text-strong, #333); font-weight: 600; }
    .rod-chart-legend { display: flex; gap: 16px; justify-content: center; font-size: 11px; color: var(--rmbz-text-muted, #666); margin-top: 8px; padding-top: 8px; border-top: 1px solid #f0f0f0; }
    .rod-chart-legend .swatch { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 4px; vertical-align: middle; }
    .rod-chart-legend .swatch.g { background: var(--rmbz-accent, #a855f7); }
    .rod-chart-legend .swatch.m { background: var(--rmbz-info, #3b82f6); }

    .rod-split { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
    @media (max-width: 900px) { .rod-split { grid-template-columns: 1fr; } }

    /* [FEAT 1.6.25] Trends — top crescimento + top quedas */
    .rod-trends-card {
        background: #fff; border: 1px solid #e5e5e5;
        border-radius: 8px; padding: 14px 16px; margin-bottom: 12px;
    }
    .rod-trends-grid {
        display: grid; grid-template-columns: 1fr 1fr;
        gap: 14px; margin-top: 10px;
    }
    @media (max-width: 900px) { .rod-trends-grid { grid-template-columns: 1fr; } }

    .rod-trends-col-head {
        padding: 8px 12px; border-radius: 6px;
        margin-bottom: 8px;
    }
    .rod-trends-col-head.growth {
        background: linear-gradient(135deg, #ecfdf5, #d1fae5);
        border-left: 3px solid #10b981;
    }
    .rod-trends-col-head.drop {
        background: linear-gradient(135deg, #fef2f2, #fee2e2);
        border-left: 3px solid #dc2626;
    }
    .rod-trends-col-head strong { display: block; font-size: 13px; }
    .rod-trends-col-head.growth strong { color: #065f46; }
    .rod-trends-col-head.drop strong { color: #991b1b; }
    .rod-trends-col-head small { font-size: 11px; opacity: 0.75; }

    .rod-trends-row {
        display: flex; align-items: center; gap: 10px;
        padding: 7px 10px; border-bottom: 1px solid #f3f4f6;
        font-size: 12px; color: inherit; text-decoration: none;
        transition: background 0.1s;
        border-radius: 4px;
    }
    .rod-trends-row:hover { background: #fffbeb; }
    .rod-trends-row:last-child { border-bottom: none; }
    .rod-trends-rank {
        font-size: 14px; min-width: 28px;
        text-align: center;
        color: #9ca3af; font-weight: 600;
    }
    .rod-trends-info { flex: 1; min-width: 0; }
    .rod-trends-info strong {
        display: block; color: #1a1a1a;
        font-size: 12.5px;
        white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    }
    .rod-trends-info small {
        color: #6b7280; font-size: 10.5px;
        font-variant-numeric: tabular-nums;
    }
    .rod-trends-pct {
        font-weight: 700; font-size: 13px;
        font-variant-numeric: tabular-nums;
        white-space: nowrap;
    }
    .rod-trends-pct.growth { color: #065f46; }
    .rod-trends-pct.drop   { color: #991b1b; }

    .rod-trends-empty {
        padding: 18px 12px;
        text-align: center;
        color: #9ca3af;
        font-size: 12px;
        background: #fafafa;
        border-radius: 5px;
    }
    .rod-trends-foot {
        margin-top: 10px;
        padding: 8px 12px;
        background: #f9fafb;
        border-radius: 5px;
        font-size: 11px; color: #6b7280;
        line-height: 1.5;
    }

    .rod-table { width: 100%; border-collapse: collapse; font-size: 12px; }
    .rod-table td { padding: 8px; border-bottom: 1px solid #f0f0f0; vertical-align: middle; }
    .rod-table td.rank { color: var(--rmbz-text-faint, #888); font-weight: 600; width: 40px; }
    .rod-table .muted { font-size: 10px; color: var(--rmbz-text-faint, #888); margin-top: 2px; }

    .rod-activity .act-item { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #f0f0f0; font-size: 12px; }
    .rod-activity .act-item:last-child { border-bottom: none; }
    .rod-activity .act-main { flex: 1; min-width: 0; }
    .rod-activity .act-main strong { color: var(--rmbz-text-strong, #222); }
    .rod-activity .act-main .muted { font-size: 10px; color: var(--rmbz-text-faint, #888); margin-top: 2px; }
    .rod-activity .act-date { color: var(--rmbz-text-faint, #888); font-size: 11px; font-family: monospace; }
    .rod-activity .act-item.import .act-main strong { color: #7f4ba0; }
    .rod-activity .act-item.payout .act-main strong { color: var(--rmbz-success-strong, #059669); }
    .rod-breakdowns-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; margin: 24px 0 14px 0; }
    .rod-breakdowns-head h3 { margin: 0; font-size: 15px; font-weight: 700; color: var(--rmbz-text-strong, #16181d); }
    .rod-breakdowns-sub { margin: 4px 0 0; font-size: 12px; color: var(--rmbz-text-muted, #6b7280); max-width: 620px; line-height: 1.5; }
    .rod-breakdowns-top { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px; }
    .rod-breakdowns-bottom { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px; }
    @media (max-width: 900px) {
        .rod-breakdowns-top, .rod-breakdowns-bottom { grid-template-columns: 1fr; }
    }
    .rod-mini-chart { background: var(--rmbz-bg-card, #fff); border: 1px solid #e6e8eb; border-radius: 14px; padding: 16px 18px; min-height: 200px; display: flex; flex-direction: column; box-shadow: 0 1px 3px rgba(16,24,40,.04); }
    .rod-mc-title { font-size: 10px; text-transform: uppercase; letter-spacing: 0.6px; color: var(--rmbz-text-faint, #9aa1ad); font-weight: 700; margin-bottom: 14px; }
    .rod-mc-empty { color: var(--rmbz-text-faint, #aaa); font-size: 12px; padding: 30px 0; text-align: center; flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; }
    .rod-mc-empty-ico { font-size: 26px; opacity: .6; }

    /* Ranking horizontal */
    .rod-mc-rows { display: flex; flex-direction: column; gap: 11px; }
    .rod-mc-row { display: grid; grid-template-columns: minmax(0, 110px) 1fr auto; gap: 12px; align-items: center; }
    .rod-mc-row.is-others { opacity: .72; }
    .rod-mc-name { display: flex; align-items: center; gap: 7px; font-size: 12px; color: #2b2f36; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
    .rod-mc-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
    .rod-mc-track { height: 9px; background: #eef0f3; border-radius: 999px; overflow: hidden; }
    .rod-mc-fill { display: block; height: 100%; border-radius: 999px; transform-origin: left; animation: rod-fill .6s cubic-bezier(.4,0,.2,1) both; }
    @keyframes rod-fill { from { transform: scaleX(0); } to { transform: scaleX(1); } }
    .rod-mc-amount { font-size: 12px; font-weight: 700; color: #16181d; white-space: nowrap; font-variant-numeric: tabular-nums; text-align: right; }
    .rod-mc-foot { margin-top: 13px; padding-top: 10px; border-top: 1px solid #f0f1f3; font-size: 11px; color: var(--rmbz-text-muted, #6b7280); }
    .rod-mc-foot strong { color: #16181d; }
    </style>
    <?php
}
