<?php
/**
 * [1.5.414] PAINEL VIP DESKTOP DO ARTISTA — layout novo, full-screen, M3.
 *
 * Novo layout do "minha-conta" para DESKTOP, exclusivo para ARTISTAS VIP
 * (subscrição ativa), em regime OPT-IN:
 *   - No painel clássico, o VIP vê o banner "✨ Experimentar o novo painel";
 *   - Ao ativar (extra_data['vip_desktop']=1 na carteira), o minha-conta
 *     passa a renderizar ESTE painel, que ocupa o ecrã todo (position:fixed);
 *   - Botão "Voltar ao painel antigo" desliga a qualquer momento;
 *   - Se a subscrição VIP expirar, volta automaticamente ao clássico.
 *
 * Design: Material 3, sidebar fixa à esquerda, 2 temas (OLED preto puro +
 * claro) com alternador guardado em localStorage, dourado 1MZ (#f0b90b),
 * tipografia Bricolage Grotesque + Geist + JetBrains Mono.
 *
 * Tudo usa os dados e endpoints REAIS já existentes:
 *   - Levantamento: admin-post rmbz_request_withdrawal (source=wallet,
 *     rmbz_payment_method mpesa/emola, rmbz_payment_details, valor) —
 *     fluxo em 3 passos no diálogo;
 *   - Depósito: admin-post rmbz_processar_deposito (form completo);
 *   - Chat do projeto: leitura rmbz_pchat_get_messages + envio
 *     admin-post onemz_update_feedback;
 *   - Saldos/VIP/projetos/releases/envios/notificações: mesmas queries
 *     do dashboard clássico.
 *
 * Local: includes/my-account-vip-desktop.php
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

// =============================================================================
// OPT-IN (guardado em wallets.extra_data['vip_desktop'])
// =============================================================================

function rmbz_vipdesk_enabled( $user_telemovel ) {
    global $wpdb;
    $raw = $wpdb->get_var( $wpdb->prepare(
        "SELECT extra_data FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s", $user_telemovel
    ) );
    $data = ! empty( $raw ) ? json_decode( $raw, true ) : [];
    return is_array( $data ) && ! empty( $data['vip_desktop'] );
}

function rmbz_vipdesk_set( $user_telemovel, $on ) {
    global $wpdb;
    $raw = $wpdb->get_var( $wpdb->prepare(
        "SELECT extra_data FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s", $user_telemovel
    ) );
    $data = ! empty( $raw ) ? json_decode( $raw, true ) : [];
    if ( ! is_array( $data ) ) $data = [];
    if ( $on ) { $data['vip_desktop'] = 1; } else { unset( $data['vip_desktop'] ); }
    $wpdb->update(
        $wpdb->prefix . 'rmbz_wallets',
        [ 'extra_data' => wp_json_encode( $data ) ],
        [ 'user_telemovel' => $user_telemovel ]
    );
}

/** O novo painel deve renderizar? (logado + VIP ativo + opt-in ligado) */
function rmbz_vipdesk_should_render() {
    if ( ! function_exists( 'rmbz_is_user_logged_in' ) || ! rmbz_is_user_logged_in() ) return false;
    $tel = rmbz_get_current_user_telemovel();
    if ( ! function_exists( 'rmbz_user_has_active_subscription' ) || ! rmbz_user_has_active_subscription( $tel ) ) return false;
    // First deposit gate tem prioridade — deixa o fluxo clássico tratar.
    if ( function_exists( 'rmbz_first_deposit_gate_is_blocked' ) && rmbz_first_deposit_gate_is_blocked( $tel ) ) return false;
    return rmbz_vipdesk_enabled( $tel );
}

/** Ligar/desligar o novo painel (admin-post). */
function rmbz_vipdesk_handle_toggle() {
    if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'rmbz_vipdesk_toggle' ) ) {
        wp_die( 'Falha de segurança!' );
    }
    if ( ! function_exists( 'rmbz_is_user_logged_in' ) || ! rmbz_is_user_logged_in() ) {
        rmbz_safe_redirect( home_url( '/minha-conta/' ) );
    }
    if ( session_status() === PHP_SESSION_NONE && ! headers_sent() ) { session_start(); }
    $tel = rmbz_get_current_user_telemovel();
    $on  = isset( $_POST['vipdesk_on'] ) && $_POST['vipdesk_on'] === '1';
    if ( $on && ( ! function_exists( 'rmbz_user_has_active_subscription' ) || ! rmbz_user_has_active_subscription( $tel ) ) ) {
        $_SESSION['rmbz_withdrawal_notice'] = [ 'error', 'O novo painel desktop é exclusivo para Artistas VIP com subscrição ativa.' ];
        rmbz_safe_redirect( home_url( '/minha-conta/' ) );
    }
    rmbz_vipdesk_set( $tel, $on );
    $_SESSION['rmbz_withdrawal_notice'] = $on
        ? [ 'success', '✨ Bem-vindo ao novo painel VIP desktop! Podes voltar ao antigo a qualquer momento.' ]
        : [ 'success', 'Voltaste ao painel clássico. O novo painel fica à tua espera no banner ✨.' ];
    rmbz_safe_redirect( home_url( '/minha-conta/' ) );
}
add_action( 'admin_post_rmbz_vipdesk_toggle', 'rmbz_vipdesk_handle_toggle' );
add_action( 'admin_post_nopriv_rmbz_vipdesk_toggle', 'rmbz_vipdesk_handle_toggle' );

/** Banner "Experimentar o novo painel" — só VIP, mostrado no painel clássico. */
function rmbz_vipdesk_render_banner() {
    if ( ! function_exists( 'rmbz_is_user_logged_in' ) || ! rmbz_is_user_logged_in() ) return;
    $tel = rmbz_get_current_user_telemovel();
    if ( ! function_exists( 'rmbz_user_has_active_subscription' ) || ! rmbz_user_has_active_subscription( $tel ) ) return;
    ?>
    <div style="max-width:1080px; margin:14px auto 0; padding:0 12px; box-sizing:border-box;">
        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
              style="display:flex; align-items:center; gap:12px; background:rgba(240,185,11,.10); border:1px solid rgba(240,185,11,.45); border-radius:100px; padding:10px 20px; flex-wrap:wrap;">
            <input type="hidden" name="action" value="rmbz_vipdesk_toggle">
            <input type="hidden" name="vipdesk_on" value="1">
            <?php wp_nonce_field( 'rmbz_vipdesk_toggle' ); ?>
            <span style="font-size:16px;">✨</span>
            <span style="flex:1; min-width:220px; font-size:13px; font-weight:600; color:#e8e4d4;">
                Novo <b style="color:#f0b90b;">painel VIP desktop</b> disponível — moderno, full-screen e exclusivo para Artistas VIP.
            </span>
            <button type="submit" style="border:0; background:#f0b90b; color:#0a0a0a; font-weight:800; font-size:12.5px; padding:9px 20px; border-radius:100px; cursor:pointer;">
                Experimentar agora
            </button>
        </form>
    </div>
    <?php
}

// =============================================================================
// HELPERS DE APRESENTAÇÃO
// =============================================================================

function rmbz_vipdesk_fmt( $v ) { return number_format( (float) $v, 2, ',', ' ' ); }

/** Chip de estado de PROJETO (label, é-done?, pct, índice do stepper). */
function rmbz_vipdesk_project_meta( $status ) {
    $map = [
        'pending_review'     => [ 'EM AVALIAÇÃO', 'brand', 0, 8 ],
        'approved'           => [ 'APROVADO', 'success', 1, 20 ],
        'kyc_review'         => [ 'KYC PENDENTE', 'brand', 1, 15 ],
        'pre-production'     => [ 'PRÉ-PRODUÇÃO', 'info', 1, 30 ],
        'filming'            => [ 'FILMAGEM', 'brand', 2, 55 ],
        'editing'            => [ 'EDIÇÃO', 'info', 3, 80 ],
        'done'               => [ 'ENTREGUE', 'success', 5, 100 ],
        'correction'         => [ 'CORREÇÃO', 'brand', 3, 75 ],
        'rejected'           => [ 'REJEITADO', 'danger', -1, 0 ],
        'cancelled_deadline' => [ 'CANCELADO', 'muted', -1, 0 ],
    ];
    return $map[ (string) $status ] ?? [ strtoupper( (string) $status ), 'muted', -1, 0 ];
}

/** Chip de estado de RELEASE de distribuição. */
function rmbz_vipdesk_release_meta( $status ) {
    $map = [
        'live'        => [ 'AO VIVO', 'success' ],
        'distribuido' => [ 'AO VIVO', 'success' ],
        'submitted'   => [ 'EM REVISÃO', 'brand' ],
        'pending'     => [ 'EM REVISÃO', 'brand' ],
        'in_review'   => [ 'EM REVISÃO', 'brand' ],
        'approved'    => [ 'AGENDADO', 'info' ],
        'scheduled'   => [ 'AGENDADO', 'info' ],
        'incomplete'  => [ 'RASCUNHO', 'muted' ],
        'returned'    => [ 'DEVOLVIDO', 'danger' ],
        'rejected'    => [ 'REJEITADO', 'danger' ],
    ];
    return $map[ (string) $status ] ?? [ strtoupper( (string) $status ), 'muted' ];
}

/** Chip de estado de ENVIO (submissões). */
function rmbz_vipdesk_submission_meta( $status ) {
    $s = strtolower( (string) $status );
    if ( strpos( $s, 'aprov' ) !== false || $s === 'publicado' ) return [ 'APROVADO', 'success' ];
    if ( strpos( $s, 'rejeit' ) !== false ) return [ 'REJEITADO', 'danger' ];
    return [ 'EM ANÁLISE', 'brand' ];
}

// =============================================================================
// RENDER — painel VIP desktop (full-screen)
// =============================================================================

function rmbz_vipdesk_render() {
    global $wpdb;
    $tel  = rmbz_get_current_user_telemovel();
    $user = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s", $tel ) );
    if ( ! $user ) { rmbz_render_dashboard_view(); return; }

    $notice = null;
    if ( isset( $_SESSION['rmbz_withdrawal_notice'] ) && is_array( $_SESSION['rmbz_withdrawal_notice'] ) ) {
        $notice = $_SESSION['rmbz_withdrawal_notice'];
        unset( $_SESSION['rmbz_withdrawal_notice'] );
    }

    // ── SALDOS ──
    $wallet_mt     = (float) ( $user->balance ?? 0 );
    $withdrawable  = function_exists( 'rmbz_get_withdrawable_balance' ) ? (float) rmbz_get_withdrawable_balance( $tel ) : 0.0;
    $promo_mt      = max( 0, $wallet_mt - $withdrawable );
    $distro_usd    = 0.0;
    $t_dstats = $wpdb->prefix . 'rmbz_distro_stats';
    if ( $wpdb->get_var( "SHOW TABLES LIKE '{$t_dstats}'" ) === $t_dstats ) {
        $distro_usd = (float) $wpdb->get_var( $wpdb->prepare( "SELECT total_earnings FROM {$t_dstats} WHERE artist_telemovel = %s", $tel ) );
    }
    $rate      = function_exists( 'rmbz_get_exchange_rate' ) ? (float) rmbz_get_exchange_rate() : (float) get_option( 'rmbz_exchange_rate', 63.50 );
    $total_mt  = $wallet_mt + $distro_usd * $rate;
    $min_wd    = defined( 'RMBZ_MIN_WITHDRAWAL' ) ? (float) RMBZ_MIN_WITHDRAWAL : 50.0;

    // ── VIP ──
    $days_left = 0; $expiry_br = '';
    if ( function_exists( 'rmbz_get_subscription_expiry' ) ) {
        $expiry = rmbz_get_subscription_expiry( $tel );
        if ( $expiry ) {
            $days_left = max( 0, (int) ceil( ( strtotime( $expiry ) - current_time( 'timestamp' ) ) / 86400 ) );
            $expiry_br = date_i18n( 'd/m/Y', strtotime( $expiry ) );
        }
    }

    // ── PROJETOS + sessão REC + próxima gravação ──
    $projects = $wpdb->get_results( $wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}rmbz_artist_projects WHERE artist_telemovel = %s ORDER BY contract_date DESC", $tel
    ) ) ?: [];
    if ( function_exists( 'rmbz_filming_project_hidden_from_artist' ) ) {
        $projects = array_values( array_filter( $projects, function ( $p ) {
            return ( $p->production_status ?? '' ) !== 'cancelled_no_confirmation' || ! rmbz_filming_project_hidden_from_artist( $p );
        } ) );
    }
    $live_project = null; $next_shoot = null; $hoje = current_time( 'Y-m-d' );
    foreach ( $projects as $p ) {
        $extra = ! empty( $p->extra_data ) ? json_decode( $p->extra_data, true ) : [];
        if ( ! is_array( $extra ) ) $extra = [];
        $p->rmbz_x = $extra;
        $sessions = ( isset( $extra['filming_sessions'] ) && is_array( $extra['filming_sessions'] ) ) ? $extra['filming_sessions'] : [];
        $day_n = 0; $p->rmbz_live = false;
        foreach ( $sessions as $s ) {
            if ( ! is_array( $s ) ) continue;
            $day_n++;
            if ( empty( $s['ended_at'] ) ) { $p->rmbz_live = true; $p->rmbz_live_day = $day_n; }
            if ( ! empty( $s['next_date'] ) && $s['next_date'] >= $hoje && ( ! $next_shoot || $s['next_date'] < $next_shoot['date'] ) ) {
                $next_shoot = [ 'date' => (string) $s['next_date'], 'titulo' => '«' . ( $p->project_title ?: 'Videoclipe' ) . '» — continuação da filmagem' ];
            }
        }
        $p->rmbz_days = $day_n;
        if ( $p->rmbz_live && ! $live_project ) $live_project = $p;
        $fs = (string) ( $extra['filming_start'] ?? '' );
        if ( $fs !== '' && $fs >= $hoje && $day_n === 0 && ! $p->rmbz_live && ( ! $next_shoot || $fs < $next_shoot['date'] ) ) {
            $next_shoot = [ 'date' => $fs, 'titulo' => '«' . ( $p->project_title ?: 'Videoclipe' ) . '» — início da filmagem' ];
        }
    }
    $active_project = null;
    foreach ( $projects as $p ) {
        if ( ! in_array( (string) $p->production_status, [ 'done', 'rejected', 'cancelled_deadline' ], true ) ) { $active_project = $p; break; }
    }
    if ( ! $active_project && ! empty( $projects ) ) $active_project = $projects[0];

    // ── CHAT do projeto ativo ──
    $chat_msgs = [];
    if ( $active_project && function_exists( 'rmbz_pchat_get_messages' ) ) {
        $all = rmbz_pchat_get_messages( (int) $active_project->id );
        if ( is_array( $all ) ) $chat_msgs = array_slice( $all, -30 );
    }

    // ── DISTRIBUIÇÃO ──
    $releases = [];
    $t_rel = $wpdb->prefix . 'rmbz_distro_releases';
    if ( $wpdb->get_var( "SHOW TABLES LIKE '{$t_rel}'" ) === $t_rel ) {
        $releases = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$t_rel} WHERE artist_telemovel = %s ORDER BY created_at DESC LIMIT 30", $tel
        ) ) ?: [];
    }
    $rel_live = 0;
    foreach ( $releases as $r ) { if ( in_array( (string) $r->status, [ 'live', 'distribuido' ], true ) ) $rel_live++; }

    // ── ENVIOS ──
    $submissions = $wpdb->get_results( $wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}rmbz_artist_submissions WHERE artist_telemovel = %s ORDER BY submission_date DESC LIMIT 20", $tel
    ) ) ?: [];

    // ── TRANSAÇÕES (últimos movimentos + ganhos por mês) ──
    $transactions = $wpdb->get_results( $wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}rmbz_wallet_transactions WHERE user_telemovel = %s ORDER BY transaction_date DESC LIMIT 8", $tel
    ) ) ?: [];
    $month_rows = $wpdb->get_results( $wpdb->prepare(
        "SELECT DATE_FORMAT(transaction_date,'%%Y-%%m') AS ym, SUM(amount) AS total
         FROM {$wpdb->prefix}rmbz_wallet_transactions
         WHERE user_telemovel = %s AND amount > 0 AND transaction_date >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
         GROUP BY ym ORDER BY ym ASC", $tel
    ) ) ?: [];
    $meses_pt = [ 1=>'JAN',2=>'FEV',3=>'MAR',4=>'ABR',5=>'MAI',6=>'JUN',7=>'JUL',8=>'AGO',9=>'SET',10=>'OUT',11=>'NOV',12=>'DEZ' ];
    $bars = []; $bar_max = 0;
    for ( $i = 5; $i >= 0; $i-- ) {
        $ym  = date( 'Y-m', strtotime( "-{$i} months", current_time( 'timestamp' ) ) );
        $val = 0.0;
        foreach ( $month_rows as $mr ) { if ( $mr->ym === $ym ) { $val = (float) $mr->total; break; } }
        $bar_max = max( $bar_max, $val );
        $bars[] = [ 'mes' => $meses_pt[ (int) date( 'n', strtotime( $ym . '-01' ) ) ], 'val' => $val ];
    }
    $ym_now = date( 'Y-m', current_time( 'timestamp' ) );
    $month_earn = 0.0;
    foreach ( $month_rows as $mr ) { if ( $mr->ym === $ym_now ) $month_earn = (float) $mr->total; }

    // ── PENDENTES (depósito/levantamento) ──
    $has_pending_wd  = (bool) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}rmbz_withdrawal_requests WHERE user_telemovel = %s AND status = 'pendente'", $tel ) );
    $has_pending_dep = (bool) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}rmbz_deposit_requests WHERE user_telemovel = %s AND status = 'pendente'", $tel ) );

    // ── NOTIFICAÇÕES ──
    $wpdb->suppress_errors = true;
    $notifs = [];
    if ( ! empty( $user->user_email ) && strpos( $user->user_email, '@1mz.local' ) === false ) {
        // [1.5.414] audience <> 'admin' — alertas do sistema nunca ao artista.
        $notifs = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}rmbz_email_logs
             WHERE recipient_email = %s AND is_cleared = 0 AND audience <> 'admin'
             AND subject NOT LIKE '%%Novo Depósito%%' AND subject NOT LIKE '%%Novo Levantamento%%'
             AND subject NOT LIKE '%%Nova Submissão%%' AND subject NOT LIKE '%%Novo Projeto%%'
             AND subject NOT LIKE '%%[Admin]%%'
             ORDER BY sent_date DESC LIMIT 15", $user->user_email
        ) );
    }
    $wpdb->suppress_errors = false;
    if ( ! is_array( $notifs ) ) $notifs = [];
    $unread = 0;
    foreach ( $notifs as $n ) { if ( isset( $n->is_read ) && (int) $n->is_read === 0 ) $unread++; }

    // ── CONQUISTAS derivadas de dados reais ──
    $done_projects = 0;
    foreach ( $projects as $p ) { if ( (string) $p->production_status === 'done' ) $done_projects++; }
    $conquistas = [
        [ '🎬', '1.º videoclipe', $done_projects > 0 ? 'desbloqueada' : 'por desbloquear', $done_projects > 0 ],
        [ '🌍', '1.º lançamento ao vivo', $rel_live > 0 ? 'desbloqueada' : 'por desbloquear', $rel_live > 0 ],
        [ '💿', '5 lançamentos', count( $releases ) >= 5 ? 'desbloqueada' : count( $releases ) . ' de 5', count( $releases ) >= 5 ],
        [ '💰', '1.º dólar de royalties', $distro_usd >= 1 ? 'desbloqueada' : 'por desbloquear', $distro_usd >= 1 ],
    ];

    // ── Config de pagamentos (depósito) ──
    $pset = get_option( 'rmbz_payment_settings' );
    $mpesa_number = isset( $pset['rmbz_mpesa_number'] ) ? (string) $pset['rmbz_mpesa_number'] : '';
    $emola_number = isset( $pset['rmbz_emola_number'] ) ? (string) $pset['rmbz_emola_number'] : '';

    $nome    = (string) ( $user->user_nome ?? 'Artista' );
    $inicial = mb_strtoupper( mb_substr( trim( $nome ) !== '' ? $nome : 'A', 0, 1 ) );
    $primeiro = trim( explode( ' ', trim( $nome ) )[0] ?: 'Artista' );
    $logout_url = wp_nonce_url( admin_url( 'admin-post.php?action=rmbz_logout' ), 'rmbz_logout_nonce' );
    $fmt = 'rmbz_vipdesk_fmt';
    $active_title = $active_project ? ( $active_project->project_title ?: 'Videoclipe' ) : '';

    $chip_css = [
        'brand'   => [ 'var(--vd-brand-soft)', 'var(--vd-brand-ink)' ],
        'success' => [ 'var(--vd-success-soft)', 'var(--vd-success)' ],
        'info'    => [ 'var(--vd-info-soft)', 'var(--vd-info)' ],
        'danger'  => [ 'var(--vd-danger-soft)', 'var(--vd-danger)' ],
        'muted'   => [ 'var(--vd-elev)', 'var(--vd-muted)' ],
    ];
    $steps_lbl = [ 'Avaliação', 'Pré-produção', 'Filmagem', 'Edição', 'Entrega' ];
    ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,400..800&family=Geist:wght@400..700&family=JetBrains+Mono:wght@500;600&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@20..48,300..600,0..1,0" rel="stylesheet">
    <style>
    .rmbz-vipd[data-theme="oled"]{
        --vd-bg:#000; --vd-surface:#0e0e11; --vd-elev:#17171b; --vd-hover:#1e1e23;
        --vd-border:#232329; --vd-border2:#2e2e35;
        --vd-text:#fafafa; --vd-text2:#c4c4cc; --vd-muted:#8a8a92;
        --vd-brand:#f0b90b; --vd-brand-soft:rgba(240,185,11,.12); --vd-on-brand:#0a0a0a; --vd-brand-ink:#f0b90b;
        --vd-success:#10b981; --vd-success-soft:rgba(16,185,129,.12);
        --vd-danger:#ef4444; --vd-danger-soft:rgba(239,68,68,.14);
        --vd-info:#3b82f6; --vd-info-soft:rgba(59,130,246,.14);
        --vd-navy:#2c3e50; --vd-vip1:#20392b; --vd-vip2:#1e2320; --vd-scrim:rgba(0,0,0,.7);
    }
    .rmbz-vipd[data-theme="claro"]{
        --vd-bg:#f6f4ee; --vd-surface:#fff; --vd-elev:#f1eee5; --vd-hover:#edeadf;
        --vd-border:#e4dfd1; --vd-border2:#d5cfbe;
        --vd-text:#171610; --vd-text2:#4c4840; --vd-muted:#86816f;
        --vd-brand:#f0b90b; --vd-brand-soft:rgba(240,185,11,.18); --vd-on-brand:#1c1500; --vd-brand-ink:#96770a;
        --vd-success:#0d9268; --vd-success-soft:rgba(16,185,129,.14);
        --vd-danger:#d92f2f; --vd-danger-soft:rgba(217,47,47,.10);
        --vd-info:#2563eb; --vd-info-soft:rgba(37,99,235,.10);
        --vd-navy:#2c3e50; --vd-vip1:#24513a; --vd-vip2:#1e2b23; --vd-scrim:rgba(23,22,16,.55);
    }
    .rmbz-vipd{ position:fixed; inset:0; z-index:99990; display:flex; background:var(--vd-bg); color:var(--vd-text);
        font-family:'Geist',system-ui,sans-serif; overflow:hidden; transition:background .25s; }
    .rmbz-vipd *{ box-sizing:border-box; }
    .rmbz-vipd .ms{ font-family:'Material Symbols Rounded'; font-weight:400; font-style:normal; line-height:1; display:inline-flex; vertical-align:middle; }
    .rmbz-vipd .mono{ font-family:'JetBrains Mono',monospace; }
    .rmbz-vipd .disp{ font-family:'Bricolage Grotesque',sans-serif; }
    .rmbz-vipd button{ cursor:pointer; font-family:inherit; }
    .rmbz-vipd a{ color:var(--vd-brand-ink); text-decoration:none; }
    .rmbz-vipd ::-webkit-scrollbar{ width:10px; } .rmbz-vipd ::-webkit-scrollbar-thumb{ background:var(--vd-border2); border-radius:8px; }
    @keyframes rmbzVdIn{ from{ opacity:0; transform:translateY(10px);} to{ opacity:1; transform:none;} }
    @keyframes rmbzVdPop{ from{ opacity:0; transform:scale(.95);} to{ opacity:1; transform:none;} }
    @keyframes rmbzVdRec{ 50%{ opacity:.25; } }
    .rmbz-vipd-side{ width:264px; flex-shrink:0; display:flex; flex-direction:column; padding:22px 14px 18px; border-right:1px solid var(--vd-border); background:var(--vd-surface); gap:3px; overflow-y:auto; }
    .rmbz-vipd-nav{ display:flex; align-items:center; gap:13px; width:100%; border:0; text-align:left; padding:12px 16px; border-radius:100px; background:transparent; color:var(--vd-text2); font-size:13.5px; font-weight:550; transition:background .15s; }
    .rmbz-vipd-nav:hover{ background:var(--vd-hover); }
    .rmbz-vipd-nav.on{ background:var(--vd-brand-soft); color:var(--vd-brand-ink); font-weight:700; }
    .rmbz-vipd-main{ flex:1; overflow-y:auto; }
    .rmbz-vipd-wrap{ max-width:1440px; margin:0 auto; padding:26px 38px 60px; }
    .rmbz-vipd-card{ background:var(--vd-surface); border:1px solid var(--vd-border); border-radius:26px; padding:24px 28px; }
    .rmbz-vipd-sect{ font-size:12px; font-weight:750; letter-spacing:.07em; color:var(--vd-brand-ink); display:flex; align-items:center; gap:8px; }
    .rmbz-vipd-chip{ font-size:10.5px; font-weight:750; padding:5px 12px; border-radius:100px; white-space:nowrap; display:inline-block; }
    .rmbz-vipd-pill{ display:inline-flex; align-items:center; gap:8px; border-radius:100px; border:0; font-weight:700; }
    .rmbz-vipd-pill--brand{ background:var(--vd-brand); color:var(--vd-on-brand); }
    .rmbz-vipd-pill--brand:hover{ background:#d4a000; }
    .rmbz-vipd-pill--ghost{ background:transparent; border:1px solid var(--vd-border); color:var(--vd-brand-ink); }
    .rmbz-vipd-pill--ghost:hover{ background:var(--vd-hover); }
    .rmbz-vipd-panel{ animation:rmbzVdIn .35s ease; }
    .rmbz-vipd-notice{ border-radius:16px; padding:13px 18px; font-size:13px; font-weight:650; margin-bottom:16px; }
    .rmbz-vipd-notice.error{ background:var(--vd-danger-soft); border:1px solid var(--vd-danger); color:var(--vd-danger); }
    .rmbz-vipd-notice.success{ background:var(--vd-success-soft); border:1px solid var(--vd-success); color:var(--vd-success); }
    .rmbz-vipd-scrim{ position:fixed; inset:0; background:var(--vd-scrim); display:none; align-items:center; justify-content:center; z-index:99999; padding:16px; }
    .rmbz-vipd-scrim.open{ display:flex; }
    .rmbz-vipd-dialog{ background:var(--vd-surface); border:1px solid var(--vd-border); border-radius:28px; width:460px; max-width:100%; max-height:92vh; overflow-y:auto; padding:26px 30px; color:var(--vd-text); animation:rmbzVdPop .25s ease; }
    .rmbz-vipd-input{ width:100%; background:var(--vd-elev); border:1.5px solid var(--vd-border2); border-radius:14px; padding:12px 16px; font-size:14px; color:var(--vd-text); font-weight:600; }
    .rmbz-vipd-input:focus{ border-color:var(--vd-brand); outline:none; }
    .rmbz-vipd-label{ display:block; font-size:11px; font-weight:750; color:var(--vd-muted); letter-spacing:.06em; text-transform:uppercase; margin:14px 0 6px; }
    .rmbz-vipd-step{ display:none; } .rmbz-vipd-step.on{ display:block; }
    .rmbz-vipd-met{ display:flex; align-items:center; gap:14px; width:100%; border:2px solid var(--vd-border); background:var(--vd-elev); border-radius:18px; padding:14px 16px; text-align:left; margin-bottom:10px; }
    .rmbz-vipd-met.on{ border-color:var(--vd-brand); background:var(--vd-brand-soft); }
    .rmbz-vipd-rec{ color:var(--vd-danger); font-weight:800; }
    .rmbz-vipd-rec .dot{ display:inline-block; width:8px; height:8px; border-radius:50%; background:var(--vd-danger); animation:rmbzVdRec 1s infinite; }
    .rmbz-vipd [hidden]{ display:none !important; }
    @media (max-width:1100px){ .rmbz-vipd-grid2, .rmbz-vipd-grid3, .rmbz-vipd-grid21{ grid-template-columns:1fr !important; } }
    </style>

    <div class="rmbz-vipd" id="rmbz-vipd" data-theme="oled">
        <!-- ═══ SIDEBAR ═══ -->
        <aside class="rmbz-vipd-side">
            <div style="display:flex; align-items:center; gap:12px; padding:4px 12px 20px;">
                <img src="<?php echo esc_url( RMBZ_PLUGIN_URL . 'assets/pwa/icon-192.png' ); ?>" alt="1MZ" style="width:42px; height:42px; border-radius:12px; background:#fff;">
                <div>
                    <div class="disp" style="font-size:17px; font-weight:750;">1MZ RECORDS</div>
                    <div style="font-size:11px; color:var(--vd-muted); font-weight:500;">Painel do Artista · Desktop</div>
                </div>
            </div>
            <?php
            $tabs = [
                'inicio'   => [ 'dashboard', 'Início' ],
                'projetos' => [ 'movie', 'Videoclipes' ],
                'distro'   => [ 'public', 'Distribuição' ],
                'envios'   => [ 'upload', 'Envios' ],
                'stats'    => [ 'monitoring', 'Estatísticas' ],
                'notifs'   => [ 'notifications', 'Notificações' ],
                'perfil'   => [ 'person', 'Perfil & VIP' ],
            ];
            $first = true;
            foreach ( $tabs as $tk => $tv ): ?>
                <button type="button" class="rmbz-vipd-nav<?php echo $first ? ' on' : ''; ?>" data-tab="<?php echo esc_attr( $tk ); ?>">
                    <span class="ms" style="font-size:21px;"><?php echo esc_html( $tv[0] ); ?></span>
                    <span style="flex:1;"><?php echo esc_html( $tv[1] ); ?></span>
                    <?php if ( $tk === 'notifs' && $unread > 0 ): ?>
                        <span style="background:var(--vd-danger); color:#fff; font-size:10.5px; font-weight:700; border-radius:100px; padding:2px 8px;"><?php echo (int) $unread; ?></span>
                    <?php endif; ?>
                </button>
            <?php $first = false; endforeach; ?>

            <div style="flex:1;"></div>

            <div style="background:linear-gradient(135deg,var(--vd-vip1),var(--vd-vip2)); border-radius:18px; padding:16px 18px; margin-bottom:12px;">
                <div style="display:flex; align-items:center; gap:8px; font-size:12px; font-weight:750; color:#fff; letter-spacing:.06em;">
                    <span class="ms" style="font-size:18px; color:#f0b90b; font-variation-settings:'FILL' 1;">workspace_premium</span> ARTISTA VIP ATIVO
                </div>
                <div style="font-size:11.5px; color:rgba(255,255,255,.75); margin-top:5px;">
                    <?php echo $expiry_br !== '' ? 'Renova a ' . esc_html( $expiry_br ) . ' · ' . (int) $days_left . ' dias restantes' : 'Subscrição ativa'; ?>
                </div>
            </div>

            <button type="button" id="rmbz-vipd-theme" style="display:flex; align-items:center; gap:12px; border:1px solid var(--vd-border); background:var(--vd-elev); color:var(--vd-text2); font-size:12.5px; font-weight:600; padding:11px 16px; border-radius:100px;">
                <span class="ms" style="font-size:19px;" id="rmbz-vipd-theme-ic">light_mode</span>
                <span id="rmbz-vipd-theme-lb">Tema claro</span>
            </button>

            <div style="display:flex; align-items:center; gap:11px; padding:12px 12px 4px; margin-top:6px;">
                <div style="width:38px; height:38px; border-radius:50%; background:var(--vd-brand); color:var(--vd-on-brand); display:flex; align-items:center; justify-content:center; font-weight:800; font-size:14px; flex-shrink:0;"><?php echo esc_html( $inicial ); ?></div>
                <div style="min-width:0; flex:1;">
                    <div style="font-size:13px; font-weight:650; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;"><?php echo esc_html( $nome ); ?></div>
                    <div style="font-size:11px; color:var(--vd-muted);">+258 <?php echo esc_html( $tel ? substr( preg_replace( '/\D+/', '', $tel ), -9 ) : '' ); ?></div>
                </div>
                <a href="<?php echo esc_url( $logout_url ); ?>" title="Sair" style="display:flex;"><span class="ms" style="font-size:19px; color:var(--vd-muted);">logout</span></a>
            </div>
        </aside>

        <!-- ═══ MAIN ═══ -->
        <main class="rmbz-vipd-main">
            <div class="rmbz-vipd-wrap">

                <!-- banner voltar -->
                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
                      style="display:flex; align-items:center; gap:12px; background:var(--vd-brand-soft); border:1px solid var(--vd-brand); border-radius:100px; padding:9px 20px; margin-bottom:22px; font-size:12.5px; font-weight:600; color:var(--vd-text2);">
                    <input type="hidden" name="action" value="rmbz_vipdesk_toggle">
                    <input type="hidden" name="vipdesk_on" value="0">
                    <?php wp_nonce_field( 'rmbz_vipdesk_toggle' ); ?>
                    <span style="font-size:15px;">✨</span>
                    <span style="flex:1;">Estás a experimentar o <b style="color:var(--vd-brand-ink);">novo painel VIP desktop</b> — exclusivo para Artistas VIP.</span>
                    <button type="submit" style="border:0; background:none; color:var(--vd-brand-ink); font-size:12.5px; font-weight:700; text-decoration:underline;">Voltar ao painel antigo</button>
                </form>

                <?php if ( $notice ): ?>
                    <div class="rmbz-vipd-notice <?php echo esc_attr( $notice[0] ); ?>"><?php echo esc_html( $notice[1] ); ?></div>
                <?php endif; ?>

                <!-- topbar -->
                <header style="display:flex; align-items:center; justify-content:space-between; margin-bottom:26px; gap:16px; flex-wrap:wrap;">
                    <div>
                        <h1 class="disp" style="margin:0; font-size:30px; font-weight:650; letter-spacing:-.01em; color:var(--vd-text);" id="rmbz-vipd-title">Olá, <?php echo esc_html( $primeiro ); ?> 👋🏾</h1>
                        <div style="font-size:13px; color:var(--vd-muted); margin-top:4px;" id="rmbz-vipd-sub">Bem-vindo ao teu painel VIP.</div>
                    </div>
                    <div style="display:flex; align-items:center; gap:10px;">
                        <div style="display:flex; align-items:center; gap:9px; background:var(--vd-elev); border:1px solid var(--vd-border); border-radius:100px; padding:9px 18px; font-size:12.5px; font-weight:600; color:var(--vd-text2);">
                            <span class="ms" style="font-size:17px;">calendar_today</span>
                            <?php echo esc_html( date_i18n( 'l, d M Y' ) ); ?>
                        </div>
                        <button type="button" data-goto="notifs" style="position:relative; width:42px; height:42px; border-radius:50%; border:1px solid var(--vd-border); background:var(--vd-elev); color:var(--vd-text2); display:flex; align-items:center; justify-content:center;">
                            <span class="ms" style="font-size:20px;">notifications</span>
                            <?php if ( $unread > 0 ): ?><span style="position:absolute; top:8px; right:9px; width:8px; height:8px; border-radius:50%; background:var(--vd-danger);"></span><?php endif; ?>
                        </button>
                    </div>
                </header>

                <!-- ═════ INÍCIO ═════ -->
                <section class="rmbz-vipd-panel" data-panel="inicio" data-screen-label="Início" style="display:flex; flex-direction:column; gap:20px;">
                    <div class="rmbz-vipd-grid3" style="display:grid; grid-template-columns:1.5fr 1fr 1fr; gap:20px;">
                        <div style="background:var(--vd-navy); border-radius:26px; padding:26px 30px; color:#fff;">
                            <div style="font-size:12px; font-weight:700; letter-spacing:.08em; color:rgba(255,255,255,.7); display:flex; align-items:center; gap:8px;">
                                <span class="ms" style="font-size:18px;">account_balance_wallet</span> PATRIMÓNIO TOTAL
                            </div>
                            <div class="mono" style="font-size:42px; font-weight:600; letter-spacing:-.02em; margin:10px 0 16px;"><?php echo esc_html( $fmt( $total_mt ) ); ?> <span style="font-size:20px; color:rgba(255,255,255,.65);">MT</span></div>
                            <div style="display:flex; gap:10px; flex-wrap:wrap;">
                                <button type="button" id="rmbz-vipd-open-dep" class="rmbz-vipd-pill rmbz-vipd-pill--brand" style="font-size:13.5px; font-weight:750; padding:12px 24px;">
                                    <span class="ms" style="font-size:19px;">add_circle</span> Depositar
                                </button>
                                <button type="button" id="rmbz-vipd-open-wd" class="rmbz-vipd-pill" style="background:rgba(255,255,255,.14); color:#fff; font-size:13.5px; padding:12px 24px;">
                                    <span class="ms" style="font-size:19px;">payments</span> Levantar
                                </button>
                            </div>
                        </div>
                        <div class="rmbz-vipd-card" style="padding:24px 26px;">
                            <div style="font-size:11.5px; font-weight:700; letter-spacing:.07em; color:var(--vd-muted);">SALDO RETIRÁVEL</div>
                            <div class="mono" style="font-size:26px; font-weight:600; margin:8px 0 4px;"><?php echo esc_html( $fmt( $withdrawable ) ); ?> MT</div>
                            <div style="font-size:12px; color:var(--vd-muted);"><?php echo $promo_mt > 0 ? '+ ' . esc_html( $fmt( $promo_mt ) ) . ' MT em saldo promocional' : 'Todo o saldo é retirável'; ?></div>
                            <?php if ( $has_pending_wd ): ?>
                                <div style="margin-top:14px; font-size:12px; font-weight:650; color:var(--vd-brand-ink); display:flex; align-items:center; gap:6px;"><span class="ms" style="font-size:16px;">hourglass_top</span> Levantamento pendente em processamento</div>
                            <?php elseif ( $month_earn > 0 ): ?>
                                <div style="margin-top:14px; font-size:12px; font-weight:650; color:var(--vd-success); display:flex; align-items:center; gap:6px;"><span class="ms" style="font-size:16px;">trending_up</span> +<?php echo esc_html( $fmt( $month_earn ) ); ?> MT este mês</div>
                            <?php endif; ?>
                        </div>
                        <div class="rmbz-vipd-card" style="padding:24px 26px;">
                            <div style="font-size:11.5px; font-weight:700; letter-spacing:.07em; color:var(--vd-muted);">ROYALTIES · DISTRIBUIÇÃO</div>
                            <div class="mono" style="font-size:26px; font-weight:600; margin:8px 0 4px;">$ <?php echo esc_html( number_format( $distro_usd, 2, ',', ' ' ) ); ?> USD</div>
                            <div style="font-size:12px; color:var(--vd-muted);">≈ <?php echo esc_html( $fmt( $distro_usd * $rate ) ); ?> MT (câmbio <?php echo esc_html( number_format( $rate, 2, ',', '' ) ); ?>)</div>
                            <button type="button" data-goto="distro" style="margin-top:12px; border:0; background:none; padding:0; color:var(--vd-brand-ink); font-size:12.5px; font-weight:700; display:flex; align-items:center; gap:4px;">Ver distribuição <span class="ms" style="font-size:16px;">chevron_right</span></button>
                        </div>
                    </div>

                    <?php if ( $active_project ):
                        [ $pl, $pk, $pidx, $ppct ] = rmbz_vipdesk_project_meta( $active_project->production_status );
                        [ $pbg, $pfg ] = $chip_css[ $pk ] ?? $chip_css['muted']; ?>
                    <div class="rmbz-vipd-grid21" style="display:grid; grid-template-columns:1.6fr 1fr; gap:20px;">
                        <div class="rmbz-vipd-card" style="padding:26px 28px;">
                            <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:18px; gap:12px; flex-wrap:wrap;">
                                <div class="rmbz-vipd-sect"><span class="ms" style="font-size:18px;">movie</span> O TEU VIDEOCLIPE</div>
                                <?php if ( ! empty( $active_project->rmbz_live ) ): ?>
                                    <span class="rmbz-vipd-rec" style="display:flex; align-items:center; gap:6px; font-size:11.5px;"><span class="dot"></span> REC — GRAVAÇÃO AGORA</span>
                                <?php else: ?>
                                    <span class="rmbz-vipd-chip" style="background:<?php echo $pbg; ?>; color:<?php echo $pfg; ?>;"><?php echo esc_html( $pl ); ?></span>
                                <?php endif; ?>
                            </div>
                            <div class="disp" style="font-size:22px; font-weight:700;">«<?php echo esc_html( $active_title ); ?>»</div>
                            <div style="font-size:13px; color:var(--vd-muted); margin:4px 0 20px;">
                                <?php
                                $bits = [];
                                if ( ! empty( $active_project->rmbz_live ) ) $bits[] = 'Dia ' . (int) ( $active_project->rmbz_live_day ?? 1 ) . ' de filmagem a decorrer';
                                elseif ( (int) $active_project->rmbz_days > 0 ) $bits[] = (int) $active_project->rmbz_days . ' dia(s) filmado(s)';
                                if ( ! empty( $active_project->rmbz_x['filming_start'] ) ) $bits[] = 'filmagem: ' . (string) $active_project->rmbz_x['filming_start'];
                                echo esc_html( ! empty( $bits ) ? implode( ' · ', $bits ) : 'Acompanha aqui cada fase da produção.' );
                                ?>
                            </div>
                            <div style="display:flex; align-items:center;">
                                <?php foreach ( $steps_lbl as $i => $lbl ):
                                    $done = $pidx > $i || (string) $active_project->production_status === 'done';
                                    $act  = $pidx === $i && (string) $active_project->production_status !== 'done'; ?>
                                    <div style="display:flex; align-items:center; flex:<?php echo $i < 4 ? '1' : '0'; ?>;">
                                        <div style="display:flex; flex-direction:column; align-items:center; gap:7px; min-width:68px;">
                                            <div class="ms" style="width:34px; height:34px; border-radius:50%; align-items:center; justify-content:center; font-size:17px; font-variation-settings:'FILL' 1;
                                                background:<?php echo $done ? 'var(--vd-success-soft)' : ( $act ? 'var(--vd-brand)' : 'var(--vd-elev)' ); ?>;
                                                color:<?php echo $done ? 'var(--vd-success)' : ( $act ? 'var(--vd-on-brand)' : 'var(--vd-muted)' ); ?>;
                                                border:2px solid <?php echo $act ? 'var(--vd-brand)' : 'transparent'; ?>;">
                                                <?php echo $done ? 'check' : [ 'search', 'construction', 'videocam', 'content_cut', 'flag' ][ $i ]; ?>
                                            </div>
                                            <div style="font-size:10.5px; font-weight:650; color:<?php echo ( $done || $act ) ? 'var(--vd-text2)' : 'var(--vd-muted)'; ?>; white-space:nowrap;"><?php echo esc_html( $lbl ); ?></div>
                                        </div>
                                        <?php if ( $i < 4 ): ?>
                                            <div style="flex:1; height:3px; border-radius:3px; background:<?php echo $done ? 'var(--vd-success)' : 'var(--vd-border2)'; ?>; margin:0 4px 20px;"></div>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="rmbz-vipd-card" style="padding:24px 26px; display:flex; flex-direction:column;">
                            <div class="rmbz-vipd-sect" style="margin-bottom:14px;"><span class="ms" style="font-size:18px;">forum</span> CHAT DO PROJETO</div>
                            <?php
                            $preview = array_slice( $chat_msgs, -2 );
                            if ( empty( $preview ) ): ?>
                                <div style="font-size:12.5px; color:var(--vd-muted);">Ainda sem mensagens — escreve à equipa na aba Videoclipes.</div>
                            <?php else: foreach ( $preview as $mmsg ):
                                $mine = strpos( strtolower( (string) ( $mmsg['author_type'] ?? '' ) ), 'art' ) === 0; ?>
                                <div style="background:<?php echo $mine ? 'var(--vd-brand-soft)' : 'var(--vd-elev)'; ?>; border-radius:<?php echo $mine ? '16px 16px 4px 16px' : '16px 16px 16px 4px'; ?>; padding:11px 15px; font-size:12.5px; color:var(--vd-text2); margin-bottom:8px; <?php echo $mine ? 'margin-left:28px;' : ''; ?>">
                                    <?php echo esc_html( wp_trim_words( wp_strip_all_tags( (string) ( $mmsg['body'] ?? '' ) ), 22, '…' ) ); ?>
                                </div>
                            <?php endforeach; endif; ?>
                            <div style="flex:1;"></div>
                            <button type="button" data-goto="projetos" class="rmbz-vipd-pill rmbz-vipd-pill--ghost" style="margin-top:14px; font-size:12.5px; padding:11px; justify-content:center;">Abrir conversa completa</button>
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="rmbz-vipd-grid2" style="display:grid; grid-template-columns:1fr 1fr; gap:20px;">
                        <div class="rmbz-vipd-card">
                            <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:16px;">
                                <div class="rmbz-vipd-sect">🌍 DISTRIBUIÇÃO — RELEASES</div>
                                <button type="button" data-goto="distro" style="border:0; background:none; color:var(--vd-brand-ink); font-size:12px; font-weight:700;">Ver tudo</button>
                            </div>
                            <?php if ( empty( $releases ) ): ?>
                                <div style="font-size:12.5px; color:var(--vd-muted);">Ainda não tens lançamentos na distribuição digital.</div>
                            <?php else: foreach ( array_slice( $releases, 0, 3 ) as $r ):
                                [ $rl, $rk ] = rmbz_vipdesk_release_meta( $r->status );
                                [ $rbg, $rfg ] = $chip_css[ $rk ] ?? $chip_css['muted']; ?>
                                <div style="display:flex; align-items:center; gap:14px; padding:11px 0; border-bottom:1px solid var(--vd-border);">
                                    <?php if ( ! empty( $r->cover_image ) ): ?>
                                        <img src="<?php echo esc_url( $r->cover_image ); ?>" alt="" style="width:44px; height:44px; border-radius:10px; object-fit:cover; border:1px solid var(--vd-border); flex-shrink:0;">
                                    <?php else: ?>
                                        <div style="width:44px; height:44px; border-radius:10px; background:repeating-linear-gradient(45deg,var(--vd-elev),var(--vd-elev) 6px,var(--vd-hover) 6px,var(--vd-hover) 12px); border:1px solid var(--vd-border); flex-shrink:0; display:flex; align-items:center; justify-content:center; font-size:8px; color:var(--vd-muted);" class="mono">capa</div>
                                    <?php endif; ?>
                                    <div style="flex:1; min-width:0;">
                                        <div style="font-size:13.5px; font-weight:650;"><?php echo esc_html( $r->title ); ?></div>
                                        <div style="font-size:11.5px; color:var(--vd-muted);"><?php echo esc_html( ucfirst( (string) $r->release_type ) . ( $r->release_date ? ' · ' . date_i18n( 'd/m/Y', strtotime( $r->release_date ) ) : '' ) ); ?></div>
                                    </div>
                                    <span class="rmbz-vipd-chip" style="background:<?php echo $rbg; ?>; color:<?php echo $rfg; ?>;"><?php echo esc_html( $rl ); ?></span>
                                </div>
                            <?php endforeach; endif; ?>
                        </div>
                        <div class="rmbz-vipd-card">
                            <div class="rmbz-vipd-sect" style="margin-bottom:16px;">📈 RESUMO</div>
                            <div style="display:grid; grid-template-columns:repeat(3,1fr); gap:14px;">
                                <div style="background:var(--vd-elev); border-radius:18px; padding:16px;"><div class="mono" style="font-size:22px; font-weight:600;"><?php echo esc_html( $fmt( $month_earn ) ); ?></div><div style="font-size:11px; color:var(--vd-muted); font-weight:600; margin-top:3px;">GANHOS MT (MÊS)</div></div>
                                <div style="background:var(--vd-elev); border-radius:18px; padding:16px;"><div class="mono" style="font-size:22px; font-weight:600;"><?php echo (int) $rel_live; ?></div><div style="font-size:11px; color:var(--vd-muted); font-weight:600; margin-top:3px;">RELEASES AO VIVO</div></div>
                                <div style="background:var(--vd-elev); border-radius:18px; padding:16px;"><div class="mono" style="font-size:22px; font-weight:600;"><?php echo count( $projects ); ?></div><div style="font-size:11px; color:var(--vd-muted); font-weight:600; margin-top:3px;">VIDEOCLIPES</div></div>
                            </div>
                            <?php if ( $next_shoot ): ?>
                                <div style="display:flex; align-items:center; gap:10px; margin-top:16px; background:var(--vd-brand-soft); border-radius:14px; padding:12px 16px;">
                                    <span style="font-size:18px;">🎬</span>
                                    <div style="font-size:12.5px; color:var(--vd-text2);"><b style="color:var(--vd-text);">Próxima gravação <?php echo esc_html( date_i18n( 'd/m', strtotime( $next_shoot['date'] . ' 12:00' ) ) ); ?>:</b> <?php echo esc_html( $next_shoot['titulo'] ); ?></div>
                                </div>
                            <?php endif; ?>
                            <?php if ( ! empty( $transactions ) ): ?>
                                <div style="margin-top:16px; border-top:1px solid var(--vd-border); padding-top:6px;">
                                <?php foreach ( array_slice( $transactions, 0, 3 ) as $tx ):
                                    $pos = (float) $tx->amount > 0; ?>
                                    <div style="display:flex; align-items:center; gap:12px; padding:9px 0;">
                                        <span class="ms" style="font-size:17px; width:32px; height:32px; border-radius:50%; align-items:center; justify-content:center; background:<?php echo $pos ? 'var(--vd-success-soft)' : 'var(--vd-elev)'; ?>; color:<?php echo $pos ? 'var(--vd-success)' : 'var(--vd-muted)'; ?>;"><?php echo $pos ? 'south_west' : 'north_east'; ?></span>
                                        <div style="flex:1; min-width:0; font-size:12px; color:var(--vd-text2); white-space:nowrap; overflow:hidden; text-overflow:ellipsis;"><?php echo esc_html( wp_strip_all_tags( (string) ( $tx->details ?: $tx->transaction_type ) ) ); ?></div>
                                        <span class="mono" style="font-size:12.5px; font-weight:600; color:<?php echo $pos ? 'var(--vd-success)' : 'var(--vd-text)'; ?>;"><?php echo ( $pos ? '+ ' : '− ' ) . esc_html( $fmt( abs( (float) $tx->amount ) ) ); ?> MT</span>
                                    </div>
                                <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </section>

                <!-- ═════ VIDEOCLIPES ═════ -->
                <section class="rmbz-vipd-panel rmbz-vipd-grid21" data-panel="projetos" data-screen-label="Videoclipes" hidden style="display:grid; grid-template-columns:1.5fr 1fr; gap:20px; align-items:start;">
                    <div style="display:flex; flex-direction:column; gap:18px;">
                        <?php if ( empty( $projects ) ): ?>
                            <div class="rmbz-vipd-card" style="text-align:center;">
                                <div style="font-size:40px; opacity:.4;">🎥</div>
                                <p style="margin:6px 0 0; font-weight:700;">Ainda não tens projetos de videoclipe.</p>
                                <p style="font-size:12.5px; color:var(--vd-muted); margin:4px 0 0;">Envia uma música na aba Envios para começar.</p>
                            </div>
                        <?php else: foreach ( $projects as $p ):
                            [ $pl, $pk, $pidx, $ppct ] = rmbz_vipdesk_project_meta( $p->production_status );
                            [ $pbg, $pfg ] = $chip_css[ $pk ] ?? $chip_css['muted']; ?>
                            <div class="rmbz-vipd-card" style="padding:26px 28px;">
                                <div style="display:flex; justify-content:space-between; align-items:flex-start; gap:12px;">
                                    <div>
                                        <div class="disp" style="font-size:20px; font-weight:700;">«<?php echo esc_html( $p->project_title ?: 'Videoclipe' ); ?>»</div>
                                        <div style="font-size:12.5px; color:var(--vd-muted); margin-top:3px;">
                                            Contrato: <?php echo esc_html( date_i18n( 'd/m/Y', strtotime( $p->contract_date ) ) ); ?>
                                            <?php if ( (float) $p->scenario_cost > 0 ): ?> · orçamento <?php echo esc_html( $fmt( $p->scenario_cost ) ); ?> MT<?php endif; ?>
                                            <?php if ( ! empty( $p->rmbz_live ) ): ?> · <span class="rmbz-vipd-rec"><span class="dot"></span> REC agora</span><?php endif; ?>
                                        </div>
                                    </div>
                                    <span class="rmbz-vipd-chip" style="background:<?php echo $pbg; ?>; color:<?php echo $pfg; ?>;"><?php echo esc_html( $pl ); ?></span>
                                </div>
                                <div style="height:8px; background:var(--vd-elev); border-radius:100px; overflow:hidden; margin:18px 0 8px;">
                                    <div style="height:100%; width:<?php echo (int) $ppct; ?>%; background:var(--vd-brand); border-radius:100px;"></div>
                                </div>
                                <div style="display:flex; justify-content:space-between; font-size:12px; color:var(--vd-muted);">
                                    <span><?php echo (int) $p->rmbz_days > 0 ? (int) $p->rmbz_days . ' dia(s) de filmagem' : esc_html( ucfirst( str_replace( '-', ' ', (string) $p->production_status ) ) ); ?></span>
                                    <span style="font-weight:700; color:var(--vd-text2);"><?php echo (int) $ppct; ?>%</span>
                                </div>
                                <?php if ( ! empty( $p->youtube_url ) || ! empty( $p->final_video_url ) ): ?>
                                    <a href="<?php echo esc_url( $p->youtube_url ?: $p->final_video_url ); ?>" target="_blank" class="rmbz-vipd-pill rmbz-vipd-pill--ghost" style="margin-top:14px; font-size:12.5px; padding:10px 20px;">
                                        <span class="ms" style="font-size:17px;">play_circle</span> Ver vídeo final
                                    </a>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; endif; ?>
                        <div style="font-size:12px; color:var(--vd-muted); text-align:center;">Para ações do contrato (aceitar, pagar, datas), usa o <a href="#" data-classic>painel clássico</a>.</div>
                    </div>

                    <div class="rmbz-vipd-card" style="padding:0; display:flex; flex-direction:column; height:560px;">
                        <div style="padding:18px 24px; border-bottom:1px solid var(--vd-border); display:flex; align-items:center; gap:10px;">
                            <span class="ms" style="font-size:20px; color:var(--vd-brand-ink);">forum</span>
                            <div>
                                <div style="font-size:14px; font-weight:700;">Chat — «<?php echo esc_html( $active_title ?: 'Projeto' ); ?>»</div>
                                <div style="font-size:11px; color:var(--vd-success); font-weight:650;">Equipa 1MZ</div>
                            </div>
                        </div>
                        <div style="flex:1; overflow-y:auto; padding:18px 22px; display:flex; flex-direction:column; gap:9px;" id="rmbz-vipd-chatbox">
                            <?php if ( empty( $chat_msgs ) ): ?>
                                <div style="font-size:12.5px; color:var(--vd-muted); text-align:center; margin-top:20px;">Ainda sem mensagens neste projeto.</div>
                            <?php else: foreach ( $chat_msgs as $mmsg ):
                                $mine = strpos( strtolower( (string) ( $mmsg['author_type'] ?? '' ) ), 'art' ) === 0; ?>
                                <div style="align-self:<?php echo $mine ? 'flex-end' : 'flex-start'; ?>; max-width:82%; background:<?php echo $mine ? 'var(--vd-brand-soft)' : 'var(--vd-elev)'; ?>; color:var(--vd-text); border-radius:<?php echo $mine ? '16px 16px 4px 16px' : '16px 16px 16px 4px'; ?>; padding:10px 15px; font-size:12.5px; line-height:1.5;">
                                    <?php echo esc_html( wp_strip_all_tags( (string) ( $mmsg['body'] ?? '' ) ) ); ?>
                                    <div style="font-size:10px; color:var(--vd-muted); margin-top:4px;"><?php echo esc_html( (string) ( $mmsg['created_at_label'] ?? '' ) ); ?></div>
                                </div>
                            <?php endforeach; endif; ?>
                        </div>
                        <?php if ( $active_project ): ?>
                        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="padding:14px 18px; border-top:1px solid var(--vd-border); display:flex; gap:10px;">
                            <input type="hidden" name="action" value="onemz_update_feedback">
                            <input type="hidden" name="project_id" value="<?php echo (int) $active_project->id; ?>">
                            <?php wp_nonce_field( 'onemz_update_feedback_nonce' ); ?>
                            <input name="artist_feedback" placeholder="Escreve uma mensagem…" required
                                   style="flex:1; border:1px solid var(--vd-border); background:var(--vd-elev); color:var(--vd-text); border-radius:100px; padding:12px 18px; font-size:13px; outline:none; min-width:0;">
                            <button type="submit" style="width:44px; height:44px; border-radius:50%; border:0; background:var(--vd-brand); color:var(--vd-on-brand); display:flex; align-items:center; justify-content:center; flex-shrink:0;">
                                <span class="ms" style="font-size:20px;">send</span>
                            </button>
                        </form>
                        <?php endif; ?>
                    </div>
                </section>

                <!-- ═════ DISTRIBUIÇÃO ═════ -->
                <section class="rmbz-vipd-panel" data-panel="distro" data-screen-label="Distribuição" hidden style="display:flex; flex-direction:column; gap:20px;">
                    <div class="rmbz-vipd-grid3" style="display:grid; grid-template-columns:repeat(3,1fr); gap:20px;">
                        <div class="rmbz-vipd-card" style="padding:22px 26px;"><div style="font-size:11.5px; font-weight:700; color:var(--vd-muted); letter-spacing:.07em;">ROYALTIES ACUMULADOS</div><div class="mono" style="font-size:26px; font-weight:600; margin-top:8px;">$ <?php echo esc_html( number_format( $distro_usd, 2, ',', ' ' ) ); ?></div></div>
                        <div class="rmbz-vipd-card" style="padding:22px 26px;"><div style="font-size:11.5px; font-weight:700; color:var(--vd-muted); letter-spacing:.07em;">LANÇAMENTOS</div><div class="mono" style="font-size:26px; font-weight:600; margin-top:8px;"><?php echo count( $releases ); ?></div></div>
                        <div class="rmbz-vipd-card" style="padding:22px 26px;"><div style="font-size:11.5px; font-weight:700; color:var(--vd-muted); letter-spacing:.07em;">AO VIVO NAS LOJAS</div><div class="mono" style="font-size:26px; font-weight:600; margin-top:8px;"><?php echo (int) $rel_live; ?></div></div>
                    </div>
                    <div class="rmbz-vipd-card">
                        <div class="rmbz-vipd-sect" style="margin-bottom:14px;">OS TEUS LANÇAMENTOS</div>
                        <?php if ( empty( $releases ) ): ?>
                            <div style="font-size:12.5px; color:var(--vd-muted);">Ainda não tens lançamentos. Cria o primeiro no painel de distribuição clássico.</div>
                        <?php else: foreach ( $releases as $r ):
                            [ $rl, $rk ] = rmbz_vipdesk_release_meta( $r->status );
                            [ $rbg, $rfg ] = $chip_css[ $rk ] ?? $chip_css['muted']; ?>
                            <div style="display:grid; grid-template-columns:56px 1.6fr 1fr auto; gap:16px; align-items:center; padding:13px 0; border-bottom:1px solid var(--vd-border);">
                                <?php if ( ! empty( $r->cover_image ) ): ?>
                                    <img src="<?php echo esc_url( $r->cover_image ); ?>" alt="" style="width:52px; height:52px; border-radius:12px; object-fit:cover; border:1px solid var(--vd-border);">
                                <?php else: ?>
                                    <div class="mono" style="width:52px; height:52px; border-radius:12px; background:repeating-linear-gradient(45deg,var(--vd-elev),var(--vd-elev) 6px,var(--vd-hover) 6px,var(--vd-hover) 12px); border:1px solid var(--vd-border); display:flex; align-items:center; justify-content:center; font-size:8px; color:var(--vd-muted);">capa</div>
                                <?php endif; ?>
                                <div><div style="font-size:14px; font-weight:700;"><?php echo esc_html( $r->title ); ?></div><div style="font-size:11.5px; color:var(--vd-muted);"><?php echo esc_html( ucfirst( (string) $r->release_type ) . ( $r->primary_genre ? ' · ' . $r->primary_genre : '' ) ); ?></div></div>
                                <div style="font-size:12.5px; color:var(--vd-text2);"><?php echo $r->release_date ? esc_html( date_i18n( 'd/m/Y', strtotime( $r->release_date ) ) ) : '—'; ?></div>
                                <span class="rmbz-vipd-chip" style="background:<?php echo $rbg; ?>; color:<?php echo $rfg; ?>;"><?php echo esc_html( $rl ); ?></span>
                            </div>
                        <?php endforeach; endif; ?>
                        <div style="font-size:12px; color:var(--vd-muted); margin-top:14px;">Para criar/editar lançamentos e pedir levantamento de royalties, usa o <a href="#" data-classic>painel clássico</a>.</div>
                    </div>
                </section>

                <!-- ═════ ENVIOS ═════ -->
                <section class="rmbz-vipd-panel" data-panel="envios" data-screen-label="Envios" hidden style="display:flex; flex-direction:column; gap:16px;">
                    <div style="display:flex; gap:12px; flex-wrap:wrap;">
                        <a href="#" data-classic class="rmbz-vipd-pill rmbz-vipd-pill--brand" style="font-size:13.5px; font-weight:750; padding:13px 26px;"><span class="ms" style="font-size:19px;">library_music</span> Enviar música</a>
                        <a href="#" data-classic class="rmbz-vipd-pill rmbz-vipd-pill--ghost" style="font-size:13.5px; padding:13px 26px; color:var(--vd-text2);"><span class="ms" style="font-size:19px;">smart_display</span> Enviar vídeo (redes)</a>
                    </div>
                    <div class="rmbz-vipd-card" style="padding:8px 28px;">
                        <?php if ( empty( $submissions ) ): ?>
                            <div style="font-size:12.5px; color:var(--vd-muted); padding:16px 0;">Ainda não fizeste envios.</div>
                        <?php else: foreach ( $submissions as $s ):
                            [ $sl, $sk ] = rmbz_vipdesk_submission_meta( $s->review_status );
                            [ $sbg, $sfg ] = $chip_css[ $sk ] ?? $chip_css['muted']; ?>
                            <div style="display:flex; align-items:center; gap:16px; padding:15px 0; border-bottom:1px solid var(--vd-border);">
                                <span class="ms" style="font-size:21px; color:var(--vd-brand-ink); background:var(--vd-brand-soft); width:42px; height:42px; border-radius:12px; display:flex; align-items:center; justify-content:center;">music_note</span>
                                <div style="flex:1; min-width:0;">
                                    <div style="font-size:14px; font-weight:650;"><?php echo esc_html( $s->music_title ); ?></div>
                                    <div style="font-size:11.5px; color:var(--vd-muted);"><?php echo esc_html( ( $s->music_genre ? $s->music_genre . ' · ' : '' ) . 'enviado ' . date_i18n( 'd/m/Y', strtotime( $s->submission_date ) ) ); ?></div>
                                </div>
                                <span class="rmbz-vipd-chip" style="background:<?php echo $sbg; ?>; color:<?php echo $sfg; ?>;"><?php echo esc_html( $sl ); ?></span>
                            </div>
                        <?php endforeach; endif; ?>
                    </div>
                </section>

                <!-- ═════ ESTATÍSTICAS ═════ -->
                <section class="rmbz-vipd-panel" data-panel="stats" data-screen-label="Estatísticas" hidden style="display:flex; flex-direction:column; gap:20px;">
                    <div class="rmbz-vipd-card" style="padding:26px 30px;">
                        <div class="rmbz-vipd-sect" style="margin-bottom:18px;">GANHOS NA CARTEIRA (MT) — ÚLTIMOS 6 MESES</div>
                        <div style="display:flex; align-items:flex-end; gap:18px; height:180px;">
                            <?php foreach ( $bars as $i => $b ):
                                $h = $bar_max > 0 ? max( 4, round( $b['val'] / $bar_max * 82 ) ) : 4; ?>
                                <div style="flex:1; display:flex; flex-direction:column; align-items:center; gap:8px; height:100%; justify-content:flex-end;">
                                    <div class="mono" style="font-size:11px; color:var(--vd-muted);"><?php echo esc_html( $b['val'] > 0 ? number_format( $b['val'], 0, ',', ' ' ) : '0' ); ?></div>
                                    <div style="width:100%; max-width:64px; height:<?php echo $h; ?>%; background:<?php echo $i === 5 ? 'var(--vd-brand)' : 'var(--vd-border2)'; ?>; border-radius:10px 10px 4px 4px;"></div>
                                    <div style="font-size:11px; font-weight:650; color:var(--vd-muted);"><?php echo esc_html( $b['mes'] ); ?></div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div class="rmbz-vipd-card">
                        <div class="rmbz-vipd-sect" style="margin-bottom:16px;">🏆 CONQUISTAS</div>
                        <div style="display:grid; grid-template-columns:repeat(4,1fr); gap:14px;" class="rmbz-vipd-grid3">
                            <?php foreach ( $conquistas as $c ): ?>
                                <div style="background:var(--vd-elev); border-radius:18px; padding:18px; text-align:center; opacity:<?php echo $c[3] ? '1' : '0.45'; ?>;">
                                    <div style="font-size:30px;"><?php echo $c[0]; ?></div>
                                    <div style="font-size:13px; font-weight:700; margin-top:8px;"><?php echo esc_html( $c[1] ); ?></div>
                                    <div style="font-size:11px; color:var(--vd-muted); margin-top:3px;"><?php echo esc_html( $c[2] ); ?></div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </section>

                <!-- ═════ NOTIFICAÇÕES ═════ -->
                <section class="rmbz-vipd-panel" data-panel="notifs" data-screen-label="Notificações" hidden style="display:flex; flex-direction:column; gap:12px; max-width:860px;">
                    <?php if ( empty( $notifs ) ): ?>
                        <div class="rmbz-vipd-card" style="text-align:center;">
                            <div style="font-size:40px; opacity:.4;">🔔</div>
                            <p style="margin:6px 0 0; font-weight:700;">Sem notificações.</p>
                        </div>
                    <?php else: foreach ( $notifs as $n ):
                        $is_new = isset( $n->is_read ) && (int) $n->is_read === 0; ?>
                        <div class="rmbz-vipd-card" style="padding:16px 22px; display:flex; gap:15px; align-items:flex-start; <?php echo $is_new ? 'border-color:var(--vd-brand);' : ''; ?>">
                            <span class="ms" style="font-size:20px; color:<?php echo $is_new ? 'var(--vd-brand-ink)' : 'var(--vd-muted)'; ?>; background:<?php echo $is_new ? 'var(--vd-brand-soft)' : 'var(--vd-elev)'; ?>; width:40px; height:40px; border-radius:50%; display:flex; align-items:center; justify-content:center; flex-shrink:0; font-variation-settings:'FILL' 1;">notifications</span>
                            <div style="flex:1; min-width:0;">
                                <div style="font-size:14px; font-weight:700;"><?php echo esc_html( wp_strip_all_tags( (string) $n->subject ) ); ?></div>
                                <?php if ( ! empty( $n->message ) ): ?>
                                    <div style="font-size:12.5px; color:var(--vd-text2); margin-top:3px; line-height:1.5;"><?php echo esc_html( wp_trim_words( wp_strip_all_tags( (string) $n->message ), 30, '…' ) ); ?></div>
                                <?php endif; ?>
                                <div style="font-size:11px; color:var(--vd-muted); margin-top:6px;"><?php echo esc_html( date_i18n( 'd/m/Y H:i', strtotime( $n->sent_date ) ) ); ?></div>
                            </div>
                        </div>
                    <?php endforeach; endif; ?>
                </section>

                <!-- ═════ PERFIL & VIP ═════ -->
                <section class="rmbz-vipd-panel rmbz-vipd-grid21" data-panel="perfil" data-screen-label="Perfil" hidden style="display:grid; grid-template-columns:360px 1fr; gap:20px; align-items:start;">
                    <div class="rmbz-vipd-card" style="padding:30px; text-align:center;">
                        <div style="width:96px; height:96px; border-radius:50%; background:var(--vd-brand); color:var(--vd-on-brand); display:flex; align-items:center; justify-content:center; font-weight:800; font-size:34px; margin:0 auto 16px;"><?php echo esc_html( $inicial ); ?></div>
                        <div class="disp" style="font-size:21px; font-weight:750;"><?php echo esc_html( $nome ); ?></div>
                        <div style="font-size:12.5px; color:var(--vd-muted); margin-top:4px;">Artista 1MZ Records</div>
                        <div style="margin-top:18px; background:linear-gradient(135deg,var(--vd-vip1),var(--vd-vip2)); border-radius:18px; padding:18px; color:#fff; text-align:left;">
                            <div style="display:flex; align-items:center; gap:8px; font-size:12px; font-weight:750;"><span class="ms" style="font-size:18px; color:#f0b90b; font-variation-settings:'FILL' 1;">workspace_premium</span> SUBSCRIÇÃO VIP</div>
                            <div style="font-size:12px; color:rgba(255,255,255,.8); margin-top:8px;">
                                <?php echo $expiry_br !== '' ? 'Ativa até <b>' . esc_html( $expiry_br ) . '</b> · ' . (int) $days_left . ' dias restantes' : 'Ativa'; ?>
                            </div>
                            <a href="#" data-classic style="display:block; margin-top:12px; text-align:center; background:#f0b90b; color:#0a0a0a; font-size:12.5px; font-weight:750; padding:11px; border-radius:100px;">Gerir / renovar no painel clássico</a>
                        </div>
                    </div>
                    <div class="rmbz-vipd-card" style="padding:26px 30px;">
                        <div style="font-size:15px; font-weight:750; margin-bottom:14px;">Dados de conta</div>
                        <?php
                        $campos = [
                            [ 'call', 'TELEMÓVEL', '+258 ' . substr( preg_replace( '/\D+/', '', (string) $tel ), -9 ) ],
                            [ 'mail', 'EMAIL', ( ! empty( $user->user_email ) && strpos( $user->user_email, '@1mz.local' ) === false ) ? (string) $user->user_email : '— não definido —' ],
                            [ 'artist', 'NOME ARTÍSTICO', $nome ],
                            [ 'workspace_premium', 'PLANO', 'Artista VIP' . ( $expiry_br !== '' ? ' · até ' . $expiry_br : '' ) ],
                        ];
                        foreach ( $campos as $c ): ?>
                            <div style="display:flex; align-items:center; gap:14px; padding:13px 0; border-bottom:1px solid var(--vd-border);">
                                <span class="ms" style="font-size:20px; color:var(--vd-brand-ink);"><?php echo esc_html( $c[0] ); ?></span>
                                <div><div style="font-size:11px; color:var(--vd-muted); font-weight:700; letter-spacing:.04em;"><?php echo esc_html( $c[1] ); ?></div><div style="font-size:14px; font-weight:600; margin-top:2px;"><?php echo esc_html( $c[2] ); ?></div></div>
                            </div>
                        <?php endforeach; ?>
                        <div style="display:flex; gap:10px; margin-top:18px; flex-wrap:wrap;">
                            <a href="#" data-classic class="rmbz-vipd-pill rmbz-vipd-pill--ghost" style="font-size:13px; padding:12px 24px;"><span class="ms" style="font-size:18px;">lock_reset</span> Alterar PIN (painel clássico)</a>
                            <a href="<?php echo esc_url( $logout_url ); ?>" class="rmbz-vipd-pill rmbz-vipd-pill--ghost" style="font-size:13px; padding:12px 24px; color:var(--vd-danger); border-color:var(--vd-danger);"><span class="ms" style="font-size:18px;">logout</span> Terminar sessão</a>
                        </div>
                    </div>
                </section>
            </div>
        </main>

        <!-- ═════ DIALOG LEVANTAMENTO (3 passos — POST real) ═════ -->
        <div class="rmbz-vipd-scrim" id="rmbz-vipd-wd" data-screen-label="Levantamento"
             data-saldo="<?php echo esc_attr( $withdrawable ); ?>" data-min="<?php echo esc_attr( $min_wd ); ?>">
            <div class="rmbz-vipd-dialog">
                <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:8px;">
                    <div style="font-size:11.5px; font-weight:800; color:var(--vd-brand-ink); letter-spacing:.08em;" id="rmbz-vipd-wd-lb">PASSO 1 DE 3 — VALOR</div>
                    <button type="button" data-close="rmbz-vipd-wd" style="border:0; background:none; color:var(--vd-muted); display:flex;"><span class="ms" style="font-size:22px;">close</span></button>
                </div>
                <?php if ( $has_pending_wd ): ?>
                    <div style="text-align:center; padding:20px 0;">
                        <span class="ms" style="font-size:56px; color:var(--vd-brand-ink);">hourglass_top</span>
                        <h3 class="disp" style="margin:10px 0 6px; font-size:20px; font-weight:700;">Já tens um pedido pendente</h3>
                        <p style="margin:0; font-size:13px; color:var(--vd-text2);">Aguarda a conclusão do levantamento atual antes de pedir outro.</p>
                    </div>
                <?php else: ?>
                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" id="rmbz-vipd-wd-form">
                    <input type="hidden" name="action" value="rmbz_request_withdrawal">
                    <input type="hidden" name="rmbz_withdrawal_source" value="wallet">
                    <?php wp_nonce_field( 'rmbz_withdrawal_nonce' ); ?>
                    <input type="hidden" name="rmbz_payment_method" id="rmbz-vipd-wd-met" value="mpesa">

                    <div class="rmbz-vipd-step on" data-step="1">
                        <h3 class="disp" style="margin:0 0 4px; font-size:22px; font-weight:700;">Quanto queres levantar?</h3>
                        <p style="margin:0 0 18px; font-size:12.5px; color:var(--vd-muted);">Saldo retirável: <b style="color:var(--vd-text2);"><?php echo esc_html( $fmt( $withdrawable ) ); ?> MT</b> · mínimo <?php echo esc_html( $fmt( $min_wd ) ); ?> MT</p>
                        <div style="display:flex; align-items:baseline; gap:8px; background:var(--vd-elev); border:1px solid var(--vd-border2); border-radius:18px; padding:15px 20px;">
                            <input name="rmbz_withdrawal_amount" id="rmbz-vipd-wd-amt" placeholder="0" inputmode="decimal" autocomplete="off"
                                   style="flex:1; border:0; background:none; outline:none; font-family:'JetBrains Mono',monospace; font-size:28px; font-weight:600; color:var(--vd-text); min-width:0; width:100%;">
                            <span style="font-size:15px; font-weight:750; color:var(--vd-muted);">MT</span>
                        </div>
                        <div style="display:flex; gap:8px; margin-top:12px; flex-wrap:wrap;" id="rmbz-vipd-wd-chips"></div>
                        <div id="rmbz-vipd-wd-err" style="display:none; margin-top:12px; font-size:12.5px; font-weight:650; color:var(--vd-danger);"></div>
                        <button type="button" data-next="2" class="rmbz-vipd-pill rmbz-vipd-pill--brand" style="width:100%; justify-content:center; margin-top:20px; padding:15px; font-size:14.5px;">Continuar</button>
                    </div>

                    <div class="rmbz-vipd-step" data-step="2">
                        <h3 class="disp" style="margin:0 0 4px; font-size:22px; font-weight:700;">Para onde enviamos?</h3>
                        <p style="margin:0 0 16px; font-size:12.5px; color:var(--vd-muted);">Vais receber <b style="color:var(--vd-text2);" id="rmbz-vipd-wd-amt2">—</b> na carteira móvel.</p>
                        <button type="button" class="rmbz-vipd-met on" data-method="mpesa">
                            <span style="width:44px; height:44px; border-radius:12px; background:#E60000; color:#fff; display:flex; align-items:center; justify-content:center; font-weight:800; font-size:12.5px; flex-shrink:0;">M-P</span>
                            <span style="flex:1;"><span style="display:block; font-size:15px; font-weight:750; color:var(--vd-text);">M-Pesa</span><span style="display:block; font-size:11.5px; color:var(--vd-muted); margin-top:2px;">Vodacom · números 84 / 85</span></span>
                            <span class="ms met-check" style="font-size:22px; color:var(--vd-brand-ink); font-variation-settings:'FILL' 1;">check_circle</span>
                        </button>
                        <button type="button" class="rmbz-vipd-met" data-method="emola">
                            <span style="width:44px; height:44px; border-radius:12px; background:#F26522; color:#fff; display:flex; align-items:center; justify-content:center; font-weight:800; font-size:12.5px; flex-shrink:0;">eM</span>
                            <span style="flex:1;"><span style="display:block; font-size:15px; font-weight:750; color:var(--vd-text);">eMola</span><span style="display:block; font-size:11.5px; color:var(--vd-muted); margin-top:2px;">Movitel · números 86 / 87</span></span>
                            <span class="ms met-check" style="font-size:22px; color:var(--vd-border2);">radio_button_unchecked</span>
                        </button>
                        <label class="rmbz-vipd-label">Número da carteira</label>
                        <div style="display:flex; align-items:center; gap:10px; background:var(--vd-elev); border:1.5px solid var(--vd-border2); border-radius:16px; padding:12px 17px;">
                            <span style="font-size:13.5px; font-weight:700; color:var(--vd-muted);">+258</span>
                            <input name="rmbz_payment_details" id="rmbz-vipd-wd-ph" inputmode="numeric" maxlength="9" value="<?php echo esc_attr( substr( preg_replace( '/\D+/', '', (string) $tel ), -9 ) ); ?>"
                                   style="flex:1; border:0; background:none; outline:none; font-family:'JetBrains Mono',monospace; font-size:16px; font-weight:600; color:var(--vd-text); min-width:0;">
                        </div>
                        <div id="rmbz-vipd-wd-err2" style="display:none; margin-top:10px; font-size:12.5px; font-weight:650; color:var(--vd-danger);"></div>
                        <div style="display:flex; gap:10px; margin-top:20px;">
                            <button type="button" data-back="1" class="rmbz-vipd-pill rmbz-vipd-pill--ghost" style="font-size:13.5px; padding:13px 22px;">Voltar</button>
                            <button type="button" data-next="3" class="rmbz-vipd-pill rmbz-vipd-pill--brand" style="flex:1; justify-content:center; font-size:14.5px; padding:13px;">Rever pedido</button>
                        </div>
                    </div>

                    <div class="rmbz-vipd-step" data-step="3">
                        <h3 class="disp" style="margin:0 0 16px; font-size:22px; font-weight:700;">Confirma o levantamento</h3>
                        <div style="background:var(--vd-elev); border:1px solid var(--vd-border); border-radius:18px; padding:6px 18px;">
                            <div style="display:flex; justify-content:space-between; padding:12px 0; border-bottom:1px solid var(--vd-border); font-size:13px;"><span style="color:var(--vd-muted);">Valor pedido</span><span class="mono" style="font-weight:600;" id="rmbz-vipd-wd-s1">—</span></div>
                            <div style="display:flex; justify-content:space-between; padding:12px 0; border-bottom:1px solid var(--vd-border); font-size:13px;"><span style="color:var(--vd-muted);">Carteira</span><span style="font-weight:650;" id="rmbz-vipd-wd-s2">—</span></div>
                            <div style="display:flex; justify-content:space-between; padding:14px 0; font-size:15px;"><span style="font-weight:750;">Vais receber</span><span class="mono" style="font-weight:700; color:var(--vd-success);" id="rmbz-vipd-wd-s3">—</span></div>
                        </div>
                        <p style="font-size:12px; color:var(--vd-muted); margin:12px 2px 0;">Sem taxa — recebes o valor completo. O pedido é processado pela 1MZ Records em até 24 horas úteis.</p>
                        <div style="display:flex; gap:10px; margin-top:18px;">
                            <button type="button" data-back="2" class="rmbz-vipd-pill rmbz-vipd-pill--ghost" style="font-size:13.5px; padding:13px 22px;">Voltar</button>
                            <button type="submit" class="rmbz-vipd-pill rmbz-vipd-pill--brand" style="flex:1; justify-content:center; font-size:14.5px; padding:13px;">Confirmar levantamento</button>
                        </div>
                    </div>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <!-- ═════ DIALOG DEPÓSITO (form real) ═════ -->
        <div class="rmbz-vipd-scrim" id="rmbz-vipd-dep" data-screen-label="Depósito">
            <div class="rmbz-vipd-dialog">
                <div style="display:flex; align-items:center; justify-content:space-between;">
                    <h3 class="disp" style="margin:0; font-size:21px; font-weight:700;">Depositar na carteira</h3>
                    <button type="button" data-close="rmbz-vipd-dep" style="border:0; background:none; color:var(--vd-muted); display:flex;"><span class="ms" style="font-size:22px;">close</span></button>
                </div>
                <?php if ( $has_pending_dep ): ?>
                    <div style="text-align:center; padding:20px 0;">
                        <span class="ms" style="font-size:56px; color:var(--vd-brand-ink);">hourglass_top</span>
                        <h3 class="disp" style="margin:10px 0 6px; font-size:20px; font-weight:700;">Depósito em análise</h3>
                        <p style="margin:0; font-size:13px; color:var(--vd-text2);">Já tens um depósito pendente — o saldo entra assim que a equipa aprovar.</p>
                    </div>
                <?php else: ?>
                <p style="margin:8px 0 4px; font-size:12.5px; color:var(--vd-muted); line-height:1.55;">Transfere para a conta 1MZ e envia o comprovativo — o saldo entra após aprovação.</p>
                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="rmbz_processar_deposito">
                    <?php wp_nonce_field( 'rmbz_deposit_nonce', '_rmbz_deposit_nonce' ); ?>
                    <label class="rmbz-vipd-label">Valor a depositar (MT)</label>
                    <input class="rmbz-vipd-input mono" type="number" name="deposit_amount" min="1" max="50000" step="0.01" inputmode="decimal" required placeholder="0,00">
                    <label class="rmbz-vipd-label">Operadora para onde transferiste</label>
                    <div style="display:flex; flex-direction:column; gap:8px;">
                        <label class="rmbz-vipd-met" style="margin:0;">
                            <input type="radio" name="payment_method" value="M-Pesa" required style="accent-color:#E60000;">
                            <span style="flex:1;"><span style="display:block; font-size:14px; font-weight:750; color:var(--vd-text);">M-Pesa<?php echo $mpesa_number !== '' ? ' · ' . esc_html( $mpesa_number ) : ''; ?></span><span style="display:block; font-size:11.5px; color:var(--vd-muted);">1MZ Records</span></span>
                        </label>
                        <label class="rmbz-vipd-met" style="margin:0;">
                            <input type="radio" name="payment_method" value="E-Mola" style="accent-color:#F26522;">
                            <span style="flex:1;"><span style="display:block; font-size:14px; font-weight:750; color:var(--vd-text);">E-Mola<?php echo $emola_number !== '' ? ' · ' . esc_html( $emola_number ) : ''; ?></span><span style="display:block; font-size:11.5px; color:var(--vd-muted);">1MZ Records</span></span>
                        </label>
                    </div>
                    <label class="rmbz-vipd-label">O teu número (de onde transferiste)</label>
                    <input class="rmbz-vipd-input mono" type="tel" name="sender_phone" pattern="8[4-7][0-9]{7}" minlength="9" maxlength="15" inputmode="numeric" required placeholder="841234567">
                    <input type="hidden" name="proof_type" value="id" id="rmbz-vipd-dep-pt">
                    <label class="rmbz-vipd-label">Código da SMS (ID da transação)</label>
                    <input class="rmbz-vipd-input mono" type="text" name="transaction_id" placeholder="Ex: CHJ1A23B4C" style="text-transform:uppercase; letter-spacing:.08em;">
                    <label class="rmbz-vipd-label">Ou anexa o screenshot do comprovativo</label>
                    <input class="rmbz-vipd-input" type="file" name="proof_image" accept="image/jpeg,image/png,image/webp"
                           onchange="document.getElementById('rmbz-vipd-dep-pt').value = this.files.length ? 'image' : 'id';">
                    <button type="submit" class="rmbz-vipd-pill rmbz-vipd-pill--brand" style="width:100%; justify-content:center; margin-top:18px; padding:14px; font-size:14px;">Enviar depósito para aprovação</button>
                </form>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
    (function () {
        var root = document.getElementById('rmbz-vipd');
        if (!root) return;

        // ── Tema (persistente) ──
        var saved = null;
        try { saved = localStorage.getItem('rmbz_vipd_theme'); } catch (e) {}
        if (saved === 'claro' || saved === 'oled') root.setAttribute('data-theme', saved);
        function syncThemeBtn() {
            var oled = root.getAttribute('data-theme') === 'oled';
            document.getElementById('rmbz-vipd-theme-ic').textContent = oled ? 'light_mode' : 'dark_mode';
            document.getElementById('rmbz-vipd-theme-lb').textContent = oled ? 'Tema claro' : 'Tema escuro OLED';
        }
        syncThemeBtn();
        document.getElementById('rmbz-vipd-theme').addEventListener('click', function () {
            var next = root.getAttribute('data-theme') === 'oled' ? 'claro' : 'oled';
            root.setAttribute('data-theme', next);
            try { localStorage.setItem('rmbz_vipd_theme', next); } catch (e) {}
            syncThemeBtn();
        });

        // ── Tabs ──
        var titles = {
            inicio:   ['Olá, <?php echo esc_js( $primeiro ); ?> 👋🏾', 'Bem-vindo ao teu painel VIP.'],
            projetos: ['Videoclipes', 'Os teus projetos com a equipa 1MZ.'],
            distro:   ['Distribuição digital', 'Releases e royalties nas plataformas.'],
            envios:   ['Envios', 'Músicas para o site e vídeos para as redes.'],
            stats:    ['Estatísticas', 'O teu crescimento e conquistas.'],
            notifs:   ['Notificações', 'Tudo o que aconteceu na tua conta.'],
            perfil:   ['Perfil & VIP', 'Dados de conta e subscrição.']
        };
        var navs = root.querySelectorAll('.rmbz-vipd-nav');
        var panels = root.querySelectorAll('[data-panel]');
        function goTab(key) {
            navs.forEach(function (n) { n.classList.toggle('on', n.getAttribute('data-tab') === key); });
            panels.forEach(function (p) { p.hidden = p.getAttribute('data-panel') !== key; });
            if (titles[key]) {
                document.getElementById('rmbz-vipd-title').innerHTML = titles[key][0];
                document.getElementById('rmbz-vipd-sub').textContent = titles[key][1];
            }
            root.querySelector('.rmbz-vipd-main').scrollTop = 0;
        }
        navs.forEach(function (n) { n.addEventListener('click', function () { goTab(n.getAttribute('data-tab')); }); });
        root.querySelectorAll('[data-goto]').forEach(function (b) { b.addEventListener('click', function () { goTab(b.getAttribute('data-goto')); }); });

        // "painel clássico" → desliga o novo painel via form escondido.
        root.querySelectorAll('[data-classic]').forEach(function (a) {
            a.addEventListener('click', function (e) {
                e.preventDefault();
                var f = root.querySelector('form input[name="vipdesk_on"][value="0"]');
                if (f) f.form.submit();
            });
        });

        // ── Dialogs ──
        function openDlg(id) { document.getElementById(id).classList.add('open'); }
        function closeDlg(id) { document.getElementById(id).classList.remove('open'); }
        var openWd = document.getElementById('rmbz-vipd-open-wd');
        var openDep = document.getElementById('rmbz-vipd-open-dep');
        if (openWd) openWd.addEventListener('click', function () { openDlg('rmbz-vipd-wd'); });
        if (openDep) openDep.addEventListener('click', function () { openDlg('rmbz-vipd-dep'); });
        root.querySelectorAll('[data-close]').forEach(function (b) { b.addEventListener('click', function () { closeDlg(b.getAttribute('data-close')); }); });
        root.querySelectorAll('.rmbz-vipd-scrim').forEach(function (s) { s.addEventListener('click', function (e) { if (e.target === s) s.classList.remove('open'); }); });

        // ── Levantamento (3 passos) ──
        var wd = document.getElementById('rmbz-vipd-wd');
        var wdForm = document.getElementById('rmbz-vipd-wd-form');
        if (wd && wdForm) {
            var saldo = parseFloat(wd.getAttribute('data-saldo')) || 0;
            var minWd = parseFloat(wd.getAttribute('data-min')) || 50;
            var amtIn = document.getElementById('rmbz-vipd-wd-amt');
            var phIn = document.getElementById('rmbz-vipd-wd-ph');
            var metIn = document.getElementById('rmbz-vipd-wd-met');
            var labels = { 1: 'PASSO 1 DE 3 — VALOR', 2: 'PASSO 2 DE 3 — MÉTODO', 3: 'PASSO 3 DE 3 — CONFIRMAÇÃO' };
            function fmt(n) { return n.toLocaleString('pt-PT', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).replace(/[\u00A0\u202F]/g, ' ') + ' MT'; }
            function amount() { var n = parseFloat(String(amtIn.value).replace(/\s/g, '').replace(',', '.')); return isFinite(n) ? n : 0; }
            function show(n) {
                wdForm.querySelectorAll('.rmbz-vipd-step').forEach(function (s) { s.classList.toggle('on', s.getAttribute('data-step') === String(n)); });
                document.getElementById('rmbz-vipd-wd-lb').textContent = labels[n] || '';
                if (n >= 2) {
                    var a = amount();
                    document.getElementById('rmbz-vipd-wd-amt2').textContent = fmt(a);
                    document.getElementById('rmbz-vipd-wd-s1').textContent = fmt(a);
                    document.getElementById('rmbz-vipd-wd-s2').textContent = (metIn.value === 'emola' ? 'eMola' : 'M-Pesa') + ' · +258 ' + phIn.value;
                    document.getElementById('rmbz-vipd-wd-s3').textContent = fmt(a);
                }
            }
            var chips = document.getElementById('rmbz-vipd-wd-chips');
            [500, 1000, 2500].forEach(function (v) { if (v >= minWd && v <= saldo) addChip(fmt(v).replace(',00', ''), v); });
            if (saldo >= minWd) addChip('Tudo (' + fmt(saldo).replace(',00', '') + ')', saldo);
            function addChip(lb, v) {
                var b = document.createElement('button');
                b.type = 'button'; b.textContent = lb;
                b.style.cssText = 'border:1px solid var(--vd-border2);background:none;color:var(--vd-text2);font-size:12.5px;font-weight:650;padding:9px 17px;border-radius:100px;';
                b.addEventListener('click', function () { amtIn.value = String(v).replace('.', ','); document.getElementById('rmbz-vipd-wd-err').style.display = 'none'; });
                chips.appendChild(b);
            }
            wdForm.querySelectorAll('[data-next]').forEach(function (b) {
                b.addEventListener('click', function () {
                    var to = parseInt(b.getAttribute('data-next'), 10);
                    if (to === 2) {
                        var a = amount(), err = '';
                        if (a < minWd) err = '⚠️ O valor mínimo de levantamento é ' + fmt(minWd) + '.';
                        else if (a > saldo) err = '⚠️ O valor excede o teu saldo retirável.';
                        var el = document.getElementById('rmbz-vipd-wd-err');
                        if (err) { el.textContent = err; el.style.display = 'block'; return; }
                        el.style.display = 'none';
                    }
                    if (to === 3) {
                        var d = String(phIn.value).replace(/\D+/g, '');
                        var e2 = document.getElementById('rmbz-vipd-wd-err2');
                        var pre = d.substring(0, 2), m = metIn.value, err2 = '';
                        if (d.length !== 9) err2 = '⚠️ O número tem de ter 9 dígitos.';
                        else if (m === 'mpesa' && pre !== '84' && pre !== '85') err2 = '⚠️ M-Pesa aceita números 84/85 (Vodacom).';
                        else if (m === 'emola' && pre !== '86' && pre !== '87') err2 = '⚠️ eMola aceita números 86/87 (Movitel).';
                        if (err2) { e2.textContent = err2; e2.style.display = 'block'; return; }
                        e2.style.display = 'none';
                        phIn.value = d;
                    }
                    show(to);
                });
            });
            wdForm.querySelectorAll('[data-back]').forEach(function (b) {
                b.addEventListener('click', function () { show(parseInt(b.getAttribute('data-back'), 10)); });
            });
            wdForm.querySelectorAll('.rmbz-vipd-met[data-method]').forEach(function (b) {
                b.addEventListener('click', function () {
                    wdForm.querySelectorAll('.rmbz-vipd-met[data-method]').forEach(function (o) {
                        var on = o === b;
                        o.classList.toggle('on', on);
                        var chk = o.querySelector('.met-check');
                        chk.textContent = on ? 'check_circle' : 'radio_button_unchecked';
                        chk.style.color = on ? 'var(--vd-brand-ink)' : 'var(--vd-border2)';
                    });
                    metIn.value = b.getAttribute('data-method');
                });
            });
        }

        // Scroll do chat para o fim.
        var box = document.getElementById('rmbz-vipd-chatbox');
        if (box) box.scrollTop = box.scrollHeight;
    })();
    </script>
    <?php
}
