<?php
/**
 * [1.5.414] PAINEL VIP DESKTOP DO ARTISTA — Material Design 3 (OLED / claro).
 *
 * Layout novo, exclusivo de ARTISTAS VIP, para ecrã de desktop (ocupa o
 * monitor todo): sidebar fixa à esquerda + conteúdo largo. É OPT-IN — o
 * artista VIP vê um banner "✨ Experimentar o novo painel" no dashboard
 * antigo e, ao ligar, passa a ver este. Pode voltar ao antigo quando quiser
 * (a preferência fica em extra_data['vip_layout'] na tabela rmbz_wallets).
 *
 * Secções (separadores): Início (saldos + depositar/levantar), Videoclipes
 * (projetos + chat), Distribuição (releases/royalties), Envios, Estatísticas,
 * Notificações, Perfil & VIP.
 *
 * DADOS REAIS reutilizados (sem duplicar lógica):
 *   - Sessão:      rmbz_is_user_logged_in() + rmbz_get_current_user_telemovel()
 *   - VIP:         rmbz_user_has_active_subscription() + rmbz_get_subscription_expiry()
 *   - Saldos:      $user->balance (rmbz_wallets) + rmbz_get_withdrawable_balance()
 *   - Projetos:    {prefix}rmbz_artist_projects (artist_telemovel)
 *   - Notif.:      {prefix}rmbz_notifications + dismissed (email_logs fallback)
 *   - Royalties:   {prefix}rmbz_distro_stats (se existir)
 *   - Levantamento: MESMO handler admin_post rmbz_request_withdrawal
 *                   (nonce rmbz_withdrawal_nonce, source=wallet,
 *                    rmbz_withdrawal_amount, payment_method, payment_details)
 *
 * A entrada é injetada em rmbz_exibir_my_account_page() (my-account-page.php).
 *
 * Local: includes/my-account-vip.php
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

// =============================================================================
// ELEGIBILIDADE + PREFERÊNCIA
// =============================================================================

/** É VIP (subscrição ativa)? */
function rmbz_vip_is_active( $telemovel ) {
    if ( empty( $telemovel ) ) return false;
    return function_exists( 'rmbz_user_has_active_subscription' )
        && rmbz_user_has_active_subscription( $telemovel );
}

/** O artista escolheu o painel novo? */
function rmbz_vip_layout_on( $telemovel ) {
    global $wpdb;
    if ( empty( $telemovel ) ) return false;
    $row = $wpdb->get_var( $wpdb->prepare(
        "SELECT extra_data FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s", $telemovel
    ) );
    $d = ! empty( $row ) ? json_decode( $row, true ) : [];
    return is_array( $d ) && ! empty( $d['vip_layout'] );
}

/** Permissões normalizadas do pacote VIP atual (legado sem chave = acesso total). */
function rmbz_vip_plan_permissions( $telemovel, $extra = null ) {
    if ( ! is_array( $extra ) ) {
        global $wpdb;
        $raw = $wpdb->get_var( $wpdb->prepare(
            "SELECT extra_data FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s",
            $telemovel
        ) );
        $extra = $raw ? json_decode( (string) $raw, true ) : [];
    }
    if ( ! is_array( $extra ) ) $extra = [];

    // Contas VIP antigas não tinham vip_permissions. Mantemos a compatibilidade
    // apenas quando a chave não existe; um array presente é sempre respeitado.
    $legacy_full = ! array_key_exists( 'vip_permissions', $extra );
    $raw_perms   = isset( $extra['vip_permissions'] ) && is_array( $extra['vip_permissions'] )
        ? $extra['vip_permissions']
        : [];
    $normalized = [];
    foreach ( [ 'distribute', 'site', 'social', 'video', 'ai' ] as $permission ) {
        $normalized[ $permission ] = $legacy_full || ! empty( $raw_perms[ $permission ] ) ? 1 : 0;
    }
    return $normalized;
}

/** Ecrã Material 3 usado quando uma área não pertence ao plano atual. */
function rmbz_vip_render_service_gate( $service, $reason = 'plan', $detail = '' ) {
    $services = [
        'distribution' => [
            'icon'     => 'public_off',
            'eyebrow'  => 'Distribuição digital',
            'name'     => 'Distribuição Digital',
            'features' => [ [ 'album', 'Lançamentos e catálogo' ], [ 'monitoring', 'Streams e relatórios' ], [ 'storefront', 'Perfis nas lojas' ] ],
        ],
        'video' => [
            'icon'     => 'videocam_off',
            'eyebrow'  => 'Produção de videoclipes',
            'name'     => 'Videoclipes profissionais',
            'features' => [ [ 'movie', 'Acompanhamento da produção' ], [ 'groups', 'Equipa e participantes' ], [ 'forum', 'Conversa do projeto' ] ],
        ],
        'submissions' => [
            'icon'     => 'upload_file',
            'eyebrow'  => 'Envios e promoção',
            'name'     => 'Envios para a 1MZ',
            'features' => [ [ 'language', 'Publicação no site' ], [ 'share', 'Promoção nas redes' ], [ 'movie', 'Candidatura a videoclipe' ] ],
        ],
    ];
    $service_meta = $services[ $service ] ?? $services['distribution'];
    $states = [
        'inactive' => [
            'badge_icon' => 'workspace_premium',
            'badge'      => 'Subscrição necessária',
            'title'      => 'Ativa uma subscrição VIP para continuar',
            'message'    => 'Esta área é exclusiva para artistas com uma subscrição ativa. Nenhum dado ou formulário é apresentado enquanto o acesso estiver inativo.',
            'action'     => 'Ver planos VIP',
        ],
        'restricted' => [
            'badge_icon' => 'lock_clock',
            'badge'      => 'Acesso temporariamente limitado',
            'title'      => $service_meta['name'] . ' está indisponível',
            'message'    => 'O serviço está protegido neste momento. Os dados e formulários permanecem ocultos até o acesso ser restabelecido.',
            'action'     => 'Ver estado da conta',
        ],
        'plan' => [
            'badge_icon' => 'lock',
            'badge'      => 'Serviço não incluído',
            'title'      => $service_meta['name'] . ' não faz parte deste plano',
            'message'    => 'Escolhe um plano que inclua este serviço. Até lá, os dados, relatórios e formulários desta área permanecem protegidos.',
            'action'     => 'Ver planos e serviços',
        ],
    ];
    $state = $states[ $reason ] ?? $states['plan'];
    if ( trim( (string) $detail ) !== '' ) $state['message'] = trim( (string) $detail );
    ?>
    <article class="service-access-gate" aria-labelledby="rmbz-service-gate-title-<?php echo esc_attr( $service ); ?>">
        <div class="service-access-aura" aria-hidden="true"></div>
        <div class="service-access-content">
            <span class="service-access-badge"><span class="ms"><?php echo esc_html( $state['badge_icon'] ); ?></span><?php echo esc_html( $state['badge'] ); ?></span>
            <span class="ms service-access-icon" aria-hidden="true"><?php echo esc_html( $service_meta['icon'] ); ?></span>
            <div class="service-access-eyebrow"><?php echo esc_html( $service_meta['eyebrow'] ); ?></div>
            <h2 class="service-access-title" id="rmbz-service-gate-title-<?php echo esc_attr( $service ); ?>"><?php echo esc_html( $state['title'] ); ?></h2>
            <p class="service-access-message"><?php echo esc_html( $state['message'] ); ?></p>
            <div class="service-access-features" aria-label="Funcionalidades protegidas">
                <?php foreach ( $service_meta['features'] as $feature ): ?>
                    <span><span class="ms"><?php echo esc_html( $feature[0] ); ?></span><?php echo esc_html( $feature[1] ); ?></span>
                <?php endforeach; ?>
            </div>
            <div class="service-access-actions">
                <button type="button" class="pill service-access-primary" data-nav="perfil"><span class="ms">workspace_premium</span><?php echo esc_html( $state['action'] ); ?></button>
                <button type="button" class="pill service-access-secondary" data-nav="inicio"><span class="ms">arrow_back</span>Voltar ao início</button>
            </div>
            <div class="service-access-foot"><span class="ms">shield</span>O conteúdo da conta fica oculto enquanto esta área estiver bloqueada.</div>
        </div>
    </article>
    <?php
}

/** Liga/desliga o painel novo (opt-in). */
function rmbz_vip_handle_toggle_layout() {
    if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'rmbz_vip_layout_nonce' ) ) {
        wp_die( 'Falha de segurança!' );
    }
    if ( ! function_exists( 'rmbz_is_user_logged_in' ) || ! rmbz_is_user_logged_in() ) {
        wp_die( 'Não autorizado.' );
    }
    global $wpdb;
    $tel = rmbz_get_current_user_telemovel();
    $on  = isset( $_POST['vip_on'] ) && $_POST['vip_on'] === '1';
    $row = $wpdb->get_var( $wpdb->prepare(
        "SELECT extra_data FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s", $tel
    ) );
    $d = ! empty( $row ) ? json_decode( $row, true ) : [];
    if ( ! is_array( $d ) ) $d = [];
    if ( $on ) { $d['vip_layout'] = 1; } else { unset( $d['vip_layout'] ); }
    $wpdb->update( $wpdb->prefix . 'rmbz_wallets', [ 'extra_data' => wp_json_encode( $d ) ], [ 'user_telemovel' => $tel ] );
    rmbz_safe_redirect( home_url( '/minha-conta/' ) );
}
add_action( 'admin_post_rmbz_vip_toggle_layout', 'rmbz_vip_handle_toggle_layout' );
add_action( 'admin_post_nopriv_rmbz_vip_toggle_layout', 'rmbz_vip_handle_toggle_layout' );

/** Banner de convite (mostrado no painel ANTIGO só a VIP que ainda não ligou). */
function rmbz_vip_optin_banner() {
    $url = admin_url( 'admin-post.php' );
    ?>
    <style>
        .rmbz-vip-optin-wrap{ position:relative; z-index:5; max-width:1100px; margin:14px auto 0; padding:0 16px; box-sizing:border-box; font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif; }
        .rmbz-vip-optin{ display:grid; grid-template-columns:44px minmax(0,1fr) auto; align-items:center; gap:14px; min-height:82px; margin:0; padding:14px 18px; border:1px solid #dca900; border-radius:22px; background:linear-gradient(110deg,#211900 0%,#332700 100%); box-shadow:0 10px 28px -24px rgba(0,0,0,.8); box-sizing:border-box; }
        .rmbz-vip-optin-icon{ width:44px; height:44px; display:flex; align-items:center; justify-content:center; border-radius:15px; background:rgba(240,185,11,.14); color:#f0b90b; }
        .rmbz-vip-optin-icon svg{ width:23px; height:23px; display:block; fill:currentColor; }
        .rmbz-vip-optin-copy{ min-width:0; }
        .rmbz-vip-optin-title{ color:#f0b90b; font-size:13px; line-height:1.25; font-weight:800; }
        .rmbz-vip-optin-text{ margin-top:3px; color:#e8dfc1; font-size:12.5px; line-height:1.45; }
        .rmbz-vip-optin-action{ min-height:46px; display:inline-flex; align-items:center; justify-content:center; padding:11px 21px; border:0; border-radius:100px; background:#f0b90b; color:#141000; font-family:inherit; font-size:12.5px; line-height:1.2; font-weight:800; white-space:nowrap; cursor:pointer; box-shadow:0 9px 22px -16px #f0b90b; transition:transform .16s ease,filter .16s ease; }
        .rmbz-vip-optin-action:hover{ filter:brightness(1.06); transform:translateY(-1px); }
        .rmbz-vip-optin-action:focus-visible{ outline:3px solid rgba(240,185,11,.35); outline-offset:3px; }
        @media (max-width:680px){
            .rmbz-vip-optin-wrap{ margin-top:10px; padding:0 10px; }
            .rmbz-vip-optin{ grid-template-columns:40px minmax(0,1fr); gap:11px 12px; min-height:0; padding:14px; border-radius:20px; }
            .rmbz-vip-optin-icon{ width:40px; height:40px; border-radius:13px; }
            .rmbz-vip-optin-title{ font-size:12.5px; }
            .rmbz-vip-optin-text{ font-size:11.5px; line-height:1.4; }
            .rmbz-vip-optin-action{ grid-column:1 / -1; width:100%; min-height:45px; margin-top:1px; padding:11px 16px; }
        }
    </style>
    <div class="rmbz-vip-optin-wrap">
        <form method="post" action="<?php echo esc_url( $url ); ?>" class="rmbz-vip-optin">
            <input type="hidden" name="action" value="rmbz_vip_toggle_layout">
            <input type="hidden" name="vip_on" value="1">
            <?php wp_nonce_field( 'rmbz_vip_layout_nonce' ); ?>
            <span class="rmbz-vip-optin-icon" aria-hidden="true">
                <svg viewBox="0 0 24 24" focusable="false"><path d="M12 2l1.55 4.45L18 8l-4.45 1.55L12 14l-1.55-4.45L6 8l4.45-1.55L12 2zm7 10l.9 2.1L22 15l-2.1.9L19 18l-.9-2.1L16 15l2.1-.9L19 12zM5 13l1.25 3.75L10 18l-3.75 1.25L5 23l-1.25-3.75L0 18l3.75-1.25L5 13z"/></svg>
            </span>
            <div class="rmbz-vip-optin-copy">
                <div class="rmbz-vip-optin-title">Novo painel VIP disponível</div>
                <div class="rmbz-vip-optin-text">Mais moderno, rápido e organizado. Exclusivo para Artistas VIP.</div>
            </div>
            <button type="submit" class="rmbz-vip-optin-action">Experimentar agora</button>
        </form>
    </div>
    <?php
}

// =============================================================================
// HELPERS DE DADOS
// =============================================================================

/** Label + cores (para tema via CSS var) do estado de produção. */
function rmbz_vip_status_meta( $st ) {
    $map = [
        'pending_review'     => [ 'Em Avaliação', 'rev' ],
        'approved'           => [ 'Aprovado', 'success' ],
        'kyc_review'         => [ 'KYC Pendente', 'rev' ],
        'pre-production'     => [ 'Pré-Produção', 'info' ],
        'filming'            => [ 'Filmagem', 'brand' ],
        'editing'            => [ 'Edição', 'info' ],
        'done'               => [ 'Concluído', 'success' ],
        'correction'         => [ 'Correção', 'rev' ],
        'rejected'           => [ 'Rejeitado', 'danger' ],
        'cancelled_deadline' => [ 'Cancelado', 'muted' ],
        'cancelled_no_confirmation' => [ 'Cancelado por Prazo', 'danger' ],
    ];
    return $map[ (string) $st ] ?? [ strtoupper( (string) $st ), 'muted' ];
}

/** Progresso aproximado (%) a partir do estado. */
function rmbz_vip_status_pct( $st ) {
    $p = [ 'pending_review'=>10,'approved'=>25,'kyc_review'=>30,'pre-production'=>45,'filming'=>65,'editing'=>85,'done'=>100,'correction'=>50,'rejected'=>0,'cancelled_deadline'=>0,'cancelled_no_confirmation'=>0 ];
    return $p[ (string) $st ] ?? 20;
}

/** Etapa pública atual do projeto para o indicador Material 3. */
function rmbz_vip_project_stage_meta( $st ) {
    $map = [
        'pending_review' => [ 'step' => 1, 'rail' => 0,   'icon' => 'rate_review',  'title' => 'Em avaliação',        'description' => 'A candidatura está a ser analisada pela equipa da 1MZ.',                  'tone' => 'warning' ],
        'correction'     => [ 'step' => 1, 'rail' => 0,   'icon' => 'edit_note',    'title' => 'Correção necessária', 'description' => 'Existem informações que precisam de ser atualizadas antes de avançar.',    'tone' => 'warning' ],
        'rejected'       => [ 'step' => 1, 'rail' => 0,   'icon' => 'block',        'title' => 'Projeto rejeitado',    'description' => 'A candidatura não avançou para produção.',                                 'tone' => 'danger' ],
        'cancelled_deadline' => [ 'step' => 1, 'rail' => 0, 'icon' => 'event_busy', 'title' => 'Projeto cancelado',    'description' => 'Este projeto foi encerrado e já não está em produção.',                    'tone' => 'danger' ],
        'cancelled_no_confirmation' => [ 'step' => 1, 'rail' => 0, 'icon' => 'event_busy', 'title' => 'Cancelado por prazo', 'description' => 'O prazo de confirmação terminou e o projeto foi cancelado.',             'tone' => 'danger' ],
        'approved'       => [ 'step' => 2, 'rail' => 25,  'icon' => 'verified',     'title' => 'Projeto aprovado',     'description' => 'A candidatura foi aprovada e a produção está a ser preparada.',            'tone' => 'success' ],
        'kyc_review'     => [ 'step' => 2, 'rail' => 25,  'icon' => 'badge',        'title' => 'Validação de identidade', 'description' => 'A equipa aguarda ou está a validar a documentação do artista.',          'tone' => 'warning' ],
        'pre-production' => [ 'step' => 2, 'rail' => 25,  'icon' => 'video_settings', 'title' => 'Pré-produção',      'description' => 'Planeamento, equipa, orçamento e datas estão a ser preparados.',           'tone' => 'info' ],
        'filming'        => [ 'step' => 3, 'rail' => 50,  'icon' => 'videocam',     'title' => 'Filmagem',             'description' => 'A equipa está na fase de captação das imagens do videoclipe.',              'tone' => 'brand' ],
        'editing'        => [ 'step' => 4, 'rail' => 75,  'icon' => 'movie_edit',   'title' => 'Edição',               'description' => 'As imagens estão a ser montadas, tratadas e preparadas para entrega.',      'tone' => 'info' ],
        'done'           => [ 'step' => 5, 'rail' => 100, 'icon' => 'task_alt',     'title' => 'Projeto concluído',    'description' => 'A produção do videoclipe foi finalizada com sucesso.',                      'tone' => 'success' ],
    ];
    return $map[ (string) $st ] ?? [
        'step' => 1, 'rail' => 0, 'icon' => 'pending', 'title' => 'Estado em atualização',
        'description' => 'A equipa está a atualizar o estado deste projeto.', 'tone' => 'neutral',
    ];
}

/** Categoria publica de uma presenca, com icone Material em vez de emoji. */
function rmbz_vip_filming_category_meta( $key ) {
    $key = sanitize_key( (string) $key );
    $base = function_exists( 'rmbz_fs_category_meta' )
        ? rmbz_fs_category_meta( $key )
        : [ 'label' => ucfirst( str_replace( '_', ' ', $key ?: 'outro' ) ) ];
    $icons = [
        'artista'      => 'mic_external_on',
        'feat'         => 'music_note',
        'modelo'       => 'styler',
        'dancarino'    => 'directions_run',
        'figurante'    => 'groups',
        'realizador'   => 'movie',
        'camera'       => 'videocam',
        'drone'        => 'flight',
        'iluminacao'   => 'lightbulb',
        'som'          => 'graphic_eq',
        'maquilhagem'  => 'face_retouching_natural',
        'guarda_roupa' => 'checkroom',
        'producao'     => 'assignment',
        'seguranca'    => 'shield',
        'motorista'    => 'directions_car',
        'outro'        => 'person',
    ];
    return [
        'label' => (string) ( $base['label'] ?? 'Outro' ),
        'icon'  => (string) ( $icons[ $key ] ?? $icons['outro'] ),
    ];
}

/** Historico publico das sessoes terminadas, agrupado por dia e categoria. */
function rmbz_vip_render_filming_history( $sessions, $percent_left = -1 ) {
    $history = array_values( array_filter( (array) $sessions, static function ( $session ) {
        return is_array( $session ) && ! empty( $session['ended_at'] );
    } ) );
    if ( empty( $history ) ) return;
    $history = array_reverse( $history );
    $complete = (int) $percent_left === 0;
    ?>
    <div class="project-section-card project-filming-history">
        <div class="project-section-head">
            <span class="ms project-section-icon">video_camera_back</span>
            <div><div class="project-section-title">Dias de filmagem</div><div class="project-section-subtitle">Sessões concluídas e pessoas que participaram.</div></div>
            <span class="project-filming-summary"><span class="ms" style="font-size:14px;"><?php echo $complete ? 'check_circle' : 'event'; ?></span><?php echo $complete ? 'Filmagem concluída' : count( $history ) . ( count( $history ) === 1 ? ' dia filmado' : ' dias filmados' ); ?></span>
        </div>
        <div class="project-filming-days">
            <?php foreach ( $history as $history_index => $session ):
                $day = max( 1, (int) ( $session['day'] ?? ( count( $history ) - $history_index ) ) );
                $date_raw = (string) ( $session['date'] ?? ( $session['started_at'] ?? '' ) );
                $date_ts = $date_raw !== '' ? strtotime( $date_raw ) : false;
                $date_label = $date_ts ? date_i18n( 'd/m/Y', $date_ts ) : 'Data não registada';
                $duration = max( 0, (int) ( $session['duration_min'] ?? 0 ) );
                $duration_label = $duration >= 60
                    ? floor( $duration / 60 ) . 'h' . str_pad( (string) ( $duration % 60 ), 2, '0', STR_PAD_LEFT )
                    : $duration . ' min';
                $people = isset( $session['participants'] ) && is_array( $session['participants'] ) ? $session['participants'] : [];
                $groups = [];
                foreach ( $people as $person ) {
                    if ( ! is_array( $person ) ) continue;
                    $category = sanitize_key( (string) ( $person['category'] ?? 'outro' ) ) ?: 'outro';
                    $groups[ $category ][] = $person;
                }
                $wrapped = ( $session['result'] ?? '' ) === 'wrapped';
                $next_raw = (string) ( $session['next_date'] ?? '' );
                $next_ts = $next_raw !== '' ? strtotime( $next_raw ) : false;
            ?>
                <details class="project-filming-day"<?php echo $history_index === 0 ? ' open' : ''; ?>>
                    <summary>
                        <span class="project-filming-day-number">D<?php echo $day; ?></span>
                        <span class="project-filming-day-copy">
                            <span class="project-filming-day-title"><?php echo esc_html( $date_label ); ?></span>
                            <span class="project-filming-day-meta"><span class="ms">schedule</span><?php echo esc_html( $duration_label ); ?><span>·</span><span class="ms">group</span><?php echo count( $people ); ?> <?php echo count( $people ) === 1 ? 'participante' : 'participantes'; ?></span>
                        </span>
                        <span class="project-filming-result<?php echo $wrapped ? '' : ' continue'; ?>"><span class="ms"><?php echo $wrapped ? 'done_all' : 'pending_actions'; ?></span><?php echo $wrapped ? 'Tudo filmado' : 'Faltam ' . max( 0, (int) ( $session['percent_left'] ?? 0 ) ) . '%'; ?></span>
                        <span class="ms project-filming-expand">expand_more</span>
                    </summary>
                    <div class="project-filming-day-body">
                        <?php if ( ! $wrapped && $next_ts ): ?><div class="project-filming-day-meta" style="margin:0 0 10px;"><span class="ms">event_repeat</span>Continua em <?php echo esc_html( date_i18n( 'd/m/Y', $next_ts ) ); ?></div><?php endif; ?>
                        <?php if ( empty( $groups ) ): ?>
                            <div class="project-filming-empty">Os participantes deste dia ainda não foram registados pela equipa.</div>
                        <?php else: ?>
                            <?php foreach ( $groups as $category => $category_people ):
                                $category_meta = rmbz_vip_filming_category_meta( $category );
                            ?>
                                <div class="project-filming-group">
                                    <div class="project-filming-group-head"><span class="ms"><?php echo esc_html( $category_meta['icon'] ); ?></span><?php echo esc_html( $category_meta['label'] ); ?> (<?php echo count( $category_people ); ?>)</div>
                                    <div class="project-filming-people">
                                        <?php foreach ( $category_people as $person ):
                                            $person_name = trim( (string) ( $person['name'] ?? '' ) );
                                            if ( $person_name === '' ) continue;
                                            $person_role = trim( (string) ( $person['role'] ?? '' ) );
                                            $person_initial = function_exists( 'mb_substr' ) ? mb_strtoupper( mb_substr( $person_name, 0, 1 ) ) : strtoupper( substr( $person_name, 0, 1 ) );
                                        ?>
                                            <span class="project-filming-person">
                                                <span class="project-filming-person-photo"><?php if ( ! empty( $person['photo'] ) ): ?><img src="<?php echo esc_url( $person['photo'] ); ?>" alt="<?php echo esc_attr( $person_name ); ?>" loading="lazy"><?php else: ?><?php echo esc_html( $person_initial ?: '1' ); ?><?php endif; ?></span>
                                                <span class="project-filming-person-copy"><span class="project-filming-person-name"><?php echo esc_html( $person_name ); ?></span><?php if ( $person_role !== '' ): ?><span class="project-filming-person-role"><?php echo esc_html( $person_role ); ?></span><?php endif; ?></span>
                                            </span>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </details>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
}

/** Logotipos fixos das redes, sem depender dos emojis do dispositivo. */
function rmbz_vip_social_brand_icon( $network, $size = 18 ) {
    $size = max( 14, min( 32, (int) $size ) );
    if ( $network === 'youtube' ) {
        return '<svg class="rvu-brand-icon" width="' . $size . '" height="' . $size . '" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect x="1" y="4.5" width="22" height="15" rx="4" fill="#FF0033"/><path d="M10 8.7 16 12l-6 3.3z" fill="#fff"/></svg>';
    }
    if ( $network === 'facebook' ) {
        return '<svg class="rvu-brand-icon" width="' . $size . '" height="' . $size . '" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><circle cx="12" cy="12" r="12" fill="#1877F2"/><path d="M13.4 20v-6.2h2.1l.32-2.4H13.4V9.85c0-.7.2-1.18 1.2-1.18h1.3V6.5c-.22-.03-1-.1-1.9-.1-1.9 0-3.2 1.16-3.2 3.3v1.7H8.7v2.4h2.1V20h2.6z" fill="#fff"/></svg>';
    }
    return '';
}

/** Paginação compacta para as listas do painel VIP. */
function rmbz_vip_render_pager( $current, $total, $per_page, $param, $section, $extra = [] ) {
    $pages = max( 1, (int) ceil( (int) $total / max( 1, (int) $per_page ) ) );
    if ( $pages <= 1 ) return;

    $current = max( 1, min( (int) $current, $pages ) );
    $base    = home_url( '/minha-conta/' );
    $url_for = static function ( $page ) use ( $base, $param, $section, $extra ) {
        return add_query_arg(
            array_merge( [ 'sect' => $section, $param => max( 1, (int) $page ) ], (array) $extra ),
            $base
        );
    };
    ?>
    <nav aria-label="Paginação" style="display:flex; align-items:center; justify-content:center; gap:10px; margin-top:16px;">
        <?php if ( $current > 1 ): ?>
            <a class="chip" href="<?php echo esc_url( $url_for( $current - 1 ) ); ?>" style="text-decoration:none;">← Anterior</a>
        <?php endif; ?>
        <span class="mono" style="font-size:11.5px; color:var(--muted);">Página <?php echo (int) $current; ?> de <?php echo (int) $pages; ?></span>
        <?php if ( $current < $pages ): ?>
            <a class="chip" href="<?php echo esc_url( $url_for( $current + 1 ) ); ?>" style="text-decoration:none;">Seguinte →</a>
        <?php endif; ?>
    </nav>
    <?php
}

/** Lista compacta usada nos detalhes de analytics nativos. */
function rmbz_vip_render_stats_breakdown( $title, $rows, $name_field ) {
    if ( empty( $rows ) ) return;
    ?>
    <div class="card">
        <div style="font-size:13px;font-weight:800;margin-bottom:8px;"><?php echo esc_html( $title ); ?></div>
        <?php foreach ( $rows as $row ): ?>
            <div style="display:flex;align-items:center;gap:10px;padding:9px 0;border-bottom:1px solid var(--border);">
                <b style="flex:1;min-width:0;font-size:12.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?php echo esc_html( (string) ( $row->{$name_field} ?? '—' ) ); ?></b>
                <span class="mono" style="font-size:11.5px;color:var(--text2);"><?php echo esc_html( number_format( (int) ( $row->streams ?? 0 ) ) ); ?> str</span>
                <b class="mono" style="font-size:12px;color:var(--success);">$ <?php echo esc_html( number_format( (float) ( $row->earnings_usd ?? 0 ), 2 ) ); ?></b>
            </div>
        <?php endforeach; ?>
    </div>
    <?php
}

/** Separa texto e ficheiros anexados nas mensagens legadas do projeto. */
function rmbz_vip_chat_extract_attachments( $text ) {
    $attachments = [];
    $clean_text = preg_replace_callback(
        '#https?://[^\s<>"\']+#i',
        static function ( $match ) use ( &$attachments ) {
            $url  = rtrim( $match[0], '.,;!?' );
            $path = (string) parse_url( $url, PHP_URL_PATH );
            $ext  = strtolower( pathinfo( $path, PATHINFO_EXTENSION ) );
            $name = basename( $path );
            $attachments[] = [
                'url'      => $url,
                'name'     => $name !== '' ? rawurldecode( $name ) : 'Abrir anexo',
                'is_image' => in_array( $ext, [ 'jpg', 'jpeg', 'png', 'gif', 'webp' ], true ),
            ];
            return '';
        },
        (string) $text
    );
    $clean_text = preg_replace( '/[—\-]\s*$/u', '', trim( (string) $clean_text ) );
    if ( preg_match( '/^(pode ver|veja|see|view)\s*[📎🔗]*\s*$/iu', $clean_text ) ) $clean_text = '';
    return [ 'text' => trim( $clean_text ), 'attachments' => $attachments ];
}

/** Verifica a existência de uma tabela sem gerar erros em instalações antigas. */
function rmbz_vip_table_exists( $table ) {
    global $wpdb;
    return $table !== '' && $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) === $table;
}

/** Formatos de telefone aceites pelas tabelas antigas e pela App. */
function rmbz_vip_telemovel_variants( $telemovel ) {
    if ( function_exists( 'rmbz_api_notif_telemovel_variants' ) ) {
        return rmbz_api_notif_telemovel_variants( preg_replace( '/[^0-9+]/', '', (string) $telemovel ) );
    }
    $clean = preg_replace( '/[^0-9+]/', '', (string) $telemovel );
    $plain = ltrim( $clean, '+' );
    $out   = [ $clean, $plain ];
    if ( strpos( $plain, '258' ) === 0 ) $out[] = substr( $plain, 3 );
    return array_values( array_unique( array_filter( $out ) ) );
}

/** Converte deep links do módulo antigo para vistas nativas do painel VIP. */
function rmbz_vip_notification_action_url( $url ) {
    $url = (string) $url;
    if ( $url === '' ) return '';
    $query = wp_parse_url( html_entity_decode( $url ), PHP_URL_QUERY );
    if ( ! $query ) return esc_url_raw( $url );
    parse_str( $query, $args );
    $action = sanitize_key( (string) ( $args['distro_action'] ?? '' ) );
    $id     = absint( $args['id'] ?? ( $args['release_id'] ?? 0 ) );
    $base   = home_url( '/minha-conta/' );
    if ( $action === 'view_release' && $id ) return add_query_arg( [ 'sect' => 'distro', 'dview' => 'release', 'rid' => $id ], $base );
    if ( $action === 'edit_release' && $id ) return add_query_arg( [ 'sect' => 'distro', 'dview' => 'create', 'rid' => $id ], $base );
    if ( $action === 'analytics' && ! empty( $args['import_id'] ) ) return add_query_arg( [ 'sect' => 'distro', 'dview' => 'report', 'import_id' => absint( $args['import_id'] ) ], $base );
    if ( $action === 'analytics' && ! empty( $args['release_stats'] ) ) return add_query_arg( [ 'sect' => 'distro', 'dview' => 'release-stats', 'rid' => absint( $args['release_stats'] ) ], $base );
    if ( $action === 'analytics' ) return add_query_arg( [ 'sect' => 'distro', 'dview' => 'stats' ], $base );
    if ( $action === 'history' ) return add_query_arg( [ 'sect' => 'distro', 'dview' => 'history' ], $base );
    if ( $action === 'profiles' ) return add_query_arg( [ 'sect' => 'distro', 'dview' => 'profiles' ], $base );
    if ( $action === 'create' ) return add_query_arg( [ 'sect' => 'distro', 'dview' => 'create' ], $base );
    if ( $action === 'licensing-somas' ) {
        $native = [ 'sect' => 'distro', 'dview' => 'somas' ];
        if ( ! empty( $args['somas_path'] ) ) $native['somas_path'] = sanitize_key( $args['somas_path'] );
        return add_query_arg( $native, $base );
    }
    if ( $action === 'artist-data' ) return add_query_arg( [ 'sect' => 'distro', 'dview' => 'somas' ], $base );
    if ( in_array( $action, [ 'dashboard', 'list' ], true ) ) return add_query_arg( 'sect', 'distro', $base );
    if ( $action === 'milestones' ) return add_query_arg( 'sect', 'stats', $base );
    if ( $action === 'notifications' ) return add_query_arg( 'sect', 'notifs', $base );
    return esc_url_raw( $url );
}

/** Dados do licenciamento SOMAS para o wizard e o detalhe nativos. */
function rmbz_vip_ajax_distro_license_panel() {
    if ( ! check_ajax_referer( 'rmbz_distro_nonce', 'nonce', false ) ) {
        wp_send_json_error( [ 'message' => 'Falha de segurança.' ], 403 );
    }
    if ( ! function_exists( 'rmbz_is_user_logged_in' ) || ! rmbz_is_user_logged_in() ) {
        wp_send_json_error( [ 'message' => 'Sessão expirada.' ], 401 );
    }

    $telemovel = rmbz_get_current_user_telemovel();
    $access_error = function_exists( 'rmbz_distro_artist_access_error' )
        ? rmbz_distro_artist_access_error( $telemovel )
        : '';
    if ( $access_error !== '' ) wp_send_json_error( [ 'message' => $access_error ], 403 );

    $release_id = absint( $_POST['release_id'] ?? 0 );
    global $wpdb;
    $release = $wpdb->get_row( $wpdb->prepare(
        "SELECT id, title FROM {$wpdb->prefix}rmbz_distro_releases WHERE id = %d AND artist_telemovel = %s",
        $release_id,
        $telemovel
    ) );
    if ( ! $release ) wp_send_json_error( [ 'message' => 'Lançamento não encontrado.' ], 404 );

    $enabled = function_exists( 'rmbz_licensing_is_enabled' ) && rmbz_licensing_is_enabled();
    if ( ! $enabled ) wp_send_json_success( [ 'enabled' => false ] );

    $registration = rmbz_licensing_get_artist_somas_registration( $telemovel );
    $license      = rmbz_licensing_get_release_license( $release_id );
    $track_count  = (int) rmbz_licensing_count_release_tracks( $release_id );
    $unit_price   = (float) rmbz_licensing_get_per_track_price();
    $base_total   = round( $track_count * $unit_price, 2 );
    $balance      = (float) rmbz_get_wallet_balance_by_phone( $telemovel );

    wp_send_json_success( [
        'enabled'        => true,
        'release_id'     => $release_id,
        'release_title'  => (string) $release->title,
        'registration'   => $registration ? [
            'status' => (string) $registration->status,
            'number' => (string) ( $registration->somas_number ?? '' ),
        ] : null,
        'license'        => $license ? [
            'id'              => (int) $license->id,
            'status'          => (string) $license->status,
            'track_count'     => (int) $license->track_count,
            'amount_charged'  => (float) $license->amount_charged,
            'coupon_discount' => (float) ( $license->coupon_discount ?? 0 ),
        ] : null,
        'track_count'    => $track_count,
        'unit_price'     => $unit_price,
        'base_total'     => $base_total,
        'balance'        => $balance,
        'registration_price' => (float) rmbz_licensing_get_registration_price(),
        'license_nonce'  => wp_create_nonce( 'rmbz_license_' . $telemovel ),
    ] );
}
add_action( 'wp_ajax_rmbz_vip_distro_license_panel', 'rmbz_vip_ajax_distro_license_panel' );
add_action( 'wp_ajax_nopriv_rmbz_vip_distro_license_panel', 'rmbz_vip_ajax_distro_license_panel' );

/**
 * Centro canónico de notificações do novo tema.
 * Usa a mesma tabela da App e mantém email_logs apenas como fallback legado.
 */
function rmbz_vip_get_notifications( $telemovel, $email, $page = 1, $per_page = 20, $include_items = true ) {
    global $wpdb;
    $page     = max( 1, (int) $page );
    $per_page = max( 1, min( 50, (int) $per_page ) );
    $offset   = ( $page - 1 ) * $per_page;
    $table    = $wpdb->prefix . 'rmbz_notifications';
    $dismiss  = $wpdb->prefix . 'rmbz_notifications_dismissed';

    if ( rmbz_vip_table_exists( $table ) && rmbz_vip_table_exists( $dismiss ) ) {
        $variants     = rmbz_vip_telemovel_variants( $telemovel );
        $placeholders = implode( ',', array_fill( 0, count( $variants ), '%s' ) );
        $now          = current_time( 'mysql' );
        $where        = "n.is_archived = 0
                         AND (n.expires_at IS NULL OR n.expires_at > %s)
                         AND d.id IS NULL
                         AND (n.target_telemovel IN ($placeholders)
                              OR (n.target_telemovel IS NULL AND (n.target_role IS NULL OR n.target_role = 'artist')))";
        $params       = array_merge( $variants, [ $now ], $variants );
        $total        = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} n
             LEFT JOIN {$dismiss} d ON d.notification_id = n.id AND d.telemovel IN ($placeholders)
             WHERE {$where}",
            $params
        ) );
        $rows = $include_items ? ( $wpdb->get_results( $wpdb->prepare(
            "SELECT n.* FROM {$table} n
             LEFT JOIN {$dismiss} d ON d.notification_id = n.id AND d.telemovel IN ($placeholders)
             WHERE {$where}
             ORDER BY n.created_at DESC LIMIT %d OFFSET %d",
            array_merge( $params, [ $per_page, $offset ] )
        ) ) ?: [] ) : [];
        if ( $include_items && function_exists( 'rmbz_notify_filter_orphans' ) ) $rows = rmbz_notify_filter_orphans( $rows );

        $items = [];
        foreach ( $rows as $row ) {
            $items[] = [
                'id'           => (int) $row->id,
                'source'       => 'native',
                'titulo'       => (string) ( $row->title ?: 'Notificação' ),
                'texto'        => wp_strip_all_tags( (string) ( $row->body ?? '' ) ),
                'quando'       => ! empty( $row->created_at ) ? date_i18n( 'd/m/Y H:i', strtotime( (string) $row->created_at ) ) : '',
                'lida'         => false,
                'severity'     => in_array( (string) $row->severity, [ 'info', 'success', 'warning', 'danger' ], true ) ? (string) $row->severity : 'info',
                'action_url'   => rmbz_vip_notification_action_url( $row->action_url ?? '' ),
                'action_label' => (string) ( $row->action_label ?: 'Ver detalhes' ),
            ];
        }
        return [ 'items' => $items, 'total' => $total, 'unread' => $total, 'source' => 'native' ];
    }

    $items = [];
    $total = 0;
    $unread = 0;
    if ( $email !== '' ) {
        $legacy = $wpdb->prefix . 'rmbz_email_logs';
        if ( rmbz_vip_table_exists( $legacy ) ) {
            $total = (int) $wpdb->get_var( $wpdb->prepare(
                "SELECT COUNT(*) FROM {$legacy} WHERE recipient_email = %s AND is_cleared = 0 AND audience <> 'admin'",
                $email
            ) );
            $unread = (int) $wpdb->get_var( $wpdb->prepare(
                "SELECT COUNT(*) FROM {$legacy} WHERE recipient_email = %s AND is_cleared = 0 AND is_read = 0 AND audience <> 'admin'",
                $email
            ) );
            $rows = $include_items ? ( $wpdb->get_results( $wpdb->prepare(
                "SELECT * FROM {$legacy} WHERE recipient_email = %s AND is_cleared = 0 AND audience <> 'admin'
                 ORDER BY id DESC LIMIT %d OFFSET %d",
                $email, $per_page, $offset
            ) ) ?: [] ) : [];
            foreach ( $rows as $row ) {
                $items[] = [
                    'id' => (int) $row->id, 'source' => 'legacy',
                    'titulo' => (string) ( $row->subject ?? 'Notificação' ),
                    'texto' => wp_strip_all_tags( (string) ( $row->body ?? $row->message ?? '' ) ),
                    'quando' => ! empty( $row->sent_at ) ? date_i18n( 'd/m/Y H:i', strtotime( (string) $row->sent_at ) ) : ( ! empty( $row->created_at ) ? date_i18n( 'd/m/Y H:i', strtotime( (string) $row->created_at ) ) : '' ),
                    'lida' => ! empty( $row->is_read ), 'severity' => 'info', 'action_url' => '', 'action_label' => '',
                ];
            }
        }
    }
    return [ 'items' => $items, 'total' => $total, 'unread' => $unread, 'source' => 'legacy' ];
}

/** AJAX: dispensar uma notificação canónica ou marcar uma legacy como lida. */
function rmbz_vip_ajax_notif_dismiss() {
    if ( ! check_ajax_referer( 'rmbz_vip_notif', 'nonce', false ) ) wp_send_json_error( [ 'message' => 'Falha de segurança.' ], 403 );
    if ( ! function_exists( 'rmbz_is_user_logged_in' ) || ! rmbz_is_user_logged_in() ) wp_send_json_error( [ 'message' => 'Sessão expirada.' ], 401 );
    global $wpdb;
    $id     = absint( $_POST['notif_id'] ?? 0 );
    $source = sanitize_key( $_POST['source'] ?? 'native' );
    $tel    = rmbz_get_current_user_telemovel();
    if ( ! $id ) wp_send_json_error( [ 'message' => 'Notificação inválida.' ], 400 );

    if ( $source === 'legacy' ) {
        $email = (string) $wpdb->get_var( $wpdb->prepare( "SELECT user_email FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s", $tel ) );
        $ok = $wpdb->update( $wpdb->prefix . 'rmbz_email_logs', [ 'is_read' => 1 ], [ 'id' => $id, 'recipient_email' => $email ], [ '%d' ], [ '%d', '%s' ] );
        wp_send_json_success( [ 'dismissed' => $ok !== false ] );
    }

    $table = $wpdb->prefix . 'rmbz_notifications';
    $variants = rmbz_vip_telemovel_variants( $tel );
    $ph = implode( ',', array_fill( 0, count( $variants ), '%s' ) );
    $owns = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM {$table} WHERE id = %d AND is_archived = 0
         AND (target_telemovel IN ($ph) OR (target_telemovel IS NULL AND (target_role IS NULL OR target_role = 'artist'))) ",
        array_merge( [ $id ], $variants )
    ) );
    if ( ! $owns || ! function_exists( 'rmbz_notify_dismiss' ) ) wp_send_json_error( [ 'message' => 'Notificação não encontrada.' ], 404 );
    wp_send_json_success( [ 'dismissed' => rmbz_notify_dismiss( $id, $tel ) ] );
}
add_action( 'wp_ajax_rmbz_vip_notif_dismiss', 'rmbz_vip_ajax_notif_dismiss' );
add_action( 'wp_ajax_nopriv_rmbz_vip_notif_dismiss', 'rmbz_vip_ajax_notif_dismiss' );

/** AJAX: limpar o centro inteiro, incluindo o fallback legado. */
function rmbz_vip_ajax_notif_dismiss_all() {
    if ( ! check_ajax_referer( 'rmbz_vip_notif', 'nonce', false ) ) wp_send_json_error( [ 'message' => 'Falha de segurança.' ], 403 );
    if ( ! function_exists( 'rmbz_is_user_logged_in' ) || ! rmbz_is_user_logged_in() ) wp_send_json_error( [ 'message' => 'Sessão expirada.' ], 401 );
    global $wpdb;
    $tel = rmbz_get_current_user_telemovel();
    $count = 0;
    $table = $wpdb->prefix . 'rmbz_notifications';
    if ( rmbz_vip_table_exists( $table ) && function_exists( 'rmbz_notify_dismiss' ) ) {
        $variants = rmbz_vip_telemovel_variants( $tel );
        $ph = implode( ',', array_fill( 0, count( $variants ), '%s' ) );
        $ids = $wpdb->get_col( $wpdb->prepare(
            "SELECT id FROM {$table} WHERE is_archived = 0 AND (expires_at IS NULL OR expires_at > %s)
             AND (target_telemovel IN ($ph) OR (target_telemovel IS NULL AND (target_role IS NULL OR target_role = 'artist'))) ",
            array_merge( [ current_time( 'mysql' ) ], $variants )
        ) );
        foreach ( $ids as $id ) if ( rmbz_notify_dismiss( (int) $id, $tel ) ) $count++;
    }
    $email = (string) $wpdb->get_var( $wpdb->prepare( "SELECT user_email FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s", $tel ) );
    if ( $email !== '' ) {
        $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->prefix}rmbz_email_logs SET is_read = 1, is_cleared = 1 WHERE recipient_email = %s AND audience <> 'admin'", $email ) );
    }
    wp_send_json_success( [ 'dismissed_count' => $count ] );
}
add_action( 'wp_ajax_rmbz_vip_notif_dismiss_all', 'rmbz_vip_ajax_notif_dismiss_all' );
add_action( 'wp_ajax_nopriv_rmbz_vip_notif_dismiss_all', 'rmbz_vip_ajax_notif_dismiss_all' );

/** Guarda as preferências de push da mesma forma que a App. */
function rmbz_vip_save_notification_prefs() {
    if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'rmbz_vip_notif_prefs' ) ) wp_die( 'Falha de segurança.' );
    if ( ! function_exists( 'rmbz_is_user_logged_in' ) || ! rmbz_is_user_logged_in() ) wp_die( 'Sessão expirada.' );
    $tel = rmbz_get_current_user_telemovel();
    $cats = function_exists( 'rmbz_notif_site_categories' ) ? rmbz_notif_site_categories() : [ 'releases' => [], 'submissions' => [], 'money' => [], 'license' => [] ];
    foreach ( array_keys( $cats ) as $key ) {
        if ( function_exists( 'rmbz_notif_set_user_pref' ) ) rmbz_notif_set_user_pref( $tel, $key, ! empty( $_POST[ 'pref_' . $key ] ) );
    }
    rmbz_safe_redirect( add_query_arg( [ 'sect' => 'notifs', 'saved' => 'prefs' ], home_url( '/minha-conta/' ) ) );
}
add_action( 'admin_post_rmbz_vip_save_notif_prefs', 'rmbz_vip_save_notification_prefs' );
add_action( 'admin_post_nopriv_rmbz_vip_save_notif_prefs', 'rmbz_vip_save_notification_prefs' );

/** Termina uma sessão específica da App, sempre validando a propriedade. */
function rmbz_vip_revoke_app_session() {
    if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'rmbz_vip_revoke_session' ) ) wp_die( 'Falha de segurança.' );
    if ( ! function_exists( 'rmbz_is_user_logged_in' ) || ! rmbz_is_user_logged_in() ) wp_die( 'Sessão expirada.' );
    global $wpdb;
    $tel = rmbz_get_current_user_telemovel();
    $id  = absint( $_POST['session_id'] ?? 0 );
    if ( $id ) {
        $wpdb->query( $wpdb->prepare(
            "UPDATE {$wpdb->prefix}rmbz_api_refresh_tokens
             SET revoked_at = %s, revoke_reason = 'user_revoked_from_web'
             WHERE id = %d AND user_telemovel = %s AND revoked_at IS NULL",
            current_time( 'mysql', true ), $id, $tel
        ) );
    }
    rmbz_safe_redirect( add_query_arg( [ 'sect' => 'perfil', 'saved' => 'session' ], home_url( '/minha-conta/' ) ) );
}
add_action( 'admin_post_rmbz_vip_revoke_app_session', 'rmbz_vip_revoke_app_session' );
add_action( 'admin_post_nopriv_rmbz_vip_revoke_app_session', 'rmbz_vip_revoke_app_session' );

/** Termina todas as sessões móveis; a sessão web atual não é afetada. */
function rmbz_vip_revoke_all_app_sessions() {
    if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'rmbz_vip_revoke_all_sessions' ) ) wp_die( 'Falha de segurança.' );
    if ( ! function_exists( 'rmbz_is_user_logged_in' ) || ! rmbz_is_user_logged_in() ) wp_die( 'Sessão expirada.' );
    global $wpdb;
    $tel = rmbz_get_current_user_telemovel();
    $wpdb->query( $wpdb->prepare(
        "UPDATE {$wpdb->prefix}rmbz_api_refresh_tokens SET revoked_at = %s, revoke_reason = 'logout_all_from_web' WHERE user_telemovel = %s AND revoked_at IS NULL",
        current_time( 'mysql', true ), $tel
    ) );
    rmbz_safe_redirect( add_query_arg( [ 'sect' => 'perfil', 'saved' => 'sessions' ], home_url( '/minha-conta/' ) ) );
}
add_action( 'admin_post_rmbz_vip_revoke_all_app_sessions', 'rmbz_vip_revoke_all_app_sessions' );
add_action( 'admin_post_nopriv_rmbz_vip_revoke_all_app_sessions', 'rmbz_vip_revoke_all_app_sessions' );

/** Reutiliza o endpoint oficial do Assistente com a sessão web autenticada. */
function rmbz_vip_ajax_ai_ask() {
    if ( ! check_ajax_referer( 'rmbz_vip_ai', 'nonce', false ) ) wp_send_json_error( [ 'message' => 'Falha de segurança.' ], 403 );
    if ( ! function_exists( 'rmbz_is_user_logged_in' ) || ! rmbz_is_user_logged_in() ) wp_send_json_error( [ 'message' => 'Sessão expirada.' ], 401 );
    if ( ! function_exists( 'rmbz_api_handle_ai_ask' ) ) wp_send_json_error( [ 'message' => 'Assistente indisponível.' ], 503 );
    $question = mb_substr( trim( sanitize_textarea_field( wp_unslash( $_POST['question'] ?? '' ) ) ), 0, 400 );
    if ( $question === '' ) wp_send_json_error( [ 'message' => 'Escreve uma pergunta.' ], 400 );
    $request = new WP_REST_Request( 'POST' );
    $request->set_param( 'rmbz_telemovel', rmbz_get_current_user_telemovel() );
    $request->set_param( 'question', $question );
    $request->set_param( 'history', [] );
    $response = rmbz_api_handle_ai_ask( $request );
    $payload  = $response instanceof WP_REST_Response ? $response->get_data() : [];
    $status   = $response instanceof WP_REST_Response ? $response->get_status() : 500;
    if ( empty( $payload['success'] ) ) {
        $message = (string) ( $payload['error']['message'] ?? 'Não foi possível responder agora.' );
        wp_send_json_error( [ 'message' => $message ], $status );
    }
    wp_send_json_success( $payload['data'] );
}
add_action( 'wp_ajax_rmbz_vip_ai_ask', 'rmbz_vip_ajax_ai_ask' );
add_action( 'wp_ajax_nopriv_rmbz_vip_ai_ask', 'rmbz_vip_ajax_ai_ask' );

/** Valor atual correspondente a cada meta do catálogo oficial. */
function rmbz_vip_milestone_value( $key, $metrics ) {
    if ( strpos( $key, 'streams_' ) === 0 ) return (float) ( $metrics['total_streams'] ?? 0 );
    if ( strpos( $key, 'earnings_' ) === 0 ) return (float) ( $metrics['total_earnings'] ?? 0 );
    if ( strpos( $key, 'releases_' ) === 0 ) return (float) ( $metrics['releases_live'] ?? 0 );
    if ( strpos( $key, 'tenure_' ) === 0 ) return (float) ( $metrics['days_as_artist'] ?? 0 );
    $map = [
        'first_release_submitted' => 'releases_submitted', 'first_release_live' => 'releases_live',
        'first_ep' => 'max_tracks_in_release', 'first_album' => 'max_tracks_in_release',
        'first_payment' => 'received_any_payment', 'first_split_accepted' => 'splits_accepted_in_own_releases',
        'first_referral' => 'referrals_count', 'referrals_5' => 'referrals_count',
    ];
    return (float) ( $metrics[ $map[ $key ] ?? '' ] ?? 0 );
}

// =============================================================================
// RENDER
// =============================================================================

/**
 * [1.5.416] Dropzone de áudio (upload AJAX) para o formulário de envio nativo
 * do painel VIP. $key = 'site' | 'project'. Mesmo comportamento do template
 * antigo (progress bar + estado de sucesso), mas com as cores do tema.
 */
function rmbz_vip_audio_dropzone( $key ) {
    $key = ( $key === 'project' ) ? 'project' : 'site';
    $icon = $key === 'project' ? '💿' : '🎵';
    $lbl  = $key === 'project' ? 'Clique para carregar a Demo' : 'Clique para carregar a música';
    ob_start(); ?>
    <div class="rvu-audio" id="rvu-dz-<?php echo esc_attr( $key ); ?>" data-key="<?php echo esc_attr( $key ); ?>">
        <div class="rvu-audio-idle">
            <span style="font-size:40px; display:block;"><?php echo $icon; ?></span>
            <div style="font-weight:700; color:var(--text); margin-top:6px;"><?php echo esc_html( $lbl ); ?></div>
            <div style="font-size:11.5px; color:var(--muted);">.WAV ou .MP3 · máx. 50 MB</div>
        </div>
        <input type="file" class="rvu-audio-input" accept=".mp3,.wav,audio/mpeg,audio/wav" style="display:none;">
        <input type="hidden" name="<?php echo $key === 'project' ? 'audio_file_project_url' : 'audio_file_url'; ?>" class="rvu-audio-url">
        <div class="rvu-audio-prog" style="display:none;">
            <div style="font-size:12.5px; color:var(--text2); margin-bottom:8px;">A enviar… 🚀</div>
            <div style="background:var(--elev); border-radius:20px; height:12px; overflow:hidden;"><div class="rvu-audio-bar" style="height:100%; width:0%; background:linear-gradient(90deg,var(--brand),#ffe270); transition:.2s;"></div></div>
            <div class="rvu-audio-pct" style="color:var(--brand-ink); font-size:13px; font-weight:700; margin-top:8px;">0%</div>
        </div>
        <div class="rvu-audio-ok" style="display:none;">
            <span style="font-size:34px; color:var(--success); display:block;">✅</span>
            <div style="color:var(--success); font-weight:700; margin-top:4px;">Upload concluído!</div>
            <div class="rvu-audio-name" style="font-size:11.5px; color:var(--muted); margin-top:2px;"></div>
            <button type="button" class="chip rvu-audio-reset" style="margin-top:8px;">Mudar ficheiro</button>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

/**
 * [1.5.419] ESTÚDIO DE DISTRIBUIÇÃO — takeover de ecrã inteiro dentro da
 * minha-conta. Renderiza o módulo de distribuição REAL (com os seus assets,
 * a correr como página normal) numa camada full-screen, com uma barra de topo
 * "← Voltar ao painel". Assim os fluxos pesados (wizard, splits, analytics)
 * funcionam nativamente sem sair do painel VIP.
 */
function rmbz_vip_render_distro_studio( $telemovel ) {
    $access_error = function_exists( 'rmbz_distro_artist_access_error' )
        ? rmbz_distro_artist_access_error( $telemovel, true )
        : '';
    if ( $access_error !== '' ) {
        $_GET['sect'] = 'distro';
        unset( $_GET['distro_action'], $_GET['id'] );
        rmbz_vip_render_dashboard( $telemovel );
        return;
    }
    if ( ! function_exists( 'rmbz_render_distribution_dashboard' ) ) {
        rmbz_vip_render_dashboard( $telemovel );
        return;
    }
    $back_url = home_url( '/minha-conta/?sect=distro' );
    ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@20..48,300..600,0..1,0" rel="stylesheet">
    <div id="rmbz-vip-studio">
    <style>
    html, body{ overflow:hidden !important; }
    #wpadminbar{ display:none !important; }
    #rmbz-vip-studio{ position:fixed; inset:0; z-index:2147483600; background:#0a0a0b; display:flex; flex-direction:column; }
    #rmbz-vip-studio .studio-top{ flex-shrink:0; display:flex; align-items:center; gap:14px; padding:12px 20px; background:#111114; border-bottom:1px solid #232329; }
    #rmbz-vip-studio .studio-back{ display:inline-flex; align-items:center; gap:8px; background:rgba(255,255,255,.07); border:1px solid rgba(255,255,255,.14); color:#fafafa; text-decoration:none; font-size:13px; font-weight:650; border-radius:100px; padding:9px 18px; font-family:'Roboto Flex',system-ui,sans-serif; }
    #rmbz-vip-studio .studio-back:hover{ background:rgba(255,255,255,.12); }
    #rmbz-vip-studio .studio-ttl{ font-size:14px; font-weight:750; color:#fafafa; font-family:'Bricolage Grotesque',system-ui,sans-serif; }
    #rmbz-vip-studio .studio-body{ flex:1; overflow-y:auto; overflow-x:hidden; -webkit-overflow-scrolling:touch; }
    #rmbz-vip-studio .studio-ms{ font-family:'Material Symbols Rounded'; font-size:20px; line-height:1; }
    /* O módulo usa .rmbz-fullbleed (escapa a 100vw); dentro do estúdio (que já
       é ecrã inteiro) neutraliza-se o breakout para não gerar scroll lateral. */
    #rmbz-vip-studio .rmbz-fullbleed{ position:static !important; left:auto !important; transform:none !important; width:auto !important; max-width:100% !important; margin-left:auto !important; margin-right:auto !important; }
    </style>
    <div class="studio-top">
        <a class="studio-back" href="<?php echo esc_url( $back_url ); ?>"><span class="studio-ms">arrow_back</span> Voltar ao painel</a>
        <span class="studio-ttl">🌍 Estúdio de Distribuição</span>
    </div>
    <div class="studio-body">
        <?php
        // Mesma proteção anti-escape de & que o shortcode usa.
        $st_cc = has_filter( 'the_content', 'convert_chars' );
        $st_wt = has_filter( 'the_content', 'wptexturize' );
        if ( $st_cc ) remove_filter( 'the_content', 'convert_chars' );
        if ( $st_wt ) remove_filter( 'the_content', 'wptexturize' );
        $st_out = rmbz_render_distribution_dashboard(); // ecoa
        if ( is_string( $st_out ) ) echo $st_out;
        if ( $st_cc ) add_filter( 'the_content', 'convert_chars' );
        if ( $st_wt ) add_filter( 'the_content', 'wptexturize' );
        ?>
    </div>
    </div>
    <script>
    (function(){
        var s = document.getElementById('rmbz-vip-studio');
        // Re-parent para o <body> (escapa a stacking contexts do tema).
        if (s && s.parentNode !== document.body) document.body.appendChild(s);
        // Liberta o preload do <head> apenas depois de o takeover estar pronto.
        try {
            document.documentElement.classList.add('rmbz-vip-ready');
            setTimeout(function(){
                var preload = document.getElementById('rmbz-vip-preload');
                if (preload && preload.parentNode) preload.parentNode.removeChild(preload);
                document.documentElement.classList.remove('rmbz-vip-loading', 'rmbz-vip-ready');
            }, 380);
        } catch (e) {}
    })();
    </script>
    <?php
}

function rmbz_vip_render_dashboard( $telemovel ) {
    global $wpdb;
    $fmt = fn( $v ) => number_format( (float) $v, 2, ',', '.' );

    // Resolver a rota antes de carregar os módulos pesados. As fontes que só
    // pertencem a Estatísticas, Notificações e Perfil são carregadas sob demanda.
    $vip_sect = isset( $_GET['sect'] ) ? sanitize_key( wp_unslash( $_GET['sect'] ) ) : 'inicio';
    if ( ! in_array( $vip_sect, [ 'inicio', 'musicas', 'arttracks', 'projetos', 'distro', 'envios', 'financas', 'stats', 'notifs', 'perfil' ], true ) ) $vip_sect = 'inicio';
    $vip_dview = isset( $_GET['dview'] ) ? sanitize_key( wp_unslash( $_GET['dview'] ) ) : 'overview';
    if ( ! in_array( $vip_dview, [ 'overview', 'stats', 'report', 'release-stats', 'history', 'profiles', 'release', 'create', 'somas' ], true ) ) $vip_dview = 'overview';
    $early_vip_permissions = rmbz_vip_plan_permissions( $telemovel );
    $early_distro_block = function_exists( 'rmbz_service_blocked_message' )
        ? rmbz_service_blocked_message( $telemovel, 'block_distribution', 'distribution' )
        : null;
    $early_distro_access = rmbz_vip_is_active( $telemovel )
        && ! empty( $early_vip_permissions['distribute'] )
        && $early_distro_block === null;

    $rvd_history_filter = isset( $_GET['hfilter'] ) ? sanitize_key( wp_unslash( $_GET['hfilter'] ) ) : 'all';
    if ( ! in_array( $rvd_history_filter, [ 'all', 'releases', 'payments', 'splits', 'account' ], true ) ) $rvd_history_filter = 'all';
    $rvd_history_items = [];
    if ( $early_distro_access && $vip_sect === 'distro' && $vip_dview === 'history' ) {
        $history_collectors = [
            'releases' => 'rmbz_api_history_collect_releases',
            'payments' => 'rmbz_api_history_collect_payments',
            'splits'   => 'rmbz_api_history_collect_splits',
            'account'  => 'rmbz_api_history_collect_account',
        ];
        foreach ( $history_collectors as $history_type => $history_fn ) {
            if ( ( $rvd_history_filter === 'all' || $rvd_history_filter === $history_type ) && function_exists( $history_fn ) ) {
                $rvd_history_items = array_merge( $rvd_history_items, (array) call_user_func( $history_fn, $telemovel ) );
            }
        }
        usort( $rvd_history_items, static function ( $a, $b ) {
            return strcmp( (string) ( $b['created_at'] ?? '' ), (string) ( $a['created_at'] ?? '' ) );
        } );
    }

    // ── utilizador + saldos (reais) ──
    $user = $wpdb->get_row( $wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s", $telemovel
    ) );
    $nome    = $user->user_nome ?? 'Artista';
    $email   = ( ! empty( $user->user_email ) && strpos( (string) $user->user_email, '@1mz.local' ) === false ) ? $user->user_email : '';
    $inicial = mb_strtoupper( mb_substr( (string) $nome, 0, 1 ) );
    $saldo_total = (float) ( $user->balance ?? 0 );
    $retiravel   = function_exists( 'rmbz_get_withdrawable_balance' ) ? (float) rmbz_get_withdrawable_balance( $telemovel ) : $saldo_total;
    $promocional = max( 0, $saldo_total - $retiravel );
    $tel9 = preg_replace( '/\D+/', '', (string) $telemovel );
    if ( strlen( $tel9 ) > 9 ) $tel9 = substr( $tel9, -9 );

    // ── VIP ──
    $has_subscription = rmbz_vip_is_active( $telemovel );
    $extra_user = ! empty( $user->extra_data ) ? json_decode( (string) $user->extra_data, true ) : [];
    if ( ! is_array( $extra_user ) ) $extra_user = [];
    $up_perms = rmbz_vip_plan_permissions( $telemovel, $extra_user );
    $plan_distribute = $has_subscription && ! empty( $up_perms['distribute'] );
    $plan_site       = $has_subscription && ! empty( $up_perms['site'] );
    $plan_social     = $has_subscription && ! empty( $up_perms['social'] );
    $plan_video      = $has_subscription && ! empty( $up_perms['video'] );
    $vip_expiry = function_exists( 'rmbz_get_subscription_expiry' ) ? rmbz_get_subscription_expiry( $telemovel ) : null;
    $vip_dias   = $vip_expiry ? max( 0, (int) floor( ( strtotime( $vip_expiry ) - current_time( 'timestamp' ) ) / DAY_IN_SECONDS ) ) : 0;
    $vip_data   = $vip_expiry ? date_i18n( 'd/m/Y', strtotime( $vip_expiry ) ) : '—';

    // ── royalties (distro, defensivo) ──
    $roy_usd = 0.0; $streams_tot = 0;
    $t_stats = $wpdb->prefix . 'rmbz_distro_stats';
    $load_royalties = $vip_sect === 'financas'
        || ( $plan_distribute && in_array( $vip_sect, [ 'inicio', 'distro' ], true ) );
    if ( $load_royalties
         && $wpdb->get_var( "SHOW TABLES LIKE '{$t_stats}'" ) === $t_stats ) {
        $r = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$t_stats} WHERE artist_telemovel = %s", $telemovel ) );
        if ( $r ) { $roy_usd = (float) ( $r->total_earnings ?? 0 ); $streams_tot = (int) ( $r->total_streams ?? 0 ); }
    }
    $cambio  = function_exists( 'rmbz_get_exchange_rate' ) ? (float) rmbz_get_exchange_rate() : 63.50;
    $roy_mt  = $roy_usd * $cambio;
    $patrimonio_total = $saldo_total + $roy_mt;

    // ── projetos (reais — LINHAS COMPLETAS p/ os blocos de gestão) ──
    $projetos = [];
    $project_per_page = 10;
    $project_page = max( 1, isset( $_GET['proj_page'] ) ? absint( $_GET['proj_page'] ) : 1 );
    $project_total = 0;
    $visible_rows = [];
    $t_proj = $wpdb->prefix . 'rmbz_artist_projects';
    if ( $plan_video && in_array( $vip_sect, [ 'inicio', 'projetos' ], true )
         && $wpdb->get_var( "SHOW TABLES LIKE '{$t_proj}'" ) === $t_proj ) {
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$t_proj} WHERE artist_telemovel = %s ORDER BY id DESC", $telemovel
        ) ) ?: [];
        if ( function_exists( 'rmbz_filming_project_hidden_from_artist' ) ) {
            $rows = array_values( array_filter( $rows, static function ( $project ) {
                return ( $project->production_status ?? '' ) !== 'cancelled_no_confirmation'
                    || ! rmbz_filming_project_hidden_from_artist( $project );
            } ) );
        }
        // Sessao live sempre no topo, mesmo quando o artista tem mais projetos
        // do que o limite de uma pagina.
        $live_rows = [];
        $regular_rows = [];
        foreach ( $rows as $project_row ) {
            $project_extra = ! empty( $project_row->extra_data ) ? json_decode( (string) $project_row->extra_data, true ) : [];
            $has_live_session = false;
            if ( is_array( $project_extra ) && ! empty( $project_extra['filming_sessions'] ) && is_array( $project_extra['filming_sessions'] ) ) {
                foreach ( $project_extra['filming_sessions'] as $project_session ) {
                    if ( is_array( $project_session ) && empty( $project_session['ended_at'] ) ) {
                        $has_live_session = true;
                        break;
                    }
                }
            }
            if ( $has_live_session ) $live_rows[] = $project_row;
            else $regular_rows[] = $project_row;
        }
        $rows = array_merge( $live_rows, $regular_rows );
        if ( ! empty( $live_rows ) ) $project_page = 1;
        $project_total = count( $rows );
        $project_pages = max( 1, (int) ceil( $project_total / $project_per_page ) );
        $project_page  = min( $project_page, $project_pages );
        $visible_rows  = $rows;
        $rows = array_slice( $rows, ( $project_page - 1 ) * $project_per_page, $project_per_page );
        foreach ( $rows as $p ) {
            [ $lbl, $tone ] = rmbz_vip_status_meta( $p->production_status ?? '' );
            $x = ! empty( $p->extra_data ) ? json_decode( (string) $p->extra_data, true ) : [];
            $d = ! empty( $p->scenario_details ) ? json_decode( (string) $p->scenario_details, true ) : [];
            $projetos[] = [
                'titulo' => (string) ( $p->project_title ?: '(sem título)' ),
                'estado' => $lbl, 'tone' => $tone,
                'pct'    => rmbz_vip_status_pct( $p->production_status ?? '' ),
                'st'     => (string) ( $p->production_status ?? '' ),
                'data'   => ! empty( $p->created_at ) ? date_i18n( 'd/m/Y', strtotime( (string) $p->created_at ) ) : '',
                'row'    => $p,
                'extra'  => is_array( $x ) ? $x : [],
                'items'  => is_array( $d ) ? $d : [],
            ];
        }
    } elseif ( $plan_video && $vip_sect === 'stats' && $wpdb->get_var( "SHOW TABLES LIKE '{$t_proj}'" ) === $t_proj ) {
        $project_total = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT COUNT(id) FROM {$t_proj} WHERE artist_telemovel = %s", $telemovel
        ) );
    }
    $ativos = 0; $filmando = '';
    foreach ( (array) ( $visible_rows ?? [] ) as $visible_project ) {
        $visible_status = (string) ( $visible_project->production_status ?? '' );
        if ( in_array( $visible_status, [ 'approved','kyc_review','pre-production','filming','editing' ], true ) ) $ativos++;
        if ( $visible_status === 'filming' && $filmando === '' ) $filmando = (string) ( $visible_project->project_title ?: '(sem título)' );
    }
    // Lançamentos = projetos concluídos (tab "Meus Lançamentos" do antigo).
    $lancamentos = array_values( array_filter( $projetos, fn( $pp ) => $pp['st'] === 'done' ) );
    $em_producao = array_values( array_filter( $projetos, fn( $pp ) => $pp['st'] !== 'done' ) );

    // ── [1.5.415] Estado da conta (portado do painel antigo) ──
    // Bloqueios/limitações ativos (com expiração lazy)
    if ( function_exists( 'rmbz_apply_block_expiries' ) ) {
        rmbz_apply_block_expiries( $telemovel );
        // A expiração altera extra_data na BD; recarregar evita manter o botão
        // bloqueado até ao pedido seguinte por causa do objeto lido antes.
        $fresh_extra_raw = $wpdb->get_var( $wpdb->prepare(
            "SELECT extra_data FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s",
            $telemovel
        ) );
        $fresh_extra = $fresh_extra_raw ? json_decode( (string) $fresh_extra_raw, true ) : [];
        if ( is_array( $fresh_extra ) ) {
            $extra_user = $fresh_extra;
            $up_perms = rmbz_vip_plan_permissions( $telemovel, $extra_user );
            $plan_distribute = $has_subscription && ! empty( $up_perms['distribute'] );
            $plan_site       = $has_subscription && ! empty( $up_perms['site'] );
            $plan_social     = $has_subscription && ! empty( $up_perms['social'] );
            $plan_video      = $has_subscription && ! empty( $up_perms['video'] );
        }
    }
    $blocks = function_exists( 'rmbz_user_active_blocks' ) ? rmbz_user_active_blocks( $telemovel ) : [];
    $blocks = array_values( array_filter( (array) $blocks, fn( $b ) => ( $b['key'] ?? '' ) !== 'is_banned' ) );
    // Convites de participação (feat)
    $feat_invites = function_exists( 'rmbz_feat_pending_for' ) ? rmbz_feat_pending_for( $telemovel ) : [];
    // Multa por atraso (projeto em curso sem subscrição)
    $fine = function_exists( 'rmbz_project_overdue_info' ) ? rmbz_project_overdue_info( $telemovel ) : [];
    // Popup direto do admin
    $admin_popup = ( isset( $extra_user['admin_popup'] ) && is_array( $extra_user['admin_popup'] ) ) ? $extra_user['admin_popup'] : null;
    // [1.5.438] Avisos do dashboard antigo que viviam no wp_footer — por baixo
    // do painel (z-index) ficavam INVISÍVEIS e alguns eram CONSUMIDOS sem se
    // verem. Mapeados nativos:
    // 1) Boas-vindas VIP (transient, consumida aqui — o footer já não a vê)
    $vip_congrats = null;
    $cg_payload = get_transient( 'rmbz_vip_congrats_' . $telemovel );
    if ( is_array( $cg_payload ) && ! empty( $cg_payload['event'] ) ) {
        delete_transient( 'rmbz_vip_congrats_' . $telemovel );
        $vip_congrats = $cg_payload;
    }
    // 2) Celebração de cupão resgatado (sessão, consumida aqui)
    $coupon_cel = null;
    if ( ! empty( $_SESSION['rmbz_coupon_celebrate'] ) && is_array( $_SESSION['rmbz_coupon_celebrate'] ) ) {
        $coupon_cel = $_SESSION['rmbz_coupon_celebrate'];
        unset( $_SESSION['rmbz_coupon_celebrate'] );
    }
    // [1.5.439] Pedido de DESISTÊNCIA do projeto — o admin pediu a decisão do
    // artista; ao entrar no Início aparece o modal com a compilação + o
    // conselho da IA (guardado na BD pelo módulo project-giveup.php).
    $giveup_ask = null;
    $gu_rows = $vip_sect === 'inicio' ? ( $wpdb->get_results( $wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}rmbz_artist_projects
         WHERE artist_telemovel = %s AND extra_data LIKE %s
         ORDER BY id DESC LIMIT 5",
        $telemovel, '%"giveup"%'
    ) ) ?: [] ) : [];
    foreach ( $gu_rows as $gu_p ) {
        $gu_x = json_decode( (string) $gu_p->extra_data, true );
        $gu_g = is_array( $gu_x['giveup'] ?? null ) ? $gu_x['giveup'] : null;
        if ( $gu_g && ( $gu_g['status'] ?? '' ) === 'pending' && ( $gu_g['mode'] ?? '' ) === 'request' ) {
            $giveup_ask = [ 'p' => $gu_p, 'g' => $gu_g ];
            break;
        }
    }

    // 3) Projeto cancelado (user_meta; só sai com "Compreendi" → AJAX dismiss)
    $cancel_notice = null; $cancel_nonce = '';
    if ( is_user_logged_in() ) {
        $cn_list = get_user_meta( get_current_user_id(), 'rmbz_cancel_notices', true );
        if ( is_array( $cn_list ) && ! empty( $cn_list ) ) {
            $cancel_notice = end( $cn_list );
            $cancel_nonce  = wp_create_nonce( 'rmbz_cancel_notice_dismiss' );
        }
    }
    // Bloqueios financeiros canónicos: utilizador, prazo de expiração e global.
    // O helper reaplica expirações antes de decidir, evitando manter na interface
    // um bloqueio temporário que já terminou.
    $dep_block_message = function_exists( 'rmbz_service_blocked_message' )
        ? rmbz_service_blocked_message( $telemovel, 'block_deposits', 'deposits' )
        : ( ! empty( $extra_user['block_deposits'] ) ? 'Os depósitos estão bloqueados na tua conta.' : null );
    $wd_block_message = function_exists( 'rmbz_service_blocked_message' )
        ? rmbz_service_blocked_message( $telemovel, 'block_withdrawals', 'withdrawals' )
        : ( ! empty( $extra_user['block_withdrawals'] ) ? 'Os levantamentos estão bloqueados na tua conta.' : null );
    $dep_blocked = $dep_block_message !== null;
    $wd_blocked  = $wd_block_message !== null;
    // Email real obrigatório / OTP pendente (mesma regra do antigo)
    $is_fake_email  = ( empty( $user->user_email ) || strpos( (string) $user->user_email, '@1mz.local' ) !== false );
    $has_approved_project = $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$t_proj} WHERE artist_telemovel = %s AND production_status NOT IN ('pending_review','rejected','correction') LIMIT 1", $telemovel
    ) );
    $is_pending_otp = isset( $_SESSION['rmbz_verify_email_pending'] ) && $_SESSION['rmbz_verify_email_pending'] === true;

    // ── Acesso aos serviços do pacote atual ──
    $up_block_promo = ! empty( $extra_user['block_promotions'] );
    $up_block_video = ! empty( $extra_user['block_video_applications'] );
    $up_g_site   = function_exists( 'rmbz_is_globally_blocked' ) ? rmbz_is_globally_blocked( 'site' )   : false;
    $up_g_social = function_exists( 'rmbz_is_globally_blocked' ) ? rmbz_is_globally_blocked( 'social' ) : false;
    $up_g_video  = function_exists( 'rmbz_is_globally_blocked' ) ? rmbz_is_globally_blocked( 'video' )  : false;
    $perm_site   = $plan_site   && ! ( $up_block_promo || $up_g_site );
    $perm_social = $plan_social && ! ( $up_block_promo || $up_g_social );
    $perm_video  = $plan_video  && ! ( $up_block_video || $up_g_video );
    $motivo_site   = ( $up_g_site && ! $up_block_promo )   ? 'Suspenso (Plataforma)' : ( $up_block_promo ? 'Bloqueado (Admin)' : 'Não incluído no plano' );
    $motivo_social = ( $up_g_social && ! $up_block_promo ) ? 'Suspenso (Plataforma)' : ( $up_block_promo ? 'Bloqueado (Admin)' : 'Não incluído no plano' );
    $motivo_video  = ( $up_g_video && ! $up_block_video )  ? 'Suspenso (Plataforma)' : ( $up_block_video ? 'Bloqueado (Admin)' : 'Não incluído no plano' );

    $distribution_block = null;
    if ( $plan_distribute && function_exists( 'rmbz_service_blocked_message' ) ) {
        $distribution_block = rmbz_service_blocked_message( $telemovel, 'block_distribution', 'distribution' );
    }
    $distro_access  = $plan_distribute && $distribution_block === null;
    $project_access = $plan_video;
    $envios_access  = $perm_site || $perm_social || $perm_video;
    $partnership_access = function_exists( 'rmbz_partnership_has_access' )
        && rmbz_partnership_has_access( $telemovel );
    $distro_gate_reason = ! $has_subscription ? 'inactive' : ( ! $plan_distribute ? 'plan' : 'restricted' );
    $project_gate_reason = ! $has_subscription ? 'inactive' : ( ! $plan_video ? 'plan' : 'restricted' );
    $envios_plan_included = $plan_site || $plan_social || $plan_video;
    $envios_gate_reason = ! $has_subscription ? 'inactive' : ( ! $envios_plan_included ? 'plan' : 'restricted' );
    $current_section_locked = ( $vip_sect === 'distro' && ! $distro_access )
        || ( $vip_sect === 'projetos' && ! $project_access )
        || ( $vip_sect === 'envios' && ! $envios_access );

    // ── Submissões de música (apenas serviços disponíveis no plano) ──
    $submissions = [];
    $submission_per_page = 10;
    $submission_page = max( 1, isset( $_GET['sub_page'] ) ? absint( $_GET['sub_page'] ) : 1 );
    $submission_kind = isset( $_GET['sub_kind'] ) ? sanitize_key( wp_unslash( $_GET['sub_kind'] ) ) : 'all';
    if ( ! in_array( $submission_kind, [ 'all', 'site', 'social' ], true ) ) $submission_kind = 'all';
    if ( $submission_kind === 'site' && ! $perm_site ) $submission_kind = 'all';
    if ( $submission_kind === 'social' && ! $perm_social ) $submission_kind = 'all';
    $submission_total = 0;
    $submission_counts = [ 'all' => 0, 'site' => 0, 'social' => 0 ];
    $t_subs = $wpdb->prefix . 'rmbz_artist_submissions';
    $submission_allowed_types = [];
    if ( $perm_site ) $submission_allowed_types[] = 'Publicação Site';
    if ( $perm_social ) $submission_allowed_types[] = 'Redes Sociais';
    if ( $vip_sect === 'envios' && ! empty( $submission_allowed_types )
         && $wpdb->get_var( "SHOW TABLES LIKE '{$t_subs}'" ) === $t_subs ) {
        $submission_placeholders = implode( ', ', array_fill( 0, count( $submission_allowed_types ), '%s' ) );
        $submission_scope = "artist_telemovel = %s AND scenario_type IN ({$submission_placeholders})";
        $submission_scope_params = array_merge( [ $telemovel ], $submission_allowed_types );
        $submission_summary = $wpdb->get_row( $wpdb->prepare(
            "SELECT COUNT(id) AS total,
                    SUM(CASE WHEN scenario_type = 'Publicação Site' THEN 1 ELSE 0 END) AS site_total,
                    SUM(CASE WHEN scenario_type = 'Redes Sociais' THEN 1 ELSE 0 END) AS social_total
             FROM {$t_subs} WHERE {$submission_scope}",
            ...$submission_scope_params
        ) );
        $submission_counts = [
            'all'    => (int) ( $submission_summary->total ?? 0 ),
            'site'   => (int) ( $submission_summary->site_total ?? 0 ),
            'social' => (int) ( $submission_summary->social_total ?? 0 ),
        ];
        $submission_where = $submission_scope;
        $submission_params = $submission_scope_params;
        if ( $submission_kind === 'site' ) {
            $submission_where .= ' AND scenario_type = %s';
            $submission_params[] = 'Publicação Site';
        } elseif ( $submission_kind === 'social' ) {
            $submission_where .= ' AND scenario_type = %s';
            $submission_params[] = 'Redes Sociais';
        }
        $submission_total = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT COUNT(id) FROM {$t_subs} WHERE {$submission_where}",
            ...$submission_params
        ) );
        $submission_pages = max( 1, (int) ceil( $submission_total / $submission_per_page ) );
        $submission_page  = min( $submission_page, $submission_pages );
        $submission_query_params = array_merge( $submission_params, [ $submission_per_page, ( $submission_page - 1 ) * $submission_per_page ] );
        $submissions = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$t_subs} WHERE {$submission_where} ORDER BY id DESC LIMIT %d OFFSET %d",
            ...$submission_query_params
        ) ) ?: [];
    }

    // Serviços contratados do plano atual. A permissão diz o que pertence ao
    // plano; os bloqueios dizem apenas se o serviço está disponível agora.
    $vip_plan_name = trim( (string) ( $extra_user['active_plan_name'] ?? '' ) );
    if ( $vip_plan_name === '' ) $vip_plan_name = 'Plano VIP';
    $vip_service_items = [];
    if ( $vip_sect === 'perfil' ) {
        $vip_service_catalog = [
            'distribute' => [
                'icon'        => 'public',
                'title'       => 'Distribuição digital',
                'description' => 'Lança músicas nas lojas digitais e acompanha os teus releases.',
                'nav'         => 'distro',
                'available'   => $distribution_block === null,
                'reason'      => (string) ( $distribution_block ?? '' ),
            ],
            'site' => [
                'icon'        => 'language',
                'title'       => 'Publicação no site',
                'description' => 'Envia músicas para publicação nos canais oficiais da 1MZ.',
                'nav'         => 'envios',
                'available'   => $perm_site,
                'reason'      => $perm_site ? '' : $motivo_site,
            ],
            'social' => [
                'icon'        => 'share',
                'title'       => 'Promoção nas redes',
                'description' => 'Candidata a tua música para promoção nas redes sociais.',
                'nav'         => 'envios',
                'available'   => $perm_social,
                'reason'      => $perm_social ? '' : $motivo_social,
            ],
            'video' => [
                'icon'        => 'movie',
                'title'       => 'Videoclipe profissional',
                'description' => 'Candidata a tua música e acompanha a produção do videoclipe.',
                'nav'         => 'envios',
                'available'   => $perm_video,
                'reason'      => $perm_video ? '' : $motivo_video,
            ],
            'ai' => [
                'icon'        => 'psychology',
                'title'       => 'Assistente de IA 1MZ',
                'description' => 'Analisa os teus dados e recebe orientação personalizada.',
                'nav'         => 'stats',
                'available'   => $has_subscription,
                'reason'      => '',
            ],
        ];
        foreach ( $vip_service_catalog as $service_key => $service ) {
            if ( ! empty( $up_perms[ $service_key ] ) ) $vip_service_items[ $service_key ] = $service;
        }
    }
    // Envio pendente? (bloqueia o formulário com blur, como no antigo)
    $pendente_tipo = '';
    $up_pend = '';
    if ( $vip_sect === 'envios' && $envios_access && ! empty( $submission_allowed_types ) ) {
        $pending_placeholders = implode( ', ', array_fill( 0, count( $submission_allowed_types ), '%s' ) );
        $pending_params = array_merge( [ $telemovel ], $submission_allowed_types );
        $up_pend = $wpdb->get_var( $wpdb->prepare(
            "SELECT scenario_type FROM {$t_subs} WHERE artist_telemovel = %s AND scenario_type IN ({$pending_placeholders}) AND review_status = 'pendente' LIMIT 1",
            ...$pending_params
        ) );
    }
    if ( $up_pend ) {
        $pendente_tipo = (string) $up_pend;
    } elseif ( $vip_sect === 'envios' && $perm_video && $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$t_proj} WHERE artist_telemovel = %s AND production_status = 'pending_review' LIMIT 1", $telemovel
    ) ) ) {
        $pendente_tipo = 'Candidatura a Videoclipe';
    }
    $up_nonce_form  = wp_create_nonce( 'rmbz_frontend_upload_nonce' );
    $up_nonce_audio = wp_create_nonce( 'rmbz_audio_upload_nonce' );
    $up_nonce_feat  = wp_create_nonce( 'rmbz_feat_check' );

    // ── Finanças (visão geral + depósitos + levantamentos + extrato) ──
    $finance_view = isset( $_GET['fview'] ) ? sanitize_key( wp_unslash( $_GET['fview'] ) ) : 'overview';
    if ( ! in_array( $finance_view, [ 'overview', 'deposits', 'withdrawals', 'statement' ], true ) ) {
        $finance_view = 'overview';
    }
    // Links de paginação antigos passam diretamente para a vista correspondente.
    if ( ! isset( $_GET['fview'] ) ) {
        if ( isset( $_GET['tx_page'] ) ) $finance_view = 'statement';
        elseif ( isset( $_GET['dep_page'] ) ) $finance_view = 'deposits';
        elseif ( isset( $_GET['wd_page'] ) ) $finance_view = 'withdrawals';
    }

    $finance_per_page   = 10;
    $statement_per_page = 15;
    $tx_page  = max( 1, isset( $_GET['tx_page'] ) ? absint( $_GET['tx_page'] ) : 1 );
    $dep_page = max( 1, isset( $_GET['dep_page'] ) ? absint( $_GET['dep_page'] ) : 1 );
    $wd_page  = max( 1, isset( $_GET['wd_page'] ) ? absint( $_GET['wd_page'] ) : 1 );
    $tx_search = isset( $_GET['tx_q'] ) ? sanitize_text_field( wp_unslash( $_GET['tx_q'] ) ) : '';
    $tx_flow   = isset( $_GET['tx_flow'] ) ? sanitize_key( wp_unslash( $_GET['tx_flow'] ) ) : 'all';
    if ( ! in_array( $tx_flow, [ 'all', 'credit', 'debit', 'locked' ], true ) ) $tx_flow = 'all';
    $t_tx = $wpdb->prefix . 'rmbz_wallet_transactions';
    $t_dep = $wpdb->prefix . 'rmbz_deposit_requests';
    $t_wd = $wpdb->prefix . 'rmbz_withdrawal_requests';
    $tx_total = 0; $tx_total_all = 0; $tx_credit_total = 0.0; $tx_debit_total = 0.0; $dep_total = 0; $wd_total = 0;
    $dep_pending_total = 0; $wd_pending_total = 0;
    $transacoes = []; $depositos = []; $levantamentos = [];
    $has_pending_deposit = false; $has_pending_wd = false;
    if ( $vip_sect === 'financas' ) {
        // A chave desta tabela é transaction_id (não id). O COUNT(id) anterior
        // falhava no esquema atual e fazia o novo tema mostrar o extrato vazio.
        $tx_totals = $wpdb->get_row( $wpdb->prepare(
            "SELECT COUNT(transaction_id) AS total,
                    COALESCE(SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END), 0) AS credits,
                    COALESCE(ABS(SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END)), 0) AS debits
             FROM {$t_tx} WHERE user_telemovel = %s",
            $telemovel
        ) );
        $tx_total_all    = (int) ( $tx_totals->total ?? 0 );
        $tx_credit_total = (float) ( $tx_totals->credits ?? 0 );
        $tx_debit_total  = (float) ( $tx_totals->debits ?? 0 );

        $tx_where  = 'user_telemovel = %s';
        $tx_params = [ $telemovel ];
        if ( $tx_search !== '' ) {
            $tx_like = '%' . $wpdb->esc_like( $tx_search ) . '%';
            $tx_where .= ' AND (details LIKE %s OR type LIKE %s)';
            $tx_params[] = $tx_like;
            $tx_params[] = $tx_like;
        }
        if ( $tx_flow === 'credit' ) $tx_where .= ' AND amount > 0';
        elseif ( $tx_flow === 'debit' ) $tx_where .= ' AND amount < 0';
        elseif ( $tx_flow === 'locked' ) $tx_where .= ' AND is_unlocked = 0';

        $tx_total = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT COUNT(transaction_id) FROM {$t_tx} WHERE {$tx_where}",
            ...$tx_params
        ) );
        $dep_summary = $wpdb->get_row( $wpdb->prepare(
            "SELECT COUNT(id) AS total, SUM(CASE WHEN status IN ('pendente','pending') THEN 1 ELSE 0 END) AS pending FROM {$t_dep} WHERE user_telemovel = %s",
            $telemovel
        ) );
        $wd_summary = $wpdb->get_row( $wpdb->prepare(
            "SELECT COUNT(id) AS total, SUM(CASE WHEN status IN ('pendente','pending') THEN 1 ELSE 0 END) AS pending FROM {$t_wd} WHERE user_telemovel = %s",
            $telemovel
        ) );
        $dep_total = (int) ( $dep_summary->total ?? 0 );
        $wd_total  = (int) ( $wd_summary->total ?? 0 );
        $dep_pending_total = (int) ( $dep_summary->pending ?? 0 );
        $wd_pending_total  = (int) ( $wd_summary->pending ?? 0 );
        $tx_page  = min( $tx_page,  max( 1, (int) ceil( $tx_total / $statement_per_page ) ) );
        $dep_page = min( $dep_page, max( 1, (int) ceil( $dep_total / $finance_per_page ) ) );
        $wd_page  = min( $wd_page,  max( 1, (int) ceil( $wd_total / $finance_per_page ) ) );
        $tx_query_params = array_merge( $tx_params, [ $statement_per_page, ( $tx_page - 1 ) * $statement_per_page ] );
        $transacoes = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$t_tx} WHERE {$tx_where} ORDER BY transaction_date DESC, transaction_id DESC LIMIT %d OFFSET %d",
            ...$tx_query_params
        ) ) ?: [];
        $depositos = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$t_dep} WHERE user_telemovel = %s ORDER BY request_date DESC LIMIT %d OFFSET %d",
            $telemovel, $finance_per_page, ( $dep_page - 1 ) * $finance_per_page
        ) ) ?: [];
        $levantamentos = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$t_wd} WHERE user_telemovel = %s ORDER BY request_date DESC LIMIT %d OFFSET %d",
            $telemovel, $finance_per_page, ( $wd_page - 1 ) * $finance_per_page
        ) ) ?: [];
    }
    if ( in_array( $vip_sect, [ 'inicio', 'financas' ], true ) ) {
        $has_pending_deposit = (bool) $wpdb->get_var( $wpdb->prepare(
            "SELECT id FROM {$t_dep} WHERE user_telemovel = %s AND status = 'pendente' LIMIT 1", $telemovel
        ) );
        $has_pending_wd = (bool) $wpdb->get_var( $wpdb->prepare(
            "SELECT id FROM {$t_wd} WHERE user_telemovel = %s AND status = 'pendente' LIMIT 1", $telemovel
        ) );
    }

    // ── Distribuição: contagens + lista de releases (overview nativo) ──
    $rel_live = 0; $rel_returned = 0; $dist_releases = []; $dist_total = 0; $dist_catalog_total = 0;
    $dist_per_page = 12;
    $dist_page = max( 1, isset( $_GET['rel_page'] ) ? absint( $_GET['rel_page'] ) : 1 );
    $dist_search = isset( $_GET['rel_q'] ) ? sanitize_text_field( wp_unslash( $_GET['rel_q'] ) ) : '';
    $dist_type_filter = isset( $_GET['rel_type'] ) ? sanitize_key( wp_unslash( $_GET['rel_type'] ) ) : '';
    if ( ! in_array( $dist_type_filter, [ '', 'single', 'ep', 'album' ], true ) ) $dist_type_filter = '';
    $dist_status_filter = isset( $_GET['rel_status'] ) ? sanitize_key( wp_unslash( $_GET['rel_status'] ) ) : '';
    if ( ! in_array( $dist_status_filter, [ '', 'draft', 'review', 'live', 'returned', 'rejected' ], true ) ) $dist_status_filter = '';
    $t_rel = $wpdb->prefix . 'rmbz_distro_releases';
    // [1.5.430] Definido AQUI (antes do loader do detalhe do release) — o bug
    // dos "ganhos $0" era este nome só ser definido mais abaixo, na secção de
    // Estatísticas: o detalhe fazia SHOW TABLES LIKE '' (variável indefinida),
    // o check falhava em silêncio e streams/ganhos ficavam sempre a 0.
    $t_daily = $wpdb->prefix . 'rmbz_distro_daily_stats';
    if ( $distro_access && $vip_sect === 'distro' && $wpdb->get_var( "SHOW TABLES LIKE '{$t_rel}'" ) === $t_rel ) {
        $rel_live     = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(id) FROM {$t_rel} WHERE artist_telemovel = %s AND status IN ('live','distribuido')", $telemovel ) );
        $rel_returned = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(id) FROM {$t_rel} WHERE artist_telemovel = %s AND status = 'returned'", $telemovel ) );
        $dist_catalog_total = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(id) FROM {$t_rel} WHERE artist_telemovel = %s", $telemovel ) );
        $dist_where = "artist_telemovel = %s";
        $dist_params = [ $telemovel ];
        if ( $dist_search !== '' ) { $dist_where .= ' AND title LIKE %s'; $dist_params[] = '%' . $wpdb->esc_like( $dist_search ) . '%'; }
        if ( $dist_type_filter !== '' ) { $dist_where .= ' AND release_type = %s'; $dist_params[] = $dist_type_filter; }
        if ( $dist_status_filter === 'draft' ) $dist_where .= " AND status IN ('incomplete','draft')";
        elseif ( $dist_status_filter === 'review' ) $dist_where .= " AND status IN ('pendente','pending','submitted','approved','delivered')";
        elseif ( $dist_status_filter === 'live' ) $dist_where .= " AND status IN ('live','distribuido')";
        elseif ( $dist_status_filter !== '' ) { $dist_where .= ' AND status = %s'; $dist_params[] = $dist_status_filter; }
        $dist_total = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(id) FROM {$t_rel} WHERE {$dist_where}", $dist_params ) );
        $dist_page    = min( $dist_page, max( 1, (int) ceil( $dist_total / $dist_per_page ) ) );
        $dist_list_params = array_merge( $dist_params, [ $dist_per_page, ( $dist_page - 1 ) * $dist_per_page ] );
        $dist_releases = $wpdb->get_results( $wpdb->prepare(
            "SELECT id, title, status, cover_image, release_type, created_at FROM {$t_rel} WHERE {$dist_where} ORDER BY created_at DESC LIMIT %d OFFSET %d",
            $dist_list_params
        ) ) ?: [];
    }
    // [1.5.419] Os fluxos pesados abrem no ESTÚDIO (takeover) DENTRO da
    // minha-conta — ?distro_action= na própria página dispara o full-screen.
    $dist_url = home_url( '/minha-conta/' );

    // [1.5.422] Wizard nativo de CRIAR LANÇAMENTO — nonces + dados dos passos.
    $rvd_nonce_distro = wp_create_nonce( 'rmbz_distro_nonce' );      // save_draft/platforms/track/cover/finalize
    $rvd_nonce_upload = wp_create_nonce( 'onemz_music_upload_nonce' ); // upload de áudio
    $rvd_genres = [ 'Hip Hop','Afrobeat','Pandza','Kizomba','R&B','Gospel','Pop','Eletrónica','Outro' ];
    // [1.5.425] Catálogo REAL de lojas (24, por tier), regiões e serviços
    // exclusivos — para o passo 2 nativo bater com o módulo.
    $rvd_dsp_cat = $distro_access && $vip_sect === 'distro'
        ? ( function_exists( 'rmbz_distro_dsp_catalog' ) ? rmbz_distro_dsp_catalog()
            : ( function_exists( 'rmbz_distro_dsp_catalog_builtin' ) ? rmbz_distro_dsp_catalog_builtin() : [] ) )
        : [];
    $rvd_dsp_by_tier = [ 1 => [], 2 => [], 3 => [] ];
    foreach ( (array) $rvd_dsp_cat as $slug => $meta ) {
        $tier = (int) ( $meta['tier'] ?? 1 ); if ( ! isset( $rvd_dsp_by_tier[ $tier ] ) ) $tier = 3;
        $rvd_dsp_by_tier[ $tier ][ $slug ] = (string) ( $meta['name'] ?? $slug );
    }
    $rvd_tier_labels = [
        1 => 'Tier 1 — Essenciais (cobrem 95% dos streams globais)',
        2 => 'Tier 2 — Regionais (relevantes para a tua audiência)',
        3 => 'Tier 3 — Nicho e Ásia',
    ];
    // [1.5.426] EDITAR rascunho no wizard nativo: ?dview=create&rid=X carrega
    // o release + lojas + faixas do artista para pré-preencher o wizard.
    $rvw_edit = null;
    $rvw_edit_release = null;
    $rvw_edit_id = isset( $_GET['dview'], $_GET['rid'] ) && $_GET['dview'] === 'create' ? absint( $_GET['rid'] ) : 0;
    if ( $distro_access && $vip_sect === 'distro' && $rvw_edit_id > 0 ) {
        $er = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$t_rel} WHERE id = %d AND artist_telemovel = %s", $rvw_edit_id, $telemovel
        ) );
        if ( $er && in_array( (string) $er->status, [ 'incomplete', 'draft', 'returned' ], true ) ) {
            $rvw_edit_release = $er;
            // Lojas / territórios / exclusivos
            $ep = $wpdb->get_row( $wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}rmbz_distro_release_platforms WHERE release_id = %d", $rvw_edit_id
            ) );
            $ep_dsps = $ep && ! empty( $ep->dsp_list ) ? (array) json_decode( $ep->dsp_list, true ) : [];
            $ep_terr = $ep && ! empty( $ep->territory_list ) ? (array) json_decode( $ep->territory_list, true ) : [];
            // Faixas com metadata completa. O editor substitui extra_data ao
            // gravar, por isso o wizard nunca pode pré-carregar só um resumo.
            $et_rows = $wpdb->get_results( $wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}rmbz_distro_tracks WHERE release_id = %d ORDER BY track_order ASC", $rvw_edit_id
            ) ) ?: [];
            $et_tracks = [];
            foreach ( $et_rows as $tr ) {
                $tx = ! empty( $tr->extra_data ) ? json_decode( $tr->extra_data, true ) : [];
                if ( ! is_array( $tx ) ) $tx = [];
                $sw = ( is_array( $tx ) && ! empty( $tx['songwriters'][0]['name'] ) ) ? (string) $tx['songwriters'][0]['name'] : '';
                $split_rows = function_exists( 'rmbz_track_get_splits' ) ? rmbz_track_get_splits( (int) $tr->id ) : [];
                $track_splits = [];
                foreach ( $split_rows as $split ) {
                    $track_splits[] = [
                        'name'       => (string) ( $split->collaborator_name ?? '' ),
                        'telemovel'  => (string) ( $split->collaborator_telemovel ?? '' ),
                        'percentage'=> (float) ( $split->percentage ?? 0 ),
                        'role'       => (string) ( $split->role ?? 'feature' ),
                    ];
                }
                $audio_url = (string) ( $tr->audio_url ?? '' );
                $et_tracks[] = [
                    'id' => (int) $tr->id,
                    'title' => (string) ( $tr->track_title === 'Sem título' ? '' : $tr->track_title ),
                    'songwriter' => $sw,
                    'explicit' => ! empty( $tr->is_explicit ),
                    'name' => $audio_url ? wp_basename( (string) wp_parse_url( $audio_url, PHP_URL_PATH ) ) : (string) ( $tr->track_title ?: 'faixa' ),
                    'url' => $audio_url,
                    'loaded' => true,
                    'meta' => [
                        'language'                => (string) ( $tx['language'] ?? $er->language ?? 'Portuguese' ),
                        'isrc_code'               => (string) ( $tr->isrc_code ?? '' ),
                        'is_instrumental'         => ! empty( $tx['is_instrumental'] ) ? 1 : 0,
                        'collaborators'           => array_values( (array) ( $tx['collaborators'] ?? [] ) ),
                        'songwriters'             => array_values( (array) ( $tx['songwriters'] ?? [] ) ),
                        'has_lyrics'              => ! empty( $tx['has_lyrics'] ) ? 1 : 0,
                        'lyrics'                  => (string) ( $tx['lyrics'] ?? '' ),
                        'previously_released'     => ! empty( $tx['previously_released'] ) ? 1 : 0,
                        'original_isrc'           => (string) ( $tx['original_isrc'] ?? '' ),
                        'is_cover'                => ! empty( $tx['is_cover'] ) ? 1 : 0,
                        'cover_original_title'    => (string) ( $tx['cover_original_title'] ?? '' ),
                        'cover_original_composer' => (string) ( $tx['cover_original_composer'] ?? '' ),
                        'preview_start_seconds'   => (int) ( $tx['preview_start_seconds'] ?? 0 ),
                        'moods'                   => array_values( (array) ( $tx['moods'] ?? [] ) ),
                        'splits'                  => $track_splits,
                        'duration'                => (int) ( $tx['duration_seconds'] ?? 0 ),
                    ],
                ];
            }
            $rvw_edit = [
                'id'         => (int) $er->id,
                'status'     => (string) $er->status,
                'title'      => (string) $er->title,
                'language'   => (string) ( $er->language ?: 'Portuguese' ),
                'genre'      => (string) $er->primary_genre,
                'type'       => (string) ( $er->release_type ?: 'single' ),
                'date'       => (string) ( $er->release_date ?: '' ),
                'legacy'     => ! empty( $er->is_legacy ),
                'label'      => (string) ( $er->label_name ?? '' ),
                'recloc'     => (string) ( $er->recording_location ?? '' ),
                'upc'        => (string) ( $er->upc_code ?? '' ),
                'cover'      => (string) ( $er->cover_image ?? '' ),
                'dsps'       => array_values( array_map( 'strval', $ep_dsps ) ),
                'terr_mode'  => (string) ( $ep->territory_mode ?? 'worldwide' ),
                'terr'       => array_values( array_map( 'strval', $ep_terr ) ),
                'yt'         => $ep && (string) ( $ep->yt_content_id_status ?? '' ) === 'requested',
                'fb'         => $ep && (string) ( $ep->fb_monet_status ?? '' ) === 'requested',
                'tt'         => $ep && (string) ( $ep->tt_monet_status ?? '' ) === 'requested',
                'tracks'     => $et_tracks,
            ];
        }
    }

    // [1.5.429] DETALHE do release NATIVO: ?dview=release&rid=X.
    $rvd_detail = null;
    $rvd_detail_id = isset( $_GET['dview'], $_GET['rid'] ) && $_GET['dview'] === 'release' ? absint( $_GET['rid'] ) : 0;
    if ( $distro_access && $vip_sect === 'distro' && $rvd_detail_id > 0 ) {
        $dr = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$t_rel} WHERE id = %d AND artist_telemovel = %s", $rvd_detail_id, $telemovel
        ) );
        if ( $dr ) {
            $dp = $wpdb->get_row( $wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}rmbz_distro_release_platforms WHERE release_id = %d", $rvd_detail_id
            ) );
            $dp_dsps = $dp && ! empty( $dp->dsp_list ) ? (array) json_decode( $dp->dsp_list, true ) : [];
            $dcat = function_exists( 'rmbz_distro_dsp_catalog' ) ? rmbz_distro_dsp_catalog() : [];
            $dp_dsp_names = [];
            foreach ( $dp_dsps as $ds ) $dp_dsp_names[ (string) $ds ] = (string) ( $dcat[ $ds ]['name'] ?? $ds );
            $dtr = $wpdb->get_results( $wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}rmbz_distro_tracks WHERE release_id = %d ORDER BY track_order ASC", $rvd_detail_id
            ) ) ?: [];
            $d_tracks = [];
            foreach ( $dtr as $tr ) {
                $tx = ! empty( $tr->extra_data ) ? json_decode( $tr->extra_data, true ) : [];
                $dur = ( is_array( $tx ) && ! empty( $tx['duration_seconds'] ) ) ? (int) $tx['duration_seconds'] : 0;
                $d_tracks[] = [
                    'title'    => (string) $tr->track_title,
                    'isrc'     => (string) ( $tr->isrc_code ?? '' ),
                    'explicit' => ! empty( $tr->is_explicit ),
                    'dur'      => $dur > 0 ? sprintf( '%d:%02d', intdiv( $dur, 60 ), $dur % 60 ) : '',
                ];
            }
            // Streams/ganhos do release (se houver).
            // [1.5.430] BUG dos ganhos $0: $t_daily só era definido MAIS
            // ABAIXO (secção Estatísticas) — aqui o SHOW TABLES corria com
            // string vazia, falhava em silêncio e streams/ganhos ficavam 0.
            // Agora $t_daily é definido no topo, junto do $t_rel.
            // Além disso a soma liga por release_id DIRETO **ou** pelas faixas
            // do release (track_id) — a análise oficial do estúdio soma por
            // d.track_id = t.id, e imports legacy podem ter release_id vazio.
            // Cada linha do daily_stats é uma linha só → o OR conta-a uma vez.
            $d_streams = 0; $d_earn = 0.0;
            if ( $wpdb->get_var( "SHOW TABLES LIKE '{$t_daily}'" ) === $t_daily ) {
                $t_tracks = $wpdb->prefix . 'rmbz_distro_tracks';
                $ds_row = $wpdb->get_row( $wpdb->prepare(
                    "SELECT COALESCE(SUM(streams),0) s, COALESCE(SUM(sales),0) e
                     FROM {$t_daily}
                     WHERE release_id = %d
                        OR track_id IN ( SELECT id FROM {$t_tracks} WHERE release_id = %d )",
                    $rvd_detail_id, $rvd_detail_id
                ) );
                if ( $ds_row ) { $d_streams = (int) $ds_row->s; $d_earn = (float) $ds_row->e; }
            }
            // [1.5.436] Mapeamento COMPLETO do detalhe do estúdio antigo
            // (distribution-single-view.php + release-tracker.php) no nativo.
            $d_status = (string) $dr->status;
            // Fase do tracker (mapa de rmbz_tracker_phase_from_status)
            $d_phase_map = [ 'pendente' => 2, 'pending' => 2, 'submitted' => 2, 'returned' => 2, 'approved' => 3, 'delivered' => 4, 'live' => 5, 'distribuido' => 5, 'rejected' => -1, 'rejeitado' => -1, 'takedown_requested' => -2, 'taken_down' => -2 ];
            $d_phase = function_exists( 'rmbz_tracker_phase_from_status' ) ? rmbz_tracker_phase_from_status( $d_status ) : ( $d_phase_map[ $d_status ] ?? 0 );
            // Histórico (tabela rmbz_distro_status_history), mais recente 1.º
            $d_history = [];
            $t_hist = $wpdb->prefix . 'rmbz_distro_status_history';
            if ( $wpdb->get_var( "SHOW TABLES LIKE '{$t_hist}'" ) === $t_hist ) {
                $d_history = array_reverse( $wpdb->get_results( $wpdb->prepare(
                    "SELECT to_status, reason_code, reason_text, created_at FROM {$t_hist} WHERE release_id = %d ORDER BY created_at ASC", $rvd_detail_id
                ) ) ?: [] );
            }
            // Ouvir nas lojas (links exatos + pesquisa) — só relevante em live
            $d_listen = function_exists( 'rmbz_release_get_links_for_tracker' ) ? rmbz_release_get_links_for_tracker( $dr ) : [];
            // Territórios (texto igual ao antigo)
            $d_terr_mode = (string) ( $dp->territory_mode ?? 'worldwide' );
            $d_terr_list = $dp && ! empty( $dp->territory_list ) ? (array) json_decode( $dp->territory_list, true ) : [];
            $d_terr_txt = 'Mundo inteiro';
            if ( $d_terr_mode === 'worldwide_except' )  $d_terr_txt = 'Mundo, excluindo ' . count( $d_terr_list ) . ' país(es)';
            elseif ( $d_terr_mode === 'selected' )      $d_terr_txt = count( $d_terr_list ) . ' país(es) selecionado(s)';
            // Data original (release_date_original → release_date → created_at)
            $d_date_orig = ! empty( $dr->release_date_original ) ? $dr->release_date_original : ( ! empty( $dr->release_date ) ? $dr->release_date : ( $dr->created_at ?? '' ) );
            // Serviços exclusivos (colunas do release_platforms).
            // [1.5.437] Ícones = logótipos REAIS (SVG) em vez de emojis.
            $d_svg_yt = '<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect x="1" y="4.5" width="22" height="15" rx="4" fill="#FF0000"/><path d="M10 9l5.2 3L10 15z" fill="#fff"/></svg>';
            $d_svg_fb = '<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><circle cx="12" cy="12" r="12" fill="#1877F2"/><path d="M13.4 20v-6.2h2.1l.32-2.4H13.4v-1.55c0-.7.2-1.18 1.2-1.18h1.3V6.5c-.22-.03-1-.1-1.9-.1-1.9 0-3.2 1.16-3.2 3.3v1.7H8.7v2.4h2.1V20h2.6z" fill="#fff"/></svg>';
            $d_svg_tt = function_exists( 'rmbz_dsp_logo_svg' ) ? rmbz_dsp_logo_svg( 'tiktok', 24 ) : '';
            $d_excl = [];
            foreach ( [
                'yt_content_id' => [ 'YouTube Content ID', $d_svg_yt, 'Monetização ativa — o sistema automático do YouTube vai identificar usos da sua música em vídeos de outros utilizadores e atribuir-lhe os royalties dessa reprodução.' ],
                'fb_monet'      => [ 'Facebook / Instagram Rights Manager', $d_svg_fb, 'Monetização ativa — sempre que esta música aparecer em Reels, Stories ou vídeos no Facebook ou Instagram, os royalties são-lhe atribuídos.' ],
                'tt_monet'      => [ 'TikTok Monetization', $d_svg_tt, 'Monetização ativa — os usos da sua música em vídeos TikTok geram royalties atribuídos a si.' ],
            ] as $svc => $svc_meta ) {
                $st = $dp ? (string) ( $dp->{$svc . '_status'} ?? 'not_requested' ) : 'not_requested';
                if ( $st === 'not_requested' || $st === '' ) continue;
                $d_excl[] = [
                    'key' => $svc, 'name' => $svc_meta[0], 'ico' => $svc_meta[1], 'desc_on' => $svc_meta[2],
                    'status' => $st,
                    'note'   => $dp ? (string) ( $dp->{$svc . '_decision_note'} ?? '' ) : '',
                    'c_url'  => $dp ? (string) ( $dp->{$svc . '_conflict_url'} ?? '' ) : '',
                    'c_src'  => $dp ? (string) ( $dp->{$svc . '_conflict_source'} ?? '' ) : '',
                ];
            }
            // [1.5.437] Content ID nativo — mesmo gate/fluxo do módulo antigo
            // (contentid-frontend.php): botão + histórico + modal de pedido.
            $d_cid = null;
            if ( in_array( $d_status, [ 'live', 'distribuido' ], true )
                 && function_exists( 'rmbz_contentid_release_is_in_content_id' )
                 && rmbz_contentid_release_is_in_content_id( $rvd_detail_id ) ) {
                $t_cid = $wpdb->prefix . 'rmbz_contentid_requests';
                $d_cid_hist = [];
                if ( $wpdb->get_var( "SHOW TABLES LIKE '{$t_cid}'" ) === $t_cid ) {
                    $d_cid_hist = $wpdb->get_results( $wpdb->prepare(
                        "SELECT id, video_url, status, created_at, admin_response FROM {$t_cid}
                         WHERE release_id = %d AND artist_telemovel = %s ORDER BY id DESC LIMIT 10",
                        $rvd_detail_id, $telemovel
                    ) ) ?: [];
                }
                $d_cid_tracks = [];
                foreach ( $dtr as $ci => $tr ) $d_cid_tracks[] = [ 'id' => (int) $tr->id, 'num' => $ci + 1, 'title' => (string) $tr->track_title ];
                $d_cid = [ 'history' => $d_cid_hist, 'tracks' => $d_cid_tracks, 'nonce' => wp_create_nonce( 'rmbz_cid_submit' ) ];
            }
            $rvd_detail = [
                'row'      => $dr,
                'cid'      => $d_cid,
                'dsps'     => $dp_dsp_names,
                'terr_mode' => $d_terr_mode,
                'terr_txt' => $d_terr_txt,
                'tracks'   => $d_tracks,
                'streams'  => $d_streams,
                'earn'     => $d_earn,
                'phase'    => (int) $d_phase,
                'history'  => $d_history,
                'listen'   => $d_listen,
                'date_orig' => $d_date_orig,
                'excl'     => $d_excl,
                'links'    => [
                    'iTunes'      => [ (string) ( $dr->link_itunes ?? '' ), false ],
                    'Apple Music' => [ (string) ( $dr->link_applemusic ?? '' ), false ],
                    'Spotify URL' => [ (string) ( $dr->link_spotify_url ?? '' ), false ],
                    'Spotify URI' => [ (string) ( $dr->link_spotify_uri ?? '' ), true ], // URI: não é <a>
                ],
            ];
        }
    }

    // [1.5.434] Editor de faixa COMPLETO no wizard nativo — os catálogos vêm
    // do módulo (distribution-track-editor.php, carregado no bootstrap pelos
    // handlers AJAX). Fallbacks espelham os defaults do módulo.
    $rvt_langs = function_exists( 'rmbz_track_languages' ) ? rmbz_track_languages() : [ 'Portuguese' => 'Português', 'English' => 'Inglês', 'Spanish' => 'Espanhol', 'French' => 'Francês', 'Swahili' => 'Suaíli', 'Changana' => 'Changana', 'Xitsonga' => 'Xitsonga', 'Macua' => 'Macua', 'Other' => 'Outro' ];
    $rvt_roles = function_exists( 'rmbz_track_collaborator_roles' ) ? rmbz_track_collaborator_roles() : [ 'primary' => 'Artista principal', 'feature' => 'Featuring (feat.)', 'producer' => 'Produtor', 'mix' => 'Mistura', 'master' => 'Masterização', 'vocals' => 'Vocalista', 'remix' => 'Remix', 'songwriter' => 'Compositor (letra+música)' ];
    $rvt_moods = function_exists( 'rmbz_track_moods' ) ? rmbz_track_moods() : [ 'chill' => 'Chill', 'danceable' => 'Dançante', 'energetic' => 'Energético', 'happy' => 'Feliz', 'sad' => 'Triste', 'romantic' => 'Romântico', 'motivational' => 'Motivacional', 'spiritual' => 'Espiritual', 'party' => 'Festa', 'focus' => 'Concentração', 'sleep' => 'Dormir', 'workout' => 'Treino', 'aggressive' => 'Agressivo', 'melancholic' => 'Melancólico' ];

    $rvd_regions   = $distro_access && $vip_sect === 'distro' && function_exists( 'rmbz_distro_territory_regions' ) ? rmbz_distro_territory_regions() : [];
    $rvd_exclusives = $distro_access && $vip_sect === 'distro' && function_exists( 'rmbz_distro_exclusive_services' ) ? rmbz_distro_exclusive_services() : [];
    // key do serviço → campo POST do optin (contrato do handler)
    $rvd_excl_field = [ 'youtube_content_id' => 'yt_content_id_optin', 'facebook_monetization' => 'fb_monet_optin', 'tiktok_monetization' => 'tt_monet_optin' ];

    // [1.5.420] Perfis nas lojas (nativo) — catálogo + guardados.
    $dist_profiles_cat = $distro_access && $vip_sect === 'distro' && function_exists( 'rmbz_artist_profiles_catalog' ) ? rmbz_artist_profiles_catalog() : [];
    $dist_profiles_saved = $distro_access && $vip_sect === 'distro' && function_exists( 'rmbz_artist_profiles_get_all' ) ? rmbz_artist_profiles_get_all( $telemovel ) : [];
    // [1.5.421] Logótipos REAIS das lojas (SVG). O dsp-logos.php não é
    // carregado no bootstrap — inclui-se aqui para termos rmbz_dsp_logo_svg.
    if ( $distro_access && $vip_sect === 'distro' && ! function_exists( 'rmbz_dsp_logo_svg' ) && defined( 'RMBZ_PLUGIN_PATH' )
         && file_exists( RMBZ_PLUGIN_PATH . 'includes/distribution/dsp-logos.php' ) ) {
        require_once RMBZ_PLUGIN_PATH . 'includes/distribution/dsp-logos.php';
    }

    // Estatísticas nativas completas: período, faixas, lojas, países e imports.
    // ($t_daily definido lá em cima, junto do $t_rel — ver nota 1.5.430.)
    $dist_period = isset( $_GET['period'] ) ? sanitize_key( wp_unslash( $_GET['period'] ) ) : '30d';
    if ( ! in_array( $dist_period, [ '7d', '30d', '90d', '12m', 'all' ], true ) ) $dist_period = '30d';
    $dist_range = $distro_access && function_exists( 'rmbz_analytics_period_range' )
        ? rmbz_analytics_period_range( $dist_period, $telemovel )
        : [ 'from' => gmdate( 'Y-m-d', time() - 29 * DAY_IN_SECONDS ), 'to' => gmdate( 'Y-m-d' ), 'bucket' => 'day' ];
    $dist_daily = []; $dist_by_release = []; $dist_top_tracks = []; $dist_top_stores = []; $dist_top_countries = [];
    $dist_imports = ( $distro_access && $vip_sect === 'distro' && function_exists( 'rmbz_analytics_get_imports_list' ) ) ? rmbz_analytics_get_imports_list( $telemovel, 24 ) : [];
    $rvd_import_detail = ( $distro_access && $vip_sect === 'distro' && $vip_dview === 'report' && function_exists( 'rmbz_analytics_get_import_detail' ) )
        ? rmbz_analytics_get_import_detail( $telemovel, absint( $_GET['import_id'] ?? 0 ) ) : null;
    $rvd_release_stats = ( $distro_access && $vip_sect === 'distro' && $vip_dview === 'release-stats' && function_exists( 'rmbz_analytics_get_release_detail' ) )
        ? rmbz_analytics_get_release_detail( $telemovel, absint( $_GET['rid'] ?? 0 ) ) : null;
    if ( $distro_access && $vip_sect === 'distro' && $wpdb->get_var( "SHOW TABLES LIKE '{$t_daily}'" ) === $t_daily ) {
        $dist_pa = function_exists( 'rmbz_approval_clause' ) ? rmbz_approval_clause( $t_daily ) : '';
        $dist_bucket = [
            'day'   => "DATE_FORMAT(report_date, '%%Y-%%m-%%d')",
            'week'  => "DATE_FORMAT(DATE_SUB(report_date, INTERVAL WEEKDAY(report_date) DAY), '%%Y-%%m-%%d')",
            'month' => "DATE_FORMAT(report_date, '%%Y-%%m-01')",
        ][ $dist_range['bucket'] ?? 'day' ];
        $dist_daily = $wpdb->get_results( $wpdb->prepare(
            "SELECT {$dist_bucket} AS report_date, SUM(streams) AS s, SUM(sales) AS e
             FROM {$t_daily} WHERE artist_telemovel = %s AND report_date BETWEEN %s AND %s {$dist_pa}
             GROUP BY report_date ORDER BY report_date DESC",
            $telemovel, $dist_range['from'], $dist_range['to']
        ) ) ?: [];
        // [1.5.430] Consistente com o detalhe do release: liga a linha do
        // daily_stats ao release por release_id DIRETO ou pela faixa (track_id),
        // para apanhar imports legacy que só preencheram o track_id.
        $t_tracks_stats = $wpdb->prefix . 'rmbz_distro_tracks';
        $dist_by_release = $wpdb->get_results( $wpdb->prepare(
            "SELECT r.id, r.title, r.cover_image, COALESCE(SUM(d.streams),0) AS s, COALESCE(SUM(d.sales),0) AS e
             FROM {$t_rel} r
             LEFT JOIN {$t_daily} d
               ON ( d.release_id = r.id
                    OR d.track_id IN ( SELECT id FROM {$t_tracks_stats} WHERE release_id = r.id ) )
               AND d.report_date BETWEEN %s AND %s {$dist_pa}
             WHERE r.artist_telemovel = %s
             GROUP BY r.id ORDER BY s DESC LIMIT 20",
            $dist_range['from'], $dist_range['to'], $telemovel
        ) ) ?: [];
        $dist_top_tracks = $wpdb->get_results( $wpdb->prepare(
            "SELECT t.id, t.track_title, r.id AS release_id, r.title AS release_title, r.cover_image,
                    SUM(d.streams) AS s, SUM(d.sales) AS e
             FROM {$t_daily} d JOIN {$t_tracks_stats} t ON t.id = d.track_id
             JOIN {$t_rel} r ON r.id = t.release_id
             WHERE d.artist_telemovel = %s AND d.report_date BETWEEN %s AND %s {$dist_pa}
             GROUP BY t.id ORDER BY s DESC LIMIT 10",
            $telemovel, $dist_range['from'], $dist_range['to']
        ) ) ?: [];
        $dist_top_stores = $wpdb->get_results( $wpdb->prepare(
            "SELECT store AS name, SUM(streams) AS s, SUM(sales) AS e FROM {$t_daily}
             WHERE artist_telemovel = %s AND report_date BETWEEN %s AND %s {$dist_pa}
             GROUP BY store ORDER BY s DESC LIMIT 10",
            $telemovel, $dist_range['from'], $dist_range['to']
        ) ) ?: [];
        $dist_top_countries = $wpdb->get_results( $wpdb->prepare(
            "SELECT country_code AS name, SUM(streams) AS s, SUM(sales) AS e FROM {$t_daily}
             WHERE artist_telemovel = %s AND report_date BETWEEN %s AND %s {$dist_pa}
             GROUP BY country_code ORDER BY s DESC LIMIT 10",
            $telemovel, $dist_range['from'], $dist_range['to']
        ) ) ?: [];
    }

    // ── Pacotes VIP (renovação/compra) — mesma fonte do antigo ──
    $pacotes = $vip_sect === 'perfil' ? get_option( 'rmbz_vip_packages', [] ) : [];
    $pacotes = array_values( array_filter( (array) $pacotes, function ( $pk ) {
        return ( $pk['channel'] ?? 'both' ) !== 'app_only';
    } ) );
    if ( $vip_sect === 'perfil' && empty( $pacotes ) ) {
        $pacotes = [ [ 'id' => 'default', 'nome' => 'Acesso VIP', 'preco' => get_option( 'rmbz_sub_price', 1500 ), 'dias' => 30, 'perms' => [ 'distribute' => 1, 'site' => 1, 'social' => 1, 'video' => 1 ] ] ];
    }
    // Com uma subscrição ativa, renovar/mudar nunca pode retirar serviços.
    // A interface mostra o plano atual e apenas pacotes que acrescentam pelo
    // menos um serviço, preservando também o add-on de IA quando já existe.
    $vip_package_service_keys = [ 'site', 'social', 'distribute', 'video' ];
    $vip_change_packages = [];
    foreach ( $pacotes as $vip_change_package ) {
        $vip_change_perms = isset( $vip_change_package['perms'] ) && is_array( $vip_change_package['perms'] ) ? $vip_change_package['perms'] : [];
        $vip_change_name = trim( (string) ( $vip_change_package['nome'] ?? 'Pacote VIP' ) );
        $vip_change_is_current = $has_subscription && sanitize_title( $vip_change_name ) === sanitize_title( $vip_plan_name );
        $vip_change_preserves = true;
        $vip_change_added = 0;
        foreach ( $vip_package_service_keys as $vip_service_key ) {
            $vip_current_has = ! empty( $up_perms[ $vip_service_key ] );
            $vip_target_has = ! empty( $vip_change_perms[ $vip_service_key ] );
            if ( $vip_current_has && ! $vip_target_has ) $vip_change_preserves = false;
            if ( ! $vip_current_has && $vip_target_has ) $vip_change_added++;
        }
        $vip_change_ai_required = $has_subscription && ! empty( $up_perms['ai'] );
        if ( $vip_change_ai_required && empty( $vip_change_package['ai_offered'] ) ) $vip_change_preserves = false;
        if ( ! $has_subscription || ( $vip_change_preserves && ( $vip_change_is_current || $vip_change_added > 0 ) ) ) {
            $vip_change_package['_vip_is_current'] = $vip_change_is_current;
            $vip_change_package['_vip_added_services'] = $vip_change_added;
            $vip_change_package['_vip_ai_required'] = $vip_change_ai_required;
            $vip_change_packages[] = $vip_change_package;
        }
    }

    // ── Referral (ganhar saldo) ──
    $ref_stats = $vip_sect === 'inicio' && function_exists( 'rmbz_referral_get_user_stats' ) ? rmbz_referral_get_user_stats( $telemovel ) : null;
    $ref_type  = get_option( 'rmbz_referral_type', 'mt' );
    $ref_rate  = get_option( 'rmbz_referral_rate', 0 );
    $ref_days  = get_option( 'rmbz_referral_days', 0 );

    // ── Fontes elegíveis para levantamento (mesma regra do antigo) ──
    $withdraw_min = defined( 'RMBZ_MIN_WITHDRAWAL' ) ? (float) RMBZ_MIN_WITHDRAWAL : 50.0;
    $min_wd_usd = max( 0.01, round( $withdraw_min / max( 0.01, $cambio ), 2 ) );
    $wallet_eligible = $retiravel >= $withdraw_min;
    $royalties_eligible = $roy_usd >= $min_wd_usd;
    $roy_eligivel = $royalties_eligible;
    $saved_payouts = ( isset( $extra_user['saved_payouts'] ) && is_array( $extra_user['saved_payouts'] ) )
        ? array_slice( array_values( $extra_user['saved_payouts'] ), 0, 5 ) : [];

    // Nonce partilhado dos AJAX do artista (sino/popup/heartbeat)
    $notif_nonce = wp_create_nonce( 'rmbz_notif_nonce' );
    $ajax_url    = admin_url( 'admin-ajax.php' );

    // ── notificações (mesma fonte canónica da App) ──
    $notif_page     = max( 1, isset( $_GET['notif_page'] ) ? absint( $_GET['notif_page'] ) : 1 );
    $notif_per_page = 20;
    $notif_data     = rmbz_vip_get_notifications( $telemovel, $email, $notif_page, $notif_per_page, $vip_sect === 'notifs' );
    $notifs         = $vip_sect === 'notifs' ? $notif_data['items'] : [];
    $notif_total    = (int) $notif_data['total'];
    $n_por_ler      = (int) $notif_data['unread'];
    $vip_notif_nonce = wp_create_nonce( 'rmbz_vip_notif' );
    $notif_categories = function_exists( 'rmbz_notif_site_categories' ) ? rmbz_notif_site_categories() : [];
    $notif_prefs = ( $vip_sect === 'notifs' && function_exists( 'rmbz_notif_get_user_prefs' ) )
        ? rmbz_notif_get_user_prefs( $telemovel ) : [];

    // ── estatísticas avançadas + catálogo real de conquistas ──
    // A vista abre sempre no histórico completo. O único recorte disponível é
    // um intervalo explícito escolhido pelo artista (data inicial e final).
    $insight_period       = 'all';
    $insight_date_from    = isset( $_GET['stats_from'] ) ? sanitize_text_field( wp_unslash( $_GET['stats_from'] ) ) : '';
    $insight_date_to      = isset( $_GET['stats_to'] ) ? sanitize_text_field( wp_unslash( $_GET['stats_to'] ) ) : '';
    $insight_date_max     = current_time( 'Y-m-d' );
    $insight_date_error   = '';
    $insight_custom_range = [];
    $insight_range_active = false;
    if ( $insight_date_from !== '' || $insight_date_to !== '' ) {
        if ( $insight_date_from === '' || $insight_date_to === '' ) {
            $insight_date_error = 'Escolhe a data inicial e a data final.';
        } elseif ( function_exists( 'rmbz_insights_custom_range' ) ) {
            $insight_normalized = rmbz_insights_custom_range( $insight_date_from, $insight_date_to );
            if ( is_array( $insight_normalized ) ) {
                $insight_custom_range = [ 'from' => $insight_normalized['from'], 'to' => $insight_normalized['to'] ];
                $insight_date_from    = $insight_normalized['from'];
                $insight_date_to      = $insight_normalized['to'];
                $insight_period       = 'custom';
                $insight_range_active = true;
            } else {
                $insight_date_error = 'O intervalo é inválido. A data inicial deve ser anterior à final e nenhuma pode estar no futuro.';
            }
        } else {
            $insight_date_error = 'O filtro por datas está temporariamente indisponível.';
        }
    }
    $insight_facts = null; $insight_view = null;
    $milestone_groups = []; $milestone_achieved_count = 0; $milestone_total_count = 0;
    $stats_has_distribution = false;
    $stats_activity_cards = [];
    $stats_milestone_groups = [];
    $ai_entitled = $vip_sect === 'stats' && function_exists( 'rmbz_ai_user_is_vip' ) && rmbz_ai_user_is_vip( $telemovel );
    $ai_nonce = wp_create_nonce( 'rmbz_vip_ai' );
    if ( $vip_sect === 'stats' ) {
        if ( $distro_access && function_exists( 'rmbz_insights_compute' ) ) {
            $insight_facts = rmbz_insights_compute( $telemovel, 'all', $insight_custom_range );
            if ( function_exists( 'rmbz_insights_build' ) ) $insight_view = rmbz_insights_build( $insight_facts );
        }
        if ( function_exists( 'rmbz_milestones_check_artist' ) ) rmbz_milestones_check_artist( $telemovel );
        if ( function_exists( 'rmbz_milestones_catalog' ) && function_exists( 'rmbz_milestones_compute_metrics' ) ) {
            $catalog = rmbz_milestones_catalog();
            $metrics = rmbz_milestones_compute_metrics( $telemovel );
            $stats_has_distribution = $distro_access && (
                (int) ( $metrics['releases_submitted'] ?? 0 ) > 0
                || (int) ( $metrics['total_streams'] ?? 0 ) > 0
            );

            $stats_project_done = 0;
            if ( $plan_video && rmbz_vip_table_exists( $t_proj ) ) {
                $stats_project_done = (int) $wpdb->get_var( $wpdb->prepare(
                    "SELECT COUNT(id) FROM {$t_proj} WHERE artist_telemovel = %s AND production_status = 'done'",
                    $telemovel
                ) );
            }
            $stats_submission_total = 0;
            if ( ! empty( $submission_allowed_types ) && rmbz_vip_table_exists( $t_subs ) ) {
                $stats_submission_placeholders = implode( ', ', array_fill( 0, count( $submission_allowed_types ), '%s' ) );
                $stats_submission_params = array_merge( [ $telemovel ], $submission_allowed_types );
                $stats_submission_total = (int) $wpdb->get_var( $wpdb->prepare(
                    "SELECT COUNT(id) FROM {$t_subs} WHERE artist_telemovel = %s AND scenario_type IN ({$stats_submission_placeholders})",
                    ...$stats_submission_params
                ) );
            }
            $stats_deposit_approved = 0;
            if ( rmbz_vip_table_exists( $t_dep ) ) {
                $stats_deposit_approved = (int) $wpdb->get_var( $wpdb->prepare(
                    "SELECT COUNT(id) FROM {$t_dep} WHERE user_telemovel = %s AND status = 'aprovado'",
                    $telemovel
                ) );
            }
            $stats_activity_cards = [];
            if ( $plan_video ) {
                $stats_activity_cards[] = [ 'movie', 'Videoclipes', (string) $project_total, $stats_project_done . ' concluído(s)', 'projetos', 'brand' ];
            }
            if ( ! empty( $submission_allowed_types ) ) {
                $stats_activity_cards[] = [ 'upload_file', 'Envios para promoção', (string) $stats_submission_total, 'serviços incluídos no plano', 'envios', 'info' ];
            }
            $stats_activity_cards[] = [ 'account_balance_wallet', 'Saldo da carteira', $fmt( $saldo_total ) . ' MT', $stats_deposit_approved . ' depósito(s) aprovado(s)', 'financas', 'success' ];
            $stats_activity_cards[] = [ 'calendar_month', 'Percurso na 1MZ', (int) ( $metrics['days_as_artist'] ?? 0 ) . ' dias', 'desde a primeira atividade', 'perfil', 'brand' ];
            $stats_activity_cards[] = [ 'group_add', 'Artistas convidados', (string) (int) ( $metrics['referrals_count'] ?? 0 ), 'convites confirmados', 'inicio', 'info' ];
            $stats_activity_cards[] = [ 'workspace_premium', 'Subscrição VIP', $vip_dias . ' dias', $vip_dias > 0 ? 'acesso ativo' : 'ver planos disponíveis', 'perfil', $vip_dias > 0 ? 'success' : 'rev' ];
            $achieved_rows = [];
            $milestone_table = $wpdb->prefix . 'rmbz_artist_milestones';
            if ( rmbz_vip_table_exists( $milestone_table ) ) {
                $achieved_rows = $wpdb->get_results( $wpdb->prepare(
                    "SELECT milestone_key, achieved_at, achieved_value FROM {$milestone_table} WHERE artist_telemovel = %s",
                    $telemovel
                ), OBJECT_K ) ?: [];
            }
            $category_labels = [ 'catalog' => 'Catálogo', 'audience' => 'Audiência', 'financial' => 'Financeiro', 'time' => 'Percurso', 'community' => 'Comunidade' ];
            foreach ( $catalog as $key => $def ) {
                $category = (string) ( $def['category'] ?? 'catalog' );
                $current  = rmbz_vip_milestone_value( $key, $metrics );
                $target   = max( 1, (float) ( $def['threshold'] ?? 1 ) );
                $achieved = isset( $achieved_rows[ $key ] );
                $milestone_groups[ $category ][] = [
                    'key' => $key, 'title' => (string) ( $def['title'] ?? $key ),
                    'description' => (string) ( $def['description'] ?? '' ), 'icon' => (string) ( $def['icon'] ?? 'emoji_events' ),
                    'current' => $current, 'target' => $target, 'pct' => $achieved ? 100 : min( 100, (int) round( ( $current / $target ) * 100 ) ),
                    'achieved' => $achieved, 'achieved_at' => $achieved ? (string) $achieved_rows[ $key ]->achieved_at : '',
                ];
                if ( $achieved ) $milestone_achieved_count++;
                $milestone_total_count++;
            }
            foreach ( $milestone_groups as $category => &$group ) {
                usort( $group, static fn( $a, $b ) => (int) $b['achieved'] <=> (int) $a['achieved'] ?: $b['pct'] <=> $a['pct'] );
            }
            unset( $group );
            $milestone_category_labels = $category_labels;
        }
        $stats_milestone_groups = $milestone_groups;
        if ( ! $stats_has_distribution ) {
            $non_distro_keys = [ 'first_payment', 'earnings_1k', 'earnings_10k', 'earnings_100k', 'tenure_1m', 'tenure_6m', 'tenure_1y', 'tenure_2y', 'first_referral', 'referrals_5' ];
            foreach ( $stats_milestone_groups as $category => &$stats_group ) {
                $stats_group = array_values( array_filter( $stats_group, static fn( $item ) => in_array( $item['key'], $non_distro_keys, true ) ) );
                if ( empty( $stats_group ) ) unset( $stats_milestone_groups[ $category ] );
            }
            unset( $stats_group );
            $milestone_achieved_count = 0;
            $milestone_total_count = 0;
            foreach ( $stats_milestone_groups as $stats_group ) {
                foreach ( $stats_group as $stats_milestone ) {
                    if ( ! empty( $stats_milestone['achieved'] ) ) $milestone_achieved_count++;
                    $milestone_total_count++;
                }
            }
        }
    }

    // ── centro de segurança: sessões móveis ativas ──
    $app_sessions = [];
    if ( $vip_sect === 'perfil' ) {
        $token_table = $wpdb->prefix . 'rmbz_api_refresh_tokens';
        if ( rmbz_vip_table_exists( $token_table ) ) {
            $app_sessions = $wpdb->get_results( $wpdb->prepare(
                "SELECT id, device_label, ip_address, user_agent, created_at, last_used_at, expires_at
                 FROM {$token_table} WHERE user_telemovel = %s AND revoked_at IS NULL AND expires_at > UTC_TIMESTAMP()
                 ORDER BY last_used_at DESC, created_at DESC LIMIT 20",
                $telemovel
            ) ) ?: [];
        }
    }

    // ── depósito (números 1MZ) ──
    $pset = get_option( 'rmbz_payment_settings' );
    $dep_mpesa = isset( $pset['rmbz_mpesa_number'] ) ? (string) $pset['rmbz_mpesa_number'] : '84 000 00 00';
    $dep_emola = isset( $pset['rmbz_emola_number'] ) ? (string) $pset['rmbz_emola_number'] : '86 000 00 00';
    // [1.5.454] Nomes dos titulares (como o antigo mostra por baixo do número)
    $dep_benef      = (string) get_option( 'rmbz_payment_beneficiary', '1MZ Records' );
    $dep_mpesa_name = ! empty( $pset['rmbz_mpesa_name'] ) ? (string) $pset['rmbz_mpesa_name'] : $dep_benef;
    $dep_emola_name = ! empty( $pset['rmbz_emola_name'] ) ? (string) $pset['rmbz_emola_name'] : $dep_benef;

    // notice de operações (levantamento)
    $notice = null;
    if ( isset( $_SESSION['rmbz_withdrawal_notice'] ) && is_array( $_SESSION['rmbz_withdrawal_notice'] ) ) {
        $notice = $_SESSION['rmbz_withdrawal_notice'];
        unset( $_SESSION['rmbz_withdrawal_notice'] );
    }

    $post_url   = admin_url( 'admin-post.php' );
    // [1.5.451] O handler do logout exige nonce (SEC-MA5) — sem ele
    // redirecionava em silêncio e a sessão ficava aberta.
    $logout_url = wp_nonce_url( admin_url( 'admin-post.php?action=rmbz_logout' ), 'rmbz_logout_nonce' );
    $min_wd     = $withdraw_min;

    // [1.5.431] Estado inicial vindo do URL, resolvido NO SERVIDOR.
    // Antes: o painel renderizava sempre no "Início" e só depois o JS (no fim
    // do markup) saltava para ?sect=/?dview= — ao abrir um release via link
    // via-se o Início por um instante antes de aparecer a música. Agora a
    // secção e a sub-vista certas já vêm abertas do PHP.
    // Títulos do cabeçalho por secção (espelham o mapa "titles" do JS).
    $vip_titles = [
        'inicio'   => [ 'Olá, ' . $nome, 'O teu estúdio 1MZ num só ecrã.' ],
        'musicas'  => [ 'Músicas & Ganhos', 'Programa de parceria, catálogo, controlo e monetização.' ],
        'arttracks'=> [ 'Art Tracks', 'As tuas músicas publicadas no site da 1MZ.' ],
        'projetos' => [ 'Videoclipes', 'Os teus projetos com a equipa 1MZ.' ],
        'distro'   => [ 'Distribuição digital', 'Releases, streams e royalties.' ],
        'envios'   => [ 'Envios', 'Músicas para o site e vídeos para as redes.' ],
        'financas' => [ 'Finanças', 'Depósitos, levantamentos e extrato.' ],
        '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.' ],
    ];
    $vip_title_init = $vip_titles[ $vip_sect ];
    ?>
    <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">
    <div id="rmbz-vip" data-theme="oled">
    <?php // [1.5.431] Anti-piscar do tema: aplica o tema guardado JÁ, antes de
          // o conteúdo do painel renderizar. Sem isto, quem usa tema claro via
          // um flash escuro a cada navegação (o applyTheme só corria no fim). ?>
    <script>try{if(localStorage.getItem('rmbz_vip_theme')==='claro'){document.getElementById('rmbz-vip').setAttribute('data-theme','claro');}}catch(e){}</script>
    <?php // [1.5.433] SPLASH de navegação: ao clicar em algo que recarrega a
          // página, este ecrã (fundo do tema + logo 1MZ a flutuar) aparece
          // instantaneamente e fica até a página nova assumir — a nova, por
          // sua vez, mostra o mesmo logo via <head> (enqueue.php) até o
          // painel estar pronto. Resultado: nunca se vê o tema do site. ?>
    <div id="rmbz-vip-splash"><img src="<?php echo esc_url( RMBZ_PLUGIN_URL . 'assets/pwa/icon-192.png' ); ?>" alt="1MZ"></div>
    <?php // [1.5.435] Diálogo M3 do painel — substitui os alert()/confirm() do
          // browser em TODO o painel (vipAlert / vipConfirm no JS). ?>
    <div class="scrim" id="rmbz-vip-dlg" style="z-index:2147483644;">
        <div class="dialog" style="width:min(460px,94vw);">
            <div style="display:flex; gap:14px; align-items:flex-start;">
                <span id="rmbz-vip-dlg-ico" style="font-size:28px; line-height:1;">💬</span>
                <div id="rmbz-vip-dlg-msg" style="flex:1; font-size:13.5px; line-height:1.65; color:var(--text); white-space:pre-line; padding-top:4px;"></div>
            </div>
            <div style="display:flex; gap:10px; margin-top:20px; justify-content:flex-end;">
                <button type="button" class="pill" id="rmbz-vip-dlg-no" style="border:1px solid var(--border); background:none; color:var(--text2);">Cancelar</button>
                <button type="button" class="pill" id="rmbz-vip-dlg-ok" style="background:var(--brand); color:var(--on-brand); min-width:120px; justify-content:center;">OK</button>
            </div>
        </div>
    </div>

    <div class="scrim project-chat-image-scrim" id="rmbz-vip-chat-image" style="z-index:2147483642;">
        <div class="dialog project-chat-image-dialog">
            <div class="project-chat-image-head">
                <span class="ms project-chat-image-head-icon">image</span>
                <div style="min-width:0; flex:1;"><div class="project-chat-image-title" data-chat-image-title>Imagem do chat</div><div class="project-chat-image-subtitle">Anexo da conversa com a equipa</div></div>
                <a href="#" class="pill project-btn outlined project-chat-image-original" data-chat-image-original target="_blank" rel="noopener"><span class="ms">open_in_new</span>Abrir original</a>
                <button type="button" class="project-icon-btn rmbz-vip-dclose" aria-label="Fechar imagem"><span class="ms">close</span></button>
            </div>
            <div class="project-chat-image-stage">
                <div class="project-chat-image-loading" data-chat-image-loading><span class="ms">progress_activity</span><span>A carregar imagem…</span></div>
                <div class="project-chat-image-error" data-chat-image-error hidden><span class="ms">broken_image</span><strong>Não foi possível visualizar a imagem.</strong><span>Usa “Abrir original” para verificar o ficheiro.</span></div>
                <img data-chat-image-full alt="" hidden>
            </div>
        </div>
    </div>

    <?php // [1.5.438] 🎉 BOAS-VINDAS VIP (pós-compra) — nativo, abre sozinho. ?>
    <?php if ( $vip_congrats ):
        $cg_ret  = ( $vip_congrats['event'] ?? '' ) === 'returned';
        $cg_plan = (string) ( $vip_congrats['plan_name'] ?? '' );
    ?>
    <div class="scrim open" id="rmbz-vip-congrats" style="z-index:2147483643;">
        <div class="dialog" style="width:min(480px,94vw); text-align:center; border:2px solid var(--brand);">
            <div style="font-size:54px;"><?php echo $cg_ret ? '👑' : '🎉'; ?></div>
            <div style="font-family:'Bricolage Grotesque',sans-serif; font-size:22px; font-weight:800; color:var(--brand-ink); margin-top:8px;"><?php echo $cg_ret ? 'Bem-vindo de volta ao VIP!' : 'Bem-vindo ao VIP!'; ?></div>
            <p style="font-size:13.5px; color:var(--text2); line-height:1.65; margin:10px 0 0;">
                <?php if ( $cg_ret ): ?>Obrigado por voltares — a tua subscrição <?php echo $cg_plan !== '' ? '<b>' . esc_html( $cg_plan ) . '</b>' : 'VIP'; ?> está ativa de novo.
                <?php else: ?>A tua subscrição <?php echo $cg_plan !== '' ? '<b>' . esc_html( $cg_plan ) . '</b>' : ''; ?> está ativa! Fazes oficialmente parte da plataforma mais avançada para artistas em Moçambique.<?php endif; ?>
            </p>
            <div style="text-align:left; margin-top:16px; display:flex; flex-direction:column; gap:8px;">
                <div style="display:flex; gap:10px; align-items:center; background:var(--elev); border-radius:12px; padding:10px 14px; font-size:12.5px;"><span style="font-size:20px;">🎬</span> Videoclipes profissionais com a equipa 1MZ</div>
                <div style="display:flex; gap:10px; align-items:center; background:var(--elev); border-radius:12px; padding:10px 14px; font-size:12.5px;"><span style="font-size:20px;">🌍</span> Distribuição para Spotify, Apple Music e +20 lojas</div>
                <div style="display:flex; gap:10px; align-items:center; background:var(--elev); border-radius:12px; padding:10px 14px; font-size:12.5px;"><span style="font-size:20px;">💰</span> Carteira com royalties, depósitos e levantamentos</div>
            </div>
            <button type="button" class="pill rmbz-vip-autoclose" style="width:100%; justify-content:center; background:var(--brand); color:var(--on-brand); margin-top:18px;">Entrar no painel 🚀</button>
        </div>
    </div>
    <?php endif; ?>

    <?php // [1.5.438] 🎉 CUPÃO RESGATADO — nativo, abre sozinho. ?>
    <?php if ( $coupon_cel ): ?>
    <div class="scrim open" id="rmbz-vip-coupon" style="z-index:2147483643;">
        <div class="dialog" style="width:min(440px,94vw); text-align:center; border:1px solid var(--brand);">
            <div style="width:64px; height:64px; margin:0 auto; border-radius:50%; background:linear-gradient(135deg,#daa520,var(--brand)); display:flex; align-items:center; justify-content:center; font-size:32px;">🎉</div>
            <div style="font-family:'Bricolage Grotesque',sans-serif; font-size:21px; font-weight:800; margin-top:12px;"><?php echo esc_html( (string) ( $coupon_cel['title'] ?? 'Parabéns!' ) ); ?></div>
            <?php if ( ! empty( $coupon_cel['message'] ) ): ?><p style="font-size:13px; color:var(--text2); margin:8px 0 0;"><?php echo esc_html( (string) $coupon_cel['message'] ); ?></p><?php endif; ?>
            <?php $cc_ben = ( isset( $coupon_cel['benefits'] ) && is_array( $coupon_cel['benefits'] ) ) ? $coupon_cel['benefits'] : []; ?>
            <?php if ( $cc_ben || ! empty( $coupon_cel['has_ai'] ) ): ?>
            <div style="text-align:left; margin-top:14px; display:flex; flex-direction:column; gap:6px;">
                <div style="font-size:11px; font-weight:750; letter-spacing:.08em; color:var(--muted);">O QUE GANHASTE</div>
                <?php // [1.5.450] Cada benefício é um array {icon, text} (como no clássico).
                foreach ( $cc_ben as $cb ):
                    $cb_icon = is_array( $cb ) ? (string) ( $cb['icon'] ?? '✅' ) : '✅';
                    $cb_text = is_array( $cb ) ? (string) ( $cb['text'] ?? '' ) : (string) $cb;
                    if ( $cb_text === '' ) continue;
                    $cb_ai = ( $cb_icon === '🤖' );
                ?><div style="display:flex; align-items:center; gap:10px; border-radius:10px; padding:9px 13px; font-size:12.5px; background:<?php echo $cb_ai ? 'var(--brand-soft)' : 'var(--elev)'; ?>;<?php echo $cb_ai ? ' border:1px solid var(--brand); color:var(--brand-ink); font-weight:650;' : ''; ?>"><span style="font-size:16px;"><?php echo esc_html( $cb_icon ); ?></span> <?php echo esc_html( $cb_text ); ?></div><?php endforeach; ?>
                <?php if ( ! empty( $coupon_cel['has_ai'] ) ): ?><div style="background:var(--brand-soft); border:1px solid var(--brand); border-radius:10px; padding:9px 13px; font-size:12.5px; color:var(--brand-ink); font-weight:650;">🤖 Assistente com Inteligência Artificial incluído</div><?php endif; ?>
            </div>
            <?php endif; ?>
            <button type="button" class="pill rmbz-vip-autoclose" style="width:100%; justify-content:center; background:var(--brand); color:var(--on-brand); margin-top:16px;">Boa! 🎉</button>
        </div>
    </div>
    <?php endif; ?>

    <?php // [1.5.438] ❌ PROJETO CANCELADO — nativo; "Compreendi" dispensa no
          // servidor (rmbz_dismiss_cancel_notice), como o popup antigo. ?>
    <?php if ( $cancel_notice ): ?>
    <div class="scrim open" id="rmbz-vip-cancel" data-nid="<?php echo esc_attr( (string) ( $cancel_notice['id'] ?? '' ) ); ?>" data-nonce="<?php echo esc_attr( $cancel_nonce ); ?>" style="z-index:2147483643;">
        <div class="dialog" style="width:min(460px,94vw); padding:0; overflow:hidden;">
            <div style="background:linear-gradient(135deg,#d93025,#b3261e); padding:22px 24px; text-align:center;">
                <div style="font-size:40px; line-height:1;">❌</div>
                <div style="color:#fff; font-size:18px; font-weight:800; margin-top:8px;">Projecto cancelado</div>
            </div>
            <div style="padding:20px 24px 22px;">
                <p style="margin:0 0 16px; font-size:13.5px; line-height:1.65; color:var(--text2);">
                    <?php echo function_exists( 'rmbz_popup_cancel_message' ) ? rmbz_popup_cancel_message( $cancel_notice ) /* já escapado */ : esc_html( (string) ( $cancel_notice['reason'] ?? 'O teu projeto foi cancelado.' ) ); ?>
                </p>
                <button type="button" class="pill" id="rmbz-vip-cancel-ok" style="width:100%; justify-content:center; background:var(--text); color:var(--bg);">Compreendi</button>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php // [1.5.439] 🛑 PEDIDO DE DESISTÊNCIA — decisão do artista, com a
          // compilação do projeto e o conselho da IA (lido da BD). ?>
    <?php if ( $giveup_ask ):
        $gu_p = $giveup_ask['p']; $gu_g = $giveup_ask['g'];
        $gu_f = is_array( $gu_g['facts'] ?? null ) ? $gu_g['facts'] : [];
        $gu_fmt = fn( $n ) => number_format( (float) $n, 2, ',', '.' );
    ?>
    <div class="scrim open" id="rmbz-vip-giveup" style="z-index:2147483643;">
        <div class="dialog" style="width:min(620px,96vw); max-height:92vh; display:flex; flex-direction:column;">
            <div style="font-size:17px; font-weight:750;">🎬 A equipa 1MZ precisa da tua decisão</div>
            <p style="font-size:13px; color:var(--text2); margin:6px 0 12px;">Foi proposta a <b>desistência</b> do teu projeto de vídeo <b>"<?php echo esc_html( (string) $gu_p->project_title ); ?>"</b> (nível <?php echo esc_html( (string) ( $gu_f['level_label'] ?? '' ) ); ?>). A decisão final é <b>tua</b>. Lê tudo com calma:</p>
            <div style="flex:1; overflow-y:auto; min-height:0;">
                <div style="display:grid; grid-template-columns:repeat(auto-fill,minmax(160px,1fr)); gap:8px;">
                    <?php foreach ( [
                        [ 'JÁ PAGASTE', $gu_fmt( $gu_f['paid'] ?? 0 ) . ' MT' ],
                        [ 'A TUA PARTE', $gu_fmt( $gu_f['cost'] ?? 0 ) . ' MT' ],
                        [ 'VALOR DE MERCADO', $gu_fmt( $gu_f['market'] ?? 0 ) . ' MT' ],
                        [ 'POUPAS EM PRODUÇÃO', $gu_fmt( $gu_f['savings'] ?? 0 ) . ' MT' ],
                    ] as $gu_c ): ?>
                        <div style="background:var(--elev); border-radius:12px; padding:10px 14px;"><div style="font-size:10px; font-weight:750; letter-spacing:.08em; color:var(--muted);"><?php echo esc_html( $gu_c[0] ); ?></div><div class="mono" style="font-size:14px; font-weight:700; margin-top:3px;"><?php echo esc_html( $gu_c[1] ); ?></div></div>
                    <?php endforeach; ?>
                </div>
                <?php if ( (float) ( $gu_f['fine_pending'] ?? 0 ) > 0 ): ?>
                    <div style="border-radius:12px; padding:9px 13px; margin-top:8px; background:var(--danger-soft); color:var(--danger); font-size:12px; font-weight:650;">💸 Multa pendente no projeto: <?php echo esc_html( $gu_fmt( $gu_f['fine_pending'] ) ); ?> MT</div>
                <?php endif; ?>
                <div style="border:1px solid var(--brand); background:var(--brand-soft); border-radius:14px; padding:14px 16px; margin-top:12px;">
                    <div style="font-size:11px; font-weight:750; letter-spacing:.08em; color:var(--brand-ink); margin-bottom:6px;">🤖 CONSELHO DO ASSISTENTE 1MZ</div>
                    <div style="font-size:13px; line-height:1.7; color:var(--text);"><?php echo esc_html( (string) ( $gu_g['ai_text'] ?? '' ) ); ?></div>
                </div>
                <?php if ( (float) ( $gu_f['paid'] ?? 0 ) > 0 ): ?>
                    <div style="border-radius:12px; padding:10px 14px; margin-top:10px; background:var(--danger-soft); color:var(--danger); font-size:12px; font-weight:650;">⚠️ Regra do projeto: se confirmares a desistência, o valor que já pagaste (<b><?php echo esc_html( $gu_fmt( $gu_f['paid'] ) ); ?> MT</b>) <b>perde-se</b> — não é devolvido.</div>
                <?php endif; ?>
            </div>
            <?php if ( isset( $_GET['giveup_err'] ) && $_GET['giveup_err'] === 'sign' ): ?>
                <div style="border-radius:12px; padding:9px 13px; margin-top:10px; background:var(--danger-soft); color:var(--danger); font-size:12px; font-weight:700;">❌ A assinatura ou o número da conta não confere — tenta de novo.</div>
            <?php endif; ?>
            <div id="rvgu-s1" style="display:flex; gap:10px; margin-top:14px; flex-wrap:wrap;">
                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="flex:1.4; min-width:200px; display:flex;"
                      data-vip-confirm="⚠️ DECISÃO DEFINITIVA — não pode ser invertida.&#10;&#10;Ao escolheres CONTINUAR, ficas comprometido com o projeto até ao fim: se no futuro desistires, levas BANIMENTO do sistema e nunca mais poderás submeter projetos ou músicas na 1MZ For Artists.&#10;&#10;Confirmar que queres CONTINUAR o projeto?">
                    <input type="hidden" name="action" value="rmbz_project_giveup_respond">
                    <input type="hidden" name="project_id" value="<?php echo (int) $gu_p->id; ?>">
                    <input type="hidden" name="decision" value="refuse">
                    <?php wp_nonce_field( 'rmbz_giveup_respond_nonce' ); ?>
                    <button type="submit" class="pill" style="flex:1; justify-content:center; background:var(--success); color:#fff;">💪 Quero continuar o projeto</button>
                </form>
                <button type="button" id="rvgu-open2" class="pill" style="flex:1; min-width:180px; justify-content:center; border:1px solid var(--danger); background:none; color:var(--danger);">Confirmo que desisto</button>
            </div>
            <?php // Passo 2 — despedida + ASSINATURA (nome + nº da conta). ?>
            <div id="rvgu-s2" hidden style="margin-top:14px;">
                <div style="border:1px solid var(--border); background:var(--elev); border-radius:14px; padding:14px 16px;">
                    <div style="font-size:14px; font-weight:750;">😔 Lamentamos não trabalhar contigo neste projeto</div>
                    <p style="font-size:12.5px; color:var(--text2); line-height:1.65; margin:8px 0 0;">Respeitamos a tua decisão. Podes continuar a submeter <b>outras músicas</b> quando quiseres — mas a música <b>"<?php echo esc_html( (string) $gu_p->project_title ); ?>"</b> não será aceite novamente na plataforma. Para confirmares, <b>assina</b> com o teu nome e confirma o número da tua conta:</p>
                </div>
                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" id="rvgu-form" data-acc="<?php echo esc_attr( preg_replace( '/\D+/', '', (string) $gu_p->artist_telemovel ) ); ?>" style="margin-top:10px;">
                    <input type="hidden" name="action" value="rmbz_project_giveup_respond">
                    <input type="hidden" name="project_id" value="<?php echo (int) $gu_p->id; ?>">
                    <input type="hidden" name="decision" value="accept">
                    <?php wp_nonce_field( 'rmbz_giveup_respond_nonce' ); ?>
                    <input type="text" name="sign_name" class="inp" placeholder="✍️ O teu nome completo (assinatura)" required style="font-size:13px; margin-bottom:8px;">
                    <div style="display:flex; gap:8px; align-items:stretch;">
                        <span style="display:flex; align-items:center; border:1px solid var(--border); border-radius:12px; padding:0 14px; background:var(--elev); font-size:13px; font-weight:700; color:var(--text2);">🇲🇿 +258</span>
                        <input type="tel" name="sign_tel" class="inp" placeholder="O teu número (ex: 86 123 4567)" required inputmode="numeric" style="font-size:13px; flex:1;">
                    </div>
                    <div style="display:flex; gap:10px; margin-top:10px;">
                        <button type="button" id="rvgu-back1" class="pill" style="border:1px solid var(--border); background:none; color:var(--text2);">← Voltar</button>
                        <button type="submit" class="pill" style="flex:1; justify-content:center; background:var(--danger); color:#fff;">Avançar — assinar a desistência</button>
                    </div>
                    <p style="font-size:11px; color:var(--muted); margin:8px 0 0;">Vais receber um email de despedida com o teu Certificado de Desistência (PDF) da 1MusicMoz.</p>
                </form>
            </div>
        </div>
    </div>
    <?php endif; ?>
    <style>
    /* [1.5.414] z-index MÁXIMO: com 99998 o cabeçalho do tema e a admin bar
       do WP (99999) ficavam POR CIMA e "encolhiam" o painel no topo. O painel
       é ecrã inteiro — nada do tema pode sobrepor-se. */
    #rmbz-vip{ position:fixed; inset:0; z-index:2147483600; overflow:hidden; font-family:'Geist',system-ui,sans-serif; display:flex; }
    /* Sem scroll na página por trás (o painel tem o seu próprio scroll). */
    html, body{ overflow:hidden !important; }
    #wpadminbar{ display:none !important; }
    #rmbz-vip *{ box-sizing:border-box; }
    #rmbz-vip .ms{ font-family:'Material Symbols Rounded'; line-height:1; display:inline-flex; vertical-align:middle; }
    #rmbz-vip .mono{ font-family:'JetBrains Mono',monospace; }
    #rmbz-vip[data-theme="oled"]{ --bg:#000; --surface:#0e0e11; --elev:#17171b; --hover:#1e1e23; --border:#232329; --border2:#2e2e35; --text:#fafafa; --text2:#c4c4cc; --muted:#8a8a92; --brand:#f0b90b; --brand-soft:rgba(240,185,11,.12); --on-brand:#0a0a0a; --brand-ink:#f0b90b; --success:#10b981; --success-soft:rgba(16,185,129,.12); --danger:#ef4444; --danger-soft:rgba(239,68,68,.14); --info:#3b82f6; --info-soft:rgba(59,130,246,.14); --navy:#2c3e50; --vip1:#20392b; --vip2:#1e2320; --scrim:rgba(0,0,0,.7); --rev:#f0b90b; --rev-soft:rgba(240,185,11,.14); }
    #rmbz-vip[data-theme="claro"]{ --bg:#f6f4ee; --surface:#fff; --elev:#f1eee5; --hover:#edeadf; --border:#e4dfd1; --border2:#d5cfbe; --text:#171610; --text2:#4c4840; --muted:#86816f; --brand:#f0b90b; --brand-soft:rgba(240,185,11,.18); --on-brand:#1c1500; --brand-ink:#96770a; --success:#0d9268; --success-soft:rgba(16,185,129,.14); --danger:#d92f2f; --danger-soft:rgba(217,47,47,.10); --info:#2563eb; --info-soft:rgba(37,99,235,.10); --navy:#2c3e50; --vip1:#24513a; --vip2:#1e2b23; --scrim:rgba(23,22,16,.55); --rev:#96770a; --rev-soft:rgba(240,185,11,.16); }
    #rmbz-vip{ --rmbz-danger:var(--danger); --rmbz-success:var(--success); --rmbz-warning:var(--rev); --rmbz-warning-soft:var(--rev-soft); --rmbz-info:var(--info); --rmbz-info-soft:var(--info-soft); --rmbz-brand:var(--brand-ink); --rmbz-bg-input:var(--elev); --rmbz-bg-surface:var(--surface); --rmbz-bg-elevated:var(--elev); --rmbz-border-subtle:var(--border); --rmbz-text-primary:var(--text); --rmbz-text-secondary:var(--text2); --rmbz-text-muted:var(--muted); --rmbz-text-faint:var(--muted); --rmbz-radius-sm:12px; --rmbz-radius-md:18px; --rmbz-space-1:4px; --rmbz-space-2:8px; --rmbz-space-3:12px; --rmbz-space-4:16px; --rmbz-space-5:20px; --rmbz-space-6:24px; --rmbz-font-display:'Bricolage Grotesque',sans-serif; --rmbz-font-body:'Geist',system-ui,sans-serif; --rmbz-text-2xs:11px; --rmbz-text-xs:12px; --rmbz-text-sm:13px; --rmbz-text-lg:19px; --rmbz-weight-medium:600; --rmbz-weight-semibold:700; --rmbz-weight-bold:800; --rmbz-tracking-tight:-.01em; --rmbz-tracking-wider:.06em; --rmbz-leading-tight:1.25; --rmbz-leading-relaxed:1.6; }
    #rmbz-vip{ background:var(--bg); color:var(--text); }
    /* Splash de navegação: logo fixo no centro, com pulsação sem deslocamento. */
    #rmbz-vip-splash{ position:fixed; inset:0; z-index:2147483646; background:var(--bg); display:none; align-items:center; justify-content:center; }
    #rmbz-vip-splash.open{ display:flex; }
    #rmbz-vip-splash img{ width:92px; height:92px; border-radius:50%; box-shadow:0 14px 40px rgba(0,0,0,.34); animation:rmbzVipPulse 1.5s ease-in-out infinite; }
    @keyframes rmbzVipPulse{ 0%,100%{ filter:brightness(.94); box-shadow:0 14px 40px rgba(0,0,0,.34); } 50%{ filter:brightness(1.08); box-shadow:0 18px 54px rgba(0,0,0,.46); } }
    #rmbz-vip a{ color:var(--brand-ink); text-decoration:none; }
    #rmbz-vip ::-webkit-scrollbar{ width:10px; height:10px; }
    #rmbz-vip ::-webkit-scrollbar-thumb{ background:var(--border2); border-radius:8px; }
    #rmbz-vip .aside{ width:264px; flex-shrink:0; display:flex; flex-direction:column; padding:22px 14px 18px; border-right:1px solid var(--border); background:var(--surface); gap:3px; }
    #rmbz-vip .navbtn{ display:flex; align-items:center; gap:13px; width:100%; border:none; text-align:left; padding:12px 16px; border-radius:100px; background:transparent; color:var(--text2); font-family:inherit; font-size:13.5px; font-weight:550; cursor:pointer; transition:background .15s; }
    #rmbz-vip .navbtn:hover{ background:var(--hover); }
    #rmbz-vip .navbtn.on{ background:var(--brand-soft); color:var(--brand-ink); font-weight:700; }
    #rmbz-vip .navbtn.on .ms{ font-variation-settings:'FILL' 1; }
    #rmbz-vip .main{ flex:1; overflow-y:auto; }
    #rmbz-vip .wrap{ max-width:1440px; margin:0 auto; padding:26px 38px 60px; }
    #rmbz-vip .card{ background:var(--surface); border:1px solid var(--border); border-radius:26px; padding:24px 28px; }
    #rmbz-vip .vip-page-head{ display:flex; align-items:center; justify-content:space-between; gap:16px; margin-bottom:24px; }
    #rmbz-vip .vip-page-heading{ min-width:0; }
    #rmbz-vip .vip-page-title{ margin:0; color:var(--text); font-family:'Bricolage Grotesque',sans-serif; font-size:30px; line-height:1.15; font-weight:720; letter-spacing:-.025em; }
    #rmbz-vip .vip-page-sub{ margin-top:5px; color:var(--muted); font-size:12.5px; line-height:1.45; }
    #rmbz-vip .vip-page-notif{ position:relative; min-height:44px; padding:10px 16px; border:1px solid var(--border); background:var(--surface); color:var(--text2); box-shadow:0 6px 22px -22px rgba(0,0,0,.7); }
    #rmbz-vip .vip-page-notif>.ms{ font-size:19px; }
    #rmbz-vip .vip-page-notif-count{ display:inline-flex; min-width:20px; height:20px; padding:0 6px; align-items:center; justify-content:center; border-radius:100px; background:var(--danger); color:#fff; font-size:9.5px; font-weight:800; }
    #rmbz-vip .home-finance-grid{ display:grid; grid-template-columns:1.45fr 1fr 1fr; gap:14px; }
    #rmbz-vip .home-wealth-card{ position:relative; overflow:hidden; min-height:218px; display:flex; flex-direction:column; padding:25px 27px; border:1px solid rgba(255,255,255,.06); border-radius:27px; background:linear-gradient(145deg,#32485e 0%,#26394c 100%); color:#fff; box-shadow:0 18px 46px -38px rgba(17,30,43,.9); }
    #rmbz-vip .home-wealth-card::after{ content:''; position:absolute; width:190px; height:190px; right:-74px; top:-86px; border-radius:50%; background:rgba(255,255,255,.045); }
    #rmbz-vip .home-card-eyebrow{ position:relative; display:flex; align-items:center; gap:8px; color:rgba(255,255,255,.7); font-size:9.5px; line-height:1.2; font-weight:800; letter-spacing:.1em; text-transform:uppercase; }
    #rmbz-vip .home-card-eyebrow .ms{ font-size:17px; }
    #rmbz-vip .home-wealth-value{ position:relative; margin-top:13px; color:#fff; font-family:'JetBrains Mono',monospace; font-size:38px; line-height:1.08; font-weight:650; letter-spacing:-.035em; }
    #rmbz-vip .home-wealth-value small{ color:rgba(255,255,255,.62); font-family:'Geist',system-ui,sans-serif; font-size:13px; font-weight:750; letter-spacing:0; }
    #rmbz-vip .home-wealth-caption{ position:relative; margin-top:7px; color:rgba(255,255,255,.6); font-size:10.5px; line-height:1.4; }
    #rmbz-vip .home-wealth-actions{ position:relative; display:flex; gap:9px; flex-wrap:wrap; margin-top:auto; padding-top:17px; }
    #rmbz-vip .home-wealth-action{ min-height:42px; padding:9px 17px; font-size:11.5px; }
    #rmbz-vip .home-wealth-action.primary{ background:var(--brand); color:var(--on-brand); }
    #rmbz-vip .home-wealth-action.secondary{ background:rgba(255,255,255,.12); color:#fff; }
    #rmbz-vip .home-wealth-action .ms{ font-size:18px; }
    #rmbz-vip .home-finance-card{ min-height:218px; display:flex; flex-direction:column; padding:20px; border:1px solid var(--border); border-radius:25px; background:var(--surface); box-shadow:0 8px 28px -28px rgba(0,0,0,.65); }
    #rmbz-vip .home-finance-head{ display:flex; align-items:center; gap:10px; }
    #rmbz-vip .home-finance-icon{ width:40px; height:40px; flex:0 0 40px; align-items:center; justify-content:center; border-radius:13px; background:var(--brand-soft); color:var(--brand-ink); font-size:20px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .home-finance-label{ color:var(--muted); font-size:9.5px; line-height:1.25; font-weight:800; letter-spacing:.08em; text-transform:uppercase; }
    #rmbz-vip .home-finance-value{ margin-top:17px; color:var(--text); font-family:'JetBrains Mono',monospace; font-size:25px; line-height:1.1; font-weight:650; letter-spacing:-.02em; }
    #rmbz-vip .home-finance-value small{ color:var(--muted); font-family:'Geist',system-ui,sans-serif; font-size:10.5px; font-weight:750; }
    #rmbz-vip .home-finance-meta{ margin-top:7px; color:var(--muted); font-size:10.5px; line-height:1.5; }
    #rmbz-vip .home-finance-link{ display:inline-flex; align-items:center; gap:4px; align-self:flex-start; margin-top:auto; padding-top:13px; border:0; background:transparent; color:var(--brand-ink); font-family:inherit; font-size:10.5px; font-weight:780; cursor:pointer; }
    #rmbz-vip .home-finance-link .ms{ font-size:15px; }
    #rmbz-vip .home-live-banner{ display:flex; align-items:center; gap:11px; margin-top:14px; padding:12px 15px; border:1px solid color-mix(in srgb,var(--success) 24%,var(--border)); border-radius:17px; background:linear-gradient(120deg,var(--success-soft),var(--surface)); }
    #rmbz-vip .home-live-icon{ width:36px; height:36px; flex:0 0 36px; align-items:center; justify-content:center; border-radius:12px; background:var(--success); color:#fff; font-size:19px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .home-live-copy{ color:var(--text2); font-size:11.5px; line-height:1.45; }
    #rmbz-vip .home-live-copy b{ color:var(--text); }
    #rmbz-vip .home-main-grid{ display:grid; grid-template-columns:1.35fr 1fr; gap:14px; margin-top:14px; }
    #rmbz-vip .home-panel{ min-width:0; padding:20px; border:1px solid var(--border); border-radius:25px; background:var(--surface); box-shadow:0 8px 28px -28px rgba(0,0,0,.65); }
    #rmbz-vip .home-panel-head{ display:flex; align-items:center; gap:11px; margin-bottom:14px; }
    #rmbz-vip .home-panel-icon{ width:40px; height:40px; flex:0 0 40px; align-items:center; justify-content:center; border-radius:13px; background:var(--brand-soft); color:var(--brand-ink); font-size:20px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .home-panel-heading{ flex:1; min-width:0; }
    #rmbz-vip .home-panel-title{ color:var(--text); font-size:13px; line-height:1.3; font-weight:780; }
    #rmbz-vip .home-panel-subtitle{ margin-top:2px; color:var(--muted); font-size:10px; line-height:1.4; }
    #rmbz-vip .home-panel-link{ display:inline-flex; align-items:center; gap:4px; padding:7px 9px; border:0; border-radius:100px; background:var(--elev); color:var(--brand-ink); font-family:inherit; font-size:9.5px; font-weight:780; cursor:pointer; }
    #rmbz-vip .home-panel-link .ms{ font-size:14px; }
    #rmbz-vip .home-project-list{ display:flex; flex-direction:column; gap:8px; }
    #rmbz-vip .home-project-row{ display:grid; grid-template-columns:42px minmax(0,1fr) auto; gap:11px; align-items:center; min-width:0; padding:11px; border:1px solid var(--border); border-radius:17px; background:var(--elev); }
    #rmbz-vip .home-project-icon{ width:42px; height:42px; align-items:center; justify-content:center; border-radius:13px; background:var(--surface); color:var(--brand-ink); font-size:20px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .home-project-copy{ min-width:0; }
    #rmbz-vip .home-project-name{ overflow:hidden; color:var(--text); font-size:12.5px; line-height:1.35; font-weight:760; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .home-project-meta{ display:flex; align-items:center; gap:6px; margin-top:3px; color:var(--muted); font-size:9.5px; }
    #rmbz-vip .home-project-progress{ height:4px; margin-top:7px; overflow:hidden; border-radius:100px; background:var(--border2); }
    #rmbz-vip .home-project-progress span{ display:block; height:100%; border-radius:inherit; background:var(--brand); }
    #rmbz-vip .home-project-status{ display:inline-flex; align-items:center; min-height:27px; padding:5px 9px; border-radius:100px; font-size:9.5px; font-weight:780; white-space:nowrap; }
    #rmbz-vip .home-empty{ min-height:104px; display:flex; align-items:center; gap:12px; padding:14px; border:1px dashed var(--border2); border-radius:17px; background:var(--elev); }
    #rmbz-vip .home-empty>.ms{ width:40px; height:40px; flex:0 0 40px; align-items:center; justify-content:center; border-radius:13px; background:var(--surface); color:var(--muted); font-size:20px; }
    #rmbz-vip .home-empty strong{ display:block; color:var(--text); font-size:11.5px; }
    #rmbz-vip .home-empty small{ display:block; margin-top:3px; color:var(--muted); font-size:10px; line-height:1.45; }
    #rmbz-vip .home-work-stats{ display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:8px; }
    #rmbz-vip .home-work-stat{ min-width:0; padding:12px 10px; border:1px solid var(--border); border-radius:16px; background:var(--elev); }
    #rmbz-vip .home-work-stat>.ms{ width:29px; height:29px; align-items:center; justify-content:center; border-radius:10px; background:var(--surface); color:var(--brand-ink); font-size:16px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .home-work-value{ margin-top:9px; overflow:hidden; color:var(--text); font-family:'JetBrains Mono',monospace; font-size:18px; line-height:1.1; font-weight:700; text-overflow:ellipsis; }
    #rmbz-vip .home-work-label{ margin-top:4px; color:var(--muted); font-size:8.5px; line-height:1.3; font-weight:780; letter-spacing:.05em; text-transform:uppercase; }
    #rmbz-vip .home-vip-note{ display:flex; align-items:center; gap:10px; margin-top:11px; padding:11px 12px; border-radius:15px; background:var(--brand-soft); color:var(--text2); font-size:10.5px; line-height:1.45; }
    #rmbz-vip .home-vip-note>.ms{ width:32px; height:32px; flex:0 0 32px; align-items:center; justify-content:center; border-radius:11px; background:var(--brand); color:var(--on-brand); font-size:18px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .home-vip-note b{ color:var(--text); }
    #rmbz-vip .home-utility-grid{ display:grid; grid-template-columns:1fr 1fr; gap:14px; margin-top:14px; }
    #rmbz-vip .home-utility-card{ min-width:0; padding:18px; border:1px solid var(--border); border-radius:23px; background:var(--surface); }
    #rmbz-vip .home-utility-head{ display:flex; align-items:center; gap:10px; }
    #rmbz-vip .home-utility-head>div{ flex:1; min-width:0; }
    #rmbz-vip .home-utility-icon{ width:38px; height:38px; flex:0 0 38px; align-items:center; justify-content:center; border-radius:12px; background:var(--brand-soft); color:var(--brand-ink); font-size:20px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .home-utility-title{ color:var(--text); font-size:12.5px; font-weight:780; }
    #rmbz-vip .home-utility-text{ margin:3px 0 0; color:var(--muted); font-size:10.5px; line-height:1.45; }
    #rmbz-vip .home-utility-badge{ margin-left:auto; display:inline-flex; min-height:27px; align-items:center; padding:5px 8px; border-radius:100px; background:var(--elev); color:var(--brand-ink); font-size:9.5px; font-weight:780; white-space:nowrap; }
    #rmbz-vip .home-utility-form{ display:flex; gap:8px; margin-top:13px; }
    #rmbz-vip .home-utility-input{ min-width:0; min-height:43px; padding:10px 13px; border-radius:13px; font-size:12.5px; }
    #rmbz-vip .home-utility-action{ min-height:43px; justify-content:center; padding:9px 15px; background:var(--brand); color:var(--on-brand); font-size:11px; }
    #rmbz-vip .home-utility-action.outlined{ border:1px solid var(--border2); background:transparent; color:var(--brand-ink); }
    #rmbz-vip .home-utility-action .ms{ font-size:17px; }
    @media (max-width:1180px){ #rmbz-vip .home-finance-grid{ grid-template-columns:1fr 1fr; } #rmbz-vip .home-wealth-card{ grid-column:1 / -1; min-height:202px; } #rmbz-vip .home-main-grid{ grid-template-columns:1fr; } }
    @media (max-width:760px){ #rmbz-vip .vip-page-head{ align-items:flex-start; } #rmbz-vip .vip-page-title{ font-size:25px; } #rmbz-vip .vip-page-notif{ width:44px; min-width:44px; padding:0; justify-content:center; font-size:0; } #rmbz-vip .vip-page-notif-count{ position:absolute; top:-5px; right:-5px; } #rmbz-vip .home-finance-grid,#rmbz-vip .home-utility-grid{ grid-template-columns:1fr; } #rmbz-vip .home-wealth-card{ grid-column:auto; } #rmbz-vip .home-finance-card{ min-height:172px; } }
    @media (max-width:520px){ #rmbz-vip .home-wealth-card{ min-height:224px; padding:21px; } #rmbz-vip .home-wealth-value{ font-size:32px; } #rmbz-vip .home-wealth-action{ flex:1; justify-content:center; } #rmbz-vip .home-panel,#rmbz-vip .home-utility-card{ padding:16px; border-radius:21px; } #rmbz-vip .home-work-stats{ grid-template-columns:1fr; } #rmbz-vip .home-work-stat{ display:grid; grid-template-columns:32px minmax(0,1fr); grid-template-rows:auto auto; gap:0 10px; align-items:center; } #rmbz-vip .home-work-stat>.ms{ grid-row:1 / span 2; } #rmbz-vip .home-work-value{ margin-top:0; } #rmbz-vip .home-project-row{ grid-template-columns:38px minmax(0,1fr); } #rmbz-vip .home-project-icon{ width:38px; height:38px; } #rmbz-vip .home-project-status{ grid-column:2; justify-self:start; } #rmbz-vip .home-utility-head{ align-items:flex-start; flex-wrap:wrap; } #rmbz-vip .home-utility-badge{ margin-left:48px; } #rmbz-vip .home-utility-form{ flex-wrap:wrap; } #rmbz-vip .home-utility-action{ flex:1; } }
    #rmbz-vip .finance-hero{ position:relative; overflow:hidden; display:grid; grid-template-columns:minmax(0,1.15fr) minmax(440px,.85fr); gap:22px; align-items:stretch; min-height:230px; padding:25px 27px; border:1px solid rgba(255,255,255,.08); border-radius:28px; background:linear-gradient(125deg,#17243a 0%,#213b4f 54%,#24513a 100%); color:#fff; box-shadow:0 22px 56px -48px rgba(10,24,39,.95); }
    #rmbz-vip .finance-hero::after{ content:''; position:absolute; width:260px; height:260px; right:-86px; top:-132px; border-radius:50%; background:rgba(255,255,255,.045); pointer-events:none; }
    #rmbz-vip .finance-hero-main{ position:relative; min-width:0; display:flex; flex-direction:column; }
    #rmbz-vip .finance-hero-head{ display:flex; align-items:center; gap:9px; color:rgba(255,255,255,.68); font-size:11px; font-weight:820; letter-spacing:.08em; text-transform:uppercase; }
    #rmbz-vip .finance-hero-head>.ms{ width:31px; height:31px; align-items:center; justify-content:center; border-radius:10px; background:rgba(240,185,11,.15); color:#f0b90b; font-size:18px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .finance-hero-state{ margin-left:auto; display:inline-flex; align-items:center; gap:5px; min-height:29px; padding:5px 9px; border-radius:100px; background:rgba(255,255,255,.08); color:rgba(255,255,255,.78); font-size:10px; font-weight:760; letter-spacing:0; text-transform:none; }
    #rmbz-vip .finance-hero-state .ms{ color:#6ee7b7; font-size:14px; }
    #rmbz-vip .finance-hero-value{ margin-top:17px; color:#fff; font-family:'JetBrains Mono',monospace; font-size:38px; line-height:1.08; font-weight:680; letter-spacing:-.045em; }
    #rmbz-vip .finance-hero-value small{ margin-left:5px; color:rgba(255,255,255,.58); font-family:'Geist',system-ui,sans-serif; font-size:12px; font-weight:760; letter-spacing:0; }
    #rmbz-vip .finance-balance-facts{ display:flex; align-items:center; gap:7px; flex-wrap:wrap; margin-top:11px; }
    #rmbz-vip .finance-balance-fact{ display:inline-flex; align-items:center; gap:6px; min-height:31px; padding:6px 10px; border-radius:100px; background:rgba(255,255,255,.075); color:rgba(255,255,255,.68); font-size:10.5px; }
    #rmbz-vip .finance-balance-fact .ms{ font-size:14px; }
    #rmbz-vip .finance-balance-fact b{ color:#fff; font-weight:760; }
    #rmbz-vip .finance-hero-actions{ display:flex; gap:8px; flex-wrap:wrap; margin-top:auto; padding-top:17px; }
    #rmbz-vip .finance-action{ min-height:43px; padding:9px 16px; font-size:12px; }
    #rmbz-vip .finance-action.primary{ background:var(--brand); color:var(--on-brand); }
    #rmbz-vip .finance-action.secondary{ background:rgba(255,255,255,.11); color:#fff; }
    #rmbz-vip .finance-action .ms{ font-size:17px; }
    #rmbz-vip .finance-hero-metrics{ position:relative; display:grid; grid-template-columns:1fr 1fr; gap:9px; align-content:center; }
    #rmbz-vip .finance-metric{ min-width:0; min-height:84px; padding:13px; border:1px solid rgba(255,255,255,.09); border-radius:18px; background:rgba(255,255,255,.07); backdrop-filter:blur(10px); }
    #rmbz-vip .finance-metric.wide{ grid-column:1 / -1; min-height:70px; display:grid; grid-template-columns:40px minmax(0,1fr) auto; gap:10px; align-items:center; }
    #rmbz-vip .finance-metric-label{ color:rgba(255,255,255,.6); font-size:10px; font-weight:800; letter-spacing:.06em; text-transform:uppercase; }
    #rmbz-vip .finance-metric-value{ margin-top:7px; overflow:hidden; color:#fff; font-family:'JetBrains Mono',monospace; font-size:16px; font-weight:680; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .finance-metric.credit .finance-metric-value{ color:#6ee7b7; }
    #rmbz-vip .finance-metric.debit .finance-metric-value{ color:#fca5a5; }
    #rmbz-vip .finance-metric-icon{ width:40px; height:40px; align-items:center; justify-content:center; border-radius:13px; background:rgba(240,185,11,.15); color:#f0b90b; font-size:20px; }
    #rmbz-vip .finance-metric-pending{ display:inline-flex; align-items:center; min-height:29px; padding:5px 9px; border-radius:100px; background:rgba(240,185,11,.14); color:#f6cf54; font-size:10px; font-weight:780; white-space:nowrap; }
    #rmbz-vip .finance-tabs{ display:flex; gap:7px; overflow-x:auto; margin:14px 0 13px; padding:2px 1px; scrollbar-width:none; }
    #rmbz-vip .finance-tab{ flex:0 0 auto; min-height:41px; display:inline-flex; align-items:center; gap:7px; padding:8px 14px; border:1px solid var(--border); border-radius:100px; background:var(--surface); color:var(--text2); font-size:12px; font-weight:720; transition:background .15s,border-color .15s,color .15s; }
    #rmbz-vip .finance-tab:hover{ background:var(--hover); }
    #rmbz-vip .finance-tab.active{ border-color:color-mix(in srgb,var(--brand) 70%,var(--border)); background:var(--brand-soft); color:var(--brand-ink); }
    #rmbz-vip .finance-tab>.ms{ font-size:17px; }
    #rmbz-vip .finance-tab-count{ min-width:21px; height:21px; display:inline-flex; align-items:center; justify-content:center; padding:0 6px; border-radius:100px; background:var(--elev); color:var(--muted); font-family:'JetBrains Mono',monospace; font-size:10px; }
    #rmbz-vip .finance-tab.active .finance-tab-count{ background:var(--brand); color:var(--on-brand); }
    #rmbz-vip .finance-panels{ display:grid; grid-template-columns:1fr 1fr; gap:13px; align-items:start; }
    #rmbz-vip .finance-panels.single{ grid-template-columns:1fr; }
    #rmbz-vip .finance-panel{ min-width:0; padding:18px; border-radius:23px; }
    #rmbz-vip .finance-panel-head{ display:flex; align-items:center; gap:10px; margin-bottom:11px; }
    #rmbz-vip .finance-panel-icon{ width:39px; height:39px; flex:0 0 39px; align-items:center; justify-content:center; border-radius:13px; background:var(--brand-soft); color:var(--brand-ink); font-size:20px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .finance-panel-copy{ flex:1; min-width:0; }
    #rmbz-vip .finance-panel-title{ color:var(--text); font-size:14px; font-weight:800; }
    #rmbz-vip .finance-panel-subtitle{ margin-top:3px; color:var(--muted); font-size:11px; }
    #rmbz-vip .finance-panel-count{ display:inline-flex; min-height:29px; align-items:center; padding:5px 9px; border-radius:100px; background:var(--elev); color:var(--text2); font-size:10px; font-weight:780; }
    #rmbz-vip .finance-request-list{ display:flex; flex-direction:column; gap:7px; }
    #rmbz-vip .finance-request{ display:grid; grid-template-columns:40px minmax(0,1fr) auto auto; gap:10px; align-items:center; min-width:0; padding:10px; border:1px solid var(--border); border-radius:16px; background:var(--elev); }
    #rmbz-vip .finance-request-icon{ width:40px; height:40px; align-items:center; justify-content:center; border-radius:13px; background:var(--surface); color:var(--brand-ink); font-size:20px; }
    #rmbz-vip .finance-request-copy{ min-width:0; }
    #rmbz-vip .finance-request-value{ overflow:hidden; color:var(--text); font-size:13.5px; font-weight:760; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .finance-request-meta{ display:flex; align-items:center; gap:5px; margin-top:4px; overflow:hidden; color:var(--muted); font-size:10.5px; white-space:nowrap; }
    #rmbz-vip .finance-request-meta>.ms{ font-size:13px; }
    #rmbz-vip .finance-request-status{ display:inline-flex; align-items:center; min-height:28px; padding:5px 9px; border-radius:100px; font-size:10px; font-weight:780; white-space:nowrap; }
    #rmbz-vip .finance-request-detail{ min-height:33px; padding:6px 10px; border:1px solid var(--border2); background:var(--surface); color:var(--text2); font-size:10.5px; }
    #rmbz-vip .finance-empty{ min-height:125px; display:flex; align-items:center; justify-content:center; gap:11px; padding:17px; border:1px dashed var(--border2); border-radius:17px; background:var(--elev); text-align:left; }
    #rmbz-vip .finance-empty>.ms{ width:42px; height:42px; flex:0 0 42px; align-items:center; justify-content:center; border-radius:14px; background:var(--surface); color:var(--muted); font-size:21px; }
    #rmbz-vip .finance-empty strong{ display:block; color:var(--text); font-size:12.5px; }
    #rmbz-vip .finance-empty small{ display:block; margin-top:3px; color:var(--muted); font-size:11px; line-height:1.45; }
    #rmbz-vip .finance-statement{ margin-top:13px; padding:0; overflow:hidden; border-radius:24px; }
    #rmbz-vip .finance-statement-head{ display:flex; align-items:center; justify-content:space-between; gap:12px; padding:17px 19px; border-bottom:1px solid var(--border); }
    #rmbz-vip .finance-statement-heading{ display:flex; align-items:center; gap:10px; min-width:0; }
    #rmbz-vip .finance-statement-icon{ width:40px; height:40px; flex:0 0 40px; align-items:center; justify-content:center; border-radius:13px; background:var(--brand-soft); color:var(--brand-ink); font-size:20px; }
    #rmbz-vip .finance-statement-title{ color:var(--text); font-size:14px; font-weight:800; }
    #rmbz-vip .finance-statement-subtitle{ margin-top:3px; color:var(--muted); font-size:11px; }
    #rmbz-vip .finance-statement-open{ min-height:38px; padding:7px 12px; border:1px solid var(--border2); background:var(--surface); color:var(--brand-ink); font-size:11px; }
    #rmbz-vip .finance-filter{ display:flex; align-items:end; gap:8px; flex-wrap:wrap; padding:13px 19px; border-bottom:1px solid var(--border); background:var(--elev); }
    #rmbz-vip .finance-filter-label{ display:block; margin:0 0 5px 2px; color:var(--muted); font-size:10px; font-weight:780; letter-spacing:.06em; text-transform:uppercase; }
    #rmbz-vip .finance-filter-search{ min-height:40px; display:flex; align-items:center; gap:7px; padding:0 11px; border:1px solid var(--border2); border-radius:13px; background:var(--surface); }
    #rmbz-vip .finance-filter-search>.ms{ color:var(--muted); font-size:17px; }
    #rmbz-vip .finance-filter-search input{ width:100%; min-width:0; padding:10px 0; border:0; outline:0; background:transparent; color:var(--text); font-family:inherit; font-size:12px; font-weight:620; }
    #rmbz-vip .finance-filter-action{ min-height:40px; justify-content:center; padding:8px 12px; font-size:11px; }
    #rmbz-vip .finance-transactions{ padding:4px 19px 8px; }
    #rmbz-vip .finance-transaction{ display:grid; grid-template-columns:40px minmax(0,1fr) auto; gap:11px; align-items:center; padding:11px 0; border-bottom:1px solid var(--border); }
    #rmbz-vip .finance-transaction-icon{ width:40px; height:40px; align-items:center; justify-content:center; border-radius:13px; font-size:19px; }
    #rmbz-vip .finance-transaction-copy{ min-width:0; }
    #rmbz-vip .finance-transaction-title{ overflow:hidden; color:var(--text); font-size:13px; font-weight:740; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .finance-transaction-meta{ display:flex; align-items:center; gap:5px; flex-wrap:wrap; margin-top:4px; color:var(--muted); font-size:10.5px; }
    #rmbz-vip .finance-transaction-state{ font-weight:720; }
    #rmbz-vip .finance-transaction-value{ color:var(--text); font-size:13px; font-weight:720; white-space:nowrap; }
    @media (max-width:1100px){ #rmbz-vip .finance-hero{ grid-template-columns:1fr; } #rmbz-vip .finance-hero-metrics{ grid-template-columns:repeat(3,minmax(0,1fr)); } #rmbz-vip .finance-metric.wide{ grid-column:auto; grid-template-columns:35px minmax(0,1fr); } #rmbz-vip .finance-metric.wide .finance-metric-pending{ grid-column:2; justify-self:start; } }
    @media (max-width:760px){ #rmbz-vip .finance-panels{ grid-template-columns:1fr; } #rmbz-vip .finance-request{ grid-template-columns:38px minmax(0,1fr) auto; } #rmbz-vip .finance-request-icon{ width:38px; height:38px; } #rmbz-vip .finance-request-status{ grid-column:2; justify-self:start; } #rmbz-vip .finance-request-detail{ grid-column:3; grid-row:1 / span 2; } }
    @media (max-width:600px){ #rmbz-vip .finance-hero{ min-height:0; padding:20px; border-radius:24px; } #rmbz-vip .finance-hero-value{ font-size:32px; } #rmbz-vip .finance-hero-state{ display:none; } #rmbz-vip .finance-hero-actions .finance-action{ flex:1; justify-content:center; } #rmbz-vip .finance-hero-metrics{ grid-template-columns:1fr 1fr; } #rmbz-vip .finance-metric.wide{ grid-column:1 / -1; } #rmbz-vip .finance-panel{ padding:15px; } #rmbz-vip .finance-statement-head{ align-items:flex-start; } #rmbz-vip .finance-statement-open{ width:37px; padding:0; font-size:0; } #rmbz-vip .finance-filter>*{ flex:1 1 100% !important; } #rmbz-vip .finance-transaction{ grid-template-columns:37px minmax(0,1fr); } #rmbz-vip .finance-transaction-icon{ width:37px; height:37px; } #rmbz-vip .finance-transaction-value{ grid-column:2; justify-self:start; } }
    #rmbz-vip .vip-services-grid{ display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:12px; }
    #rmbz-vip .vip-service{ min-height:188px; display:flex; flex-direction:column; padding:17px; border:1px solid var(--border); border-radius:20px; background:var(--elev); color:var(--text); text-align:left; font-family:inherit; cursor:pointer; transition:transform .18s ease,border-color .18s ease,background .18s ease; }
    #rmbz-vip .vip-service:hover{ transform:translateY(-2px); border-color:var(--brand); background:var(--hover); }
    #rmbz-vip .vip-service.is-paused{ border-style:dashed; }
    #rmbz-vip .vip-service-icon{ width:44px; height:44px; border-radius:14px; align-items:center; justify-content:center; flex:0 0 auto; background:var(--brand-soft); color:var(--brand-ink); font-size:23px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .vip-service-state{ display:inline-flex; align-items:center; gap:4px; border-radius:100px; padding:5px 9px; background:var(--success-soft); color:var(--success); font-size:10.5px; font-weight:750; white-space:nowrap; }
    #rmbz-vip .vip-service-state.is-paused{ background:var(--rev-soft); color:var(--rev); }
    #rmbz-vip .vip-service-go{ display:flex; align-items:center; gap:5px; margin-top:auto; padding-top:14px; color:var(--brand-ink); font-size:11.5px; font-weight:750; }
    #rmbz-vip .vip-profile-grid{ display:grid; grid-template-columns:340px minmax(0,1fr); gap:16px; align-items:stretch; }
    #rmbz-vip .vip-profile-identity{ display:flex; flex-direction:column; align-items:center; padding:27px; text-align:center; }
    #rmbz-vip .vip-profile-avatar{ width:92px; height:92px; display:flex; align-items:center; justify-content:center; border:7px solid var(--brand-soft); border-radius:50%; background:var(--brand); color:var(--on-brand); font-family:'Bricolage Grotesque',sans-serif; font-size:32px; font-weight:800; box-shadow:0 14px 34px -28px rgba(0,0,0,.8); }
    #rmbz-vip .vip-profile-name{ margin-top:13px; font-family:'Bricolage Grotesque',sans-serif; font-size:21px; line-height:1.2; font-weight:780; }
    #rmbz-vip .vip-profile-role{ margin-top:4px; color:var(--muted); font-size:11.5px; }
    #rmbz-vip .vip-membership{ width:100%; margin-top:20px; padding:17px; border:1px solid rgba(255,255,255,.08); border-radius:20px; background:linear-gradient(145deg,var(--vip1),var(--vip2)); color:#fff; text-align:left; box-shadow:0 18px 40px -34px rgba(0,0,0,.9); }
    #rmbz-vip .vip-membership-head{ display:flex; align-items:center; gap:8px; color:rgba(255,255,255,.75); font-size:9.5px; font-weight:800; letter-spacing:.09em; text-transform:uppercase; }
    #rmbz-vip .vip-membership-head>.ms{ color:#f0b90b; font-size:18px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .vip-membership-state{ margin-left:auto; padding:4px 7px; border-radius:100px; background:rgba(255,255,255,.11); color:#fff; font-size:8.5px; letter-spacing:.04em; }
    #rmbz-vip .vip-membership-state.inactive{ background:rgba(239,68,68,.2); color:#fecaca; }
    #rmbz-vip .vip-membership-plan{ margin-top:13px; font-family:'Bricolage Grotesque',sans-serif; font-size:19px; line-height:1.2; font-weight:760; }
    #rmbz-vip .vip-membership-facts{ display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-top:13px; }
    #rmbz-vip .vip-membership-fact{ min-width:0; padding:9px 10px; border-radius:13px; background:rgba(255,255,255,.07); }
    #rmbz-vip .vip-membership-fact span{ display:block; color:rgba(255,255,255,.56); font-size:8.5px; font-weight:750; letter-spacing:.06em; text-transform:uppercase; }
    #rmbz-vip .vip-membership-fact strong{ display:block; margin-top:3px; overflow:hidden; color:#fff; font-size:11.5px; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .vip-membership-link{ width:100%; display:flex; align-items:center; justify-content:center; gap:6px; min-height:37px; margin-top:12px; border:0; border-radius:100px; background:#f0b90b; color:#171000 !important; font-family:inherit; font-size:10.5px; font-weight:800; cursor:pointer; }
    #rmbz-vip .vip-membership-link .ms{ font-size:16px; }
    #rmbz-vip .vip-account-card{ padding:23px 25px; }
    #rmbz-vip .vip-section-head{ display:flex; align-items:center; gap:11px; flex-wrap:wrap; }
    #rmbz-vip .vip-section-icon{ width:43px; height:43px; flex:0 0 43px; align-items:center; justify-content:center; border-radius:14px; background:var(--brand-soft); color:var(--brand-ink); font-size:22px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .vip-section-icon.info{ background:var(--info-soft); color:var(--info); }
    #rmbz-vip .vip-section-copy{ flex:1; min-width:180px; }
    #rmbz-vip .vip-section-title{ color:var(--text); font-size:14px; line-height:1.3; font-weight:800; }
    #rmbz-vip .vip-section-subtitle{ margin-top:2px; color:var(--muted); font-size:10.5px; line-height:1.45; }
    #rmbz-vip .vip-account-badge,#rmbz-vip .vip-security-count{ display:inline-flex; align-items:center; gap:5px; min-height:29px; padding:6px 10px; border-radius:100px; background:var(--elev); color:var(--text2); font-size:9.5px; font-weight:760; white-space:nowrap; }
    #rmbz-vip .vip-account-badge .ms,#rmbz-vip .vip-security-count .ms{ font-size:14px; }
    #rmbz-vip .vip-account-grid{ display:grid; grid-template-columns:1fr 1fr; gap:9px; margin-top:15px; }
    #rmbz-vip .vip-account-field{ min-width:0; display:flex; align-items:center; gap:11px; padding:12px; border:1px solid var(--border); border-radius:16px; background:var(--elev); }
    #rmbz-vip .vip-account-field>.ms{ width:35px; height:35px; flex:0 0 35px; align-items:center; justify-content:center; border-radius:11px; background:var(--surface); color:var(--brand-ink); font-size:18px; }
    #rmbz-vip .vip-account-field-copy{ min-width:0; }
    #rmbz-vip .vip-account-field-label{ color:var(--muted); font-size:8.5px; font-weight:780; letter-spacing:.06em; text-transform:uppercase; }
    #rmbz-vip .vip-account-field-value{ margin-top:3px; overflow:hidden; color:var(--text); font-size:11.5px; font-weight:680; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .vip-account-actions{ display:flex; gap:9px; flex-wrap:wrap; margin-top:14px; padding-top:14px; border-top:1px solid var(--border); }
    #rmbz-vip .vip-account-action{ min-height:39px; padding:8px 13px; border:1px solid var(--border2); background:transparent; color:var(--brand-ink); font-size:10.5px; }
    #rmbz-vip .vip-account-action.danger{ color:var(--danger); }
    #rmbz-vip .vip-account-edit{ margin-top:12px; padding:15px; border:1px solid var(--border); border-radius:17px; background:var(--elev); }
    #rmbz-vip .vip-security-card{ margin-top:16px; padding:22px 24px; }
    #rmbz-vip .vip-security-head-actions{ display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
    #rmbz-vip .vip-security-all{ min-height:34px; padding:7px 11px; border:1px solid var(--danger); background:transparent; color:var(--danger); font-size:9.5px; }
    #rmbz-vip .vip-security-success{ display:flex; align-items:center; gap:7px; margin-top:13px; padding:10px 12px; border-radius:13px; background:var(--success-soft); color:var(--success); font-size:10.5px; font-weight:680; }
    #rmbz-vip .vip-session-list{ display:flex; flex-direction:column; gap:8px; margin-top:14px; }
    #rmbz-vip .vip-session{ display:grid; grid-template-columns:40px minmax(0,1fr) auto auto; gap:11px; align-items:center; padding:11px 12px; border:1px solid var(--border); border-radius:16px; background:var(--elev); }
    #rmbz-vip .vip-session-icon{ width:40px; height:40px; align-items:center; justify-content:center; border-radius:13px; background:var(--surface); color:var(--brand-ink); font-size:20px; }
    #rmbz-vip .vip-session-copy{ min-width:0; }
    #rmbz-vip .vip-session-name{ overflow:hidden; color:var(--text); font-size:11.5px; font-weight:760; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .vip-session-meta{ margin-top:3px; color:var(--muted); font-size:9.5px; line-height:1.45; }
    #rmbz-vip .vip-session-state{ display:inline-flex; align-items:center; gap:5px; padding:5px 8px; border-radius:100px; background:var(--success-soft); color:var(--success); font-size:8.5px; font-weight:780; white-space:nowrap; }
    #rmbz-vip .vip-session-state::before{ content:''; width:6px; height:6px; border-radius:50%; background:currentColor; }
    #rmbz-vip .vip-session-end{ min-height:31px; padding:6px 9px; border:1px solid var(--border2); background:var(--surface); color:var(--danger); font-size:9.5px; }
    #rmbz-vip .vip-security-empty{ display:flex; align-items:center; gap:10px; margin-top:14px; padding:13px; border:1px dashed var(--border2); border-radius:15px; background:var(--elev); color:var(--muted); font-size:10.5px; }
    #rmbz-vip .vip-security-empty>.ms{ font-size:21px; }
    #rmbz-vip .vip-security-note{ display:flex; align-items:flex-start; gap:6px; margin-top:11px; color:var(--muted); font-size:9.5px; line-height:1.5; }
    #rmbz-vip .vip-security-note .ms{ margin-top:1px; font-size:14px; }
    #rmbz-vip .vip-packages-card{ margin-top:16px; padding:24px; scroll-margin-top:24px; }
    #rmbz-vip .vip-packages-wallet{ display:inline-flex; align-items:center; gap:7px; min-height:35px; padding:7px 11px; border-radius:100px; background:var(--brand-soft); color:var(--brand-ink); font-size:10px; font-weight:780; white-space:nowrap; }
    #rmbz-vip .vip-packages-wallet .ms{ font-size:16px; }
    #rmbz-vip .vip-packages-intro{ margin:12px 0 17px; color:var(--muted); font-size:11px; line-height:1.55; }
    #rmbz-vip .vip-packages-grid{ display:grid; grid-template-columns:repeat(auto-fit,minmax(245px,1fr)); gap:12px; }
    #rmbz-vip .vip-package{ position:relative; min-width:0; display:flex; flex-direction:column; padding:17px; border:1px solid var(--border); border-radius:21px; background:var(--elev); transition:transform .18s ease,border-color .18s ease,box-shadow .18s ease; }
    #rmbz-vip .vip-package:hover{ transform:translateY(-2px); border-color:var(--border2); box-shadow:0 17px 36px -34px rgba(0,0,0,.9); }
    #rmbz-vip .vip-package.is-featured{ border-color:color-mix(in srgb,var(--brand) 70%,var(--border)); background:linear-gradient(160deg,var(--brand-soft),var(--elev) 42%); }
    #rmbz-vip .vip-package.is-current{ border-color:var(--success); box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--success) 30%,transparent); }
    #rmbz-vip .vip-package-head{ display:grid; grid-template-columns:40px minmax(0,1fr) auto; gap:10px; align-items:center; }
    #rmbz-vip .vip-package-icon{ width:40px; height:40px; align-items:center; justify-content:center; border-radius:13px; background:var(--surface); color:var(--brand-ink); font-size:20px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .vip-package-name{ overflow:hidden; color:var(--text); font-size:13px; line-height:1.3; font-weight:820; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .vip-package-count{ margin-top:2px; color:var(--muted); font-size:9px; }
    #rmbz-vip .vip-package-badge{ display:inline-flex; align-items:center; min-height:25px; padding:5px 7px; border-radius:100px; background:var(--brand-soft); color:var(--brand-ink); font-size:8px; font-weight:820; white-space:nowrap; }
    #rmbz-vip .vip-package-badge.current{ background:var(--success-soft); color:var(--success); }
    #rmbz-vip .vip-package-price{ margin-top:16px; color:var(--brand-ink); font-size:25px; line-height:1.1; font-weight:720; letter-spacing:-.04em; }
    #rmbz-vip .vip-package-days{ display:flex; align-items:center; gap:5px; margin-top:5px; color:var(--muted); font-size:9.5px; }
    #rmbz-vip .vip-package-days .ms{ color:var(--brand-ink); font-size:15px; }
    #rmbz-vip .vip-package-services{ display:flex; flex-direction:column; gap:6px; margin:15px 0; padding:12px 0; border-top:1px solid var(--border); border-bottom:1px solid var(--border); }
    #rmbz-vip .vip-package-service{ display:flex; align-items:center; gap:7px; min-width:0; color:var(--text2); font-size:10px; }
    #rmbz-vip .vip-package-service>.ms{ width:22px; height:22px; flex:0 0 22px; align-items:center; justify-content:center; border-radius:8px; background:var(--success-soft); color:var(--success); font-size:14px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .vip-package-service.not-included{ color:var(--muted); }
    #rmbz-vip .vip-package-service.not-included>.ms{ background:var(--surface); color:var(--muted); font-variation-settings:'FILL' 0; }
    #rmbz-vip .rmbz-vip-pk-form{ display:flex; flex:1; flex-direction:column; }
    #rmbz-vip .vip-package-field-label{ display:block; margin-bottom:5px; color:var(--muted); font-size:8.5px; font-weight:800; letter-spacing:.07em; text-transform:uppercase; }
    #rmbz-vip .vip-package-select{ min-height:41px; padding:9px 11px; border-radius:13px; font-size:10.5px; }
    #rmbz-vip .vip-package-addon{ display:grid; grid-template-columns:18px 34px minmax(0,1fr); gap:8px; align-items:center; margin-top:9px; margin-bottom:12px; padding:10px; border:1px solid var(--border); border-radius:14px; background:var(--surface); cursor:pointer; }
    #rmbz-vip .vip-package-addon input{ width:18px; height:18px; margin:0; accent-color:var(--brand); }
    #rmbz-vip .vip-package-addon-icon{ width:34px; height:34px; align-items:center; justify-content:center; border-radius:11px; background:var(--brand-soft); color:var(--brand-ink); font-size:18px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .vip-package-addon strong{ display:block; color:var(--text); font-size:9.5px; }
    #rmbz-vip .vip-package-addon small{ display:block; margin-top:2px; color:var(--muted); font-size:8.5px; line-height:1.4; }
    #rmbz-vip .vip-package-submit{ width:100%; min-height:42px; justify-content:center; margin-top:auto; padding:9px 13px; background:var(--brand); color:var(--on-brand); font-size:10.5px; }
    #rmbz-vip .vip-package-submit .ms{ font-size:17px; }
    #rmbz-vip .vip-package-empty{ display:flex; align-items:center; gap:12px; padding:16px; border:1px dashed var(--border2); border-radius:18px; background:var(--elev); }
    #rmbz-vip .vip-package-empty>.ms{ width:42px; height:42px; flex:0 0 42px; align-items:center; justify-content:center; border-radius:14px; background:var(--success-soft); color:var(--success); font-size:22px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .vip-package-empty strong{ display:block; color:var(--text); font-size:11.5px; }
    #rmbz-vip .vip-package-empty small{ display:block; margin-top:3px; color:var(--muted); font-size:9.5px; line-height:1.5; }
    #rmbz-vip .vip-plan-dialog{ width:min(1120px,96vw); max-height:92vh; padding:0; overflow:hidden; display:flex; flex-direction:column; }
    #rmbz-vip .vip-plan-modal-head{ display:flex; align-items:center; gap:12px; padding:18px 20px; border-bottom:1px solid var(--border); background:var(--surface); }
    #rmbz-vip .vip-plan-modal-icon{ width:44px; height:44px; flex:0 0 44px; align-items:center; justify-content:center; border-radius:15px; background:var(--brand-soft); color:var(--brand-ink); font-size:23px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .vip-plan-modal-copy{ flex:1; min-width:0; }
    #rmbz-vip .vip-plan-modal-title{ font-family:'Bricolage Grotesque',sans-serif; color:var(--text); font-size:18px; line-height:1.25; font-weight:780; }
    #rmbz-vip .vip-plan-modal-subtitle{ margin-top:3px; color:var(--muted); font-size:10.5px; line-height:1.45; }
    #rmbz-vip .vip-plan-modal-wallet{ display:inline-flex; align-items:center; gap:6px; min-height:32px; padding:7px 10px; border-radius:100px; background:var(--brand-soft); color:var(--brand-ink); font-size:9.5px; font-weight:780; white-space:nowrap; }
    #rmbz-vip .vip-plan-modal-wallet .ms{ font-size:15px; }
    #rmbz-vip .vip-plan-modal-close{ width:36px; height:36px; display:flex; align-items:center; justify-content:center; flex:0 0 36px; border:0; border-radius:50%; background:var(--elev); color:var(--text2); cursor:pointer; }
    #rmbz-vip .vip-plan-modal-close .ms{ font-size:20px; }
    #rmbz-vip .vip-plan-modal-note{ display:flex; align-items:flex-start; gap:8px; margin:16px 20px 0; padding:11px 13px; border-radius:15px; background:var(--success-soft); color:var(--success); font-size:10px; line-height:1.5; }
    #rmbz-vip .vip-plan-modal-note .ms{ margin-top:1px; font-size:16px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .vip-plan-modal-body{ flex:1; min-height:0; overflow:auto; padding:16px 20px 20px; }
    #rmbz-vip .vip-plan-modal-body>.vip-packages-grid{ grid-template-columns:repeat(auto-fit,minmax(240px,1fr)); }
    @media (max-width:1050px){ #rmbz-vip .vip-profile-grid{ grid-template-columns:1fr; } #rmbz-vip .vip-profile-identity{ align-items:flex-start; display:grid; grid-template-columns:92px minmax(0,1fr); gap:0 17px; text-align:left; } #rmbz-vip .vip-profile-avatar{ grid-row:1 / span 2; } #rmbz-vip .vip-profile-name{ align-self:end; margin-top:0; } #rmbz-vip .vip-membership{ grid-column:1 / -1; } }
    @media (max-width:660px){ #rmbz-vip .vip-account-grid{ grid-template-columns:1fr; } #rmbz-vip .vip-session{ grid-template-columns:38px minmax(0,1fr) auto; } #rmbz-vip .vip-session-icon{ width:38px; height:38px; } #rmbz-vip .vip-session-state{ grid-column:2; justify-self:start; } #rmbz-vip .vip-session form{ grid-column:3; grid-row:1 / span 2; } #rmbz-vip .vip-packages-card,#rmbz-vip .vip-security-card{ padding:18px; } #rmbz-vip .vip-plan-dialog{ width:100%; max-width:none; max-height:94vh; margin-top:auto; border-radius:25px 25px 0 0; } #rmbz-vip .vip-plan-modal-head{ align-items:flex-start; padding:16px; } #rmbz-vip .vip-plan-modal-wallet{ display:none; } #rmbz-vip .vip-plan-modal-note{ margin:13px 16px 0; } #rmbz-vip .vip-plan-modal-body{ padding:13px 16px 20px; } }
    @media (max-width:430px){ #rmbz-vip .vip-profile-identity{ display:flex; align-items:center; text-align:center; } #rmbz-vip .vip-membership-facts{ grid-template-columns:1fr; } #rmbz-vip .vip-account-actions .pill{ width:100%; justify-content:center; } #rmbz-vip .vip-security-head-actions{ width:100%; } #rmbz-vip .vip-security-all{ flex:1; justify-content:center; } #rmbz-vip .vip-session{ grid-template-columns:36px minmax(0,1fr); } #rmbz-vip .vip-session form{ grid-column:1 / -1; grid-row:auto; } #rmbz-vip .vip-session-end{ width:100%; justify-content:center; } #rmbz-vip .vip-packages-wallet{ width:100%; justify-content:center; } }
    #rmbz-vip .pill{ display:inline-flex; align-items:center; gap:8px; border:none; border-radius:100px; padding:12px 24px; font-size:13.5px; font-weight:750; cursor:pointer; font-family:inherit; }
    #rmbz-vip .sect{ display:none; }
    #rmbz-vip .sect.on{ display:block; animation:rmbzVipIn .3s ease; }
    #rmbz-vip .status{ display:inline-flex; align-items:center; font-size:11px; font-weight:750; border-radius:100px; padding:5px 13px; white-space:nowrap; }
    #rmbz-vip .rec{ width:8px; height:8px; border-radius:50%; background:var(--danger); display:inline-block; animation:rmbzVipRec 1s infinite; }
    #rmbz-vip .shoot-card{ margin-bottom:12px; padding:20px; border:1px solid var(--border); border-radius:24px; background:var(--surface); box-shadow:0 1px 2px rgba(0,0,0,.04); }
    #rmbz-vip .shoot-head{ display:flex; align-items:center; gap:12px; margin-bottom:16px; }
    #rmbz-vip .shoot-head-icon{ width:44px; height:44px; flex:0 0 44px; border-radius:14px; display:flex; align-items:center; justify-content:center; background:var(--brand-soft); color:var(--brand-ink); }
    #rmbz-vip .shoot-head-icon .ms{ font-size:23px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .shoot-head-copy{ flex:1; min-width:0; }
    #rmbz-vip .shoot-eyebrow{ color:var(--muted); font-size:10px; line-height:1.2; font-weight:750; letter-spacing:.09em; text-transform:uppercase; }
    #rmbz-vip .shoot-title{ margin-top:3px; color:var(--text); font-size:15px; line-height:1.25; font-weight:750; }
    #rmbz-vip .shoot-badge{ display:inline-flex; align-items:center; gap:6px; min-height:31px; padding:6px 11px; border-radius:100px; background:var(--rev-soft); color:var(--rev); font-size:11px; font-weight:750; white-space:nowrap; }
    #rmbz-vip .shoot-badge.success{ background:var(--success-soft); color:var(--success); }
    #rmbz-vip .shoot-badge .ms{ font-size:16px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .shoot-dates{ display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px; }
    #rmbz-vip .shoot-date{ display:flex; align-items:center; gap:12px; min-height:72px; padding:13px 15px; border:1px solid var(--border); border-radius:17px; background:var(--elev); }
    #rmbz-vip .shoot-date>.ms{ width:34px; height:34px; flex:0 0 34px; border-radius:11px; align-items:center; justify-content:center; background:var(--surface); color:var(--brand-ink); font-size:19px; }
    #rmbz-vip .shoot-date-label{ color:var(--muted); font-size:10px; font-weight:750; letter-spacing:.07em; text-transform:uppercase; }
    #rmbz-vip .shoot-date-value{ margin-top:3px; color:var(--text); font-size:17px; line-height:1.2; font-weight:750; }
    #rmbz-vip .shoot-notice{ display:flex; align-items:flex-start; gap:10px; margin-top:12px; padding:12px 14px; border-radius:15px; background:var(--success-soft); color:var(--success); }
    #rmbz-vip .shoot-notice.pending{ background:var(--rev-soft); color:var(--rev); }
    #rmbz-vip .shoot-notice>.ms{ margin-top:1px; font-size:19px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .shoot-notice strong{ display:block; font-size:12.5px; line-height:1.3; }
    #rmbz-vip .shoot-notice small{ display:block; margin-top:2px; color:var(--text2); font-size:11.5px; line-height:1.4; }
    #rmbz-vip .shoot-complete-card{ position:relative; overflow:hidden; display:flex; align-items:center; gap:17px; margin-bottom:12px; padding:21px; border:1px solid color-mix(in srgb,var(--success) 30%,var(--border)); border-radius:24px; background:linear-gradient(135deg,var(--success-soft),var(--surface) 58%); box-shadow:0 1px 2px rgba(0,0,0,.04); }
    #rmbz-vip .shoot-complete-icon{ position:relative; width:58px; height:58px; flex:0 0 58px; align-items:center; justify-content:center; border-radius:19px; background:var(--success); color:#fff; font-size:29px; font-variation-settings:'FILL' 1; box-shadow:0 10px 24px -16px var(--success); }
    #rmbz-vip .shoot-complete-copy{ position:relative; flex:1; min-width:0; }
    #rmbz-vip .shoot-complete-kicker{ color:var(--success); font-size:10px; line-height:1.2; font-weight:800; letter-spacing:.09em; text-transform:uppercase; }
    #rmbz-vip .shoot-complete-title{ margin-top:4px; color:var(--text); font-family:'Bricolage Grotesque',sans-serif; font-size:18px; line-height:1.3; font-weight:780; }
    #rmbz-vip .shoot-complete-text{ margin-top:5px; color:var(--text2); font-size:12px; line-height:1.55; }
    #rmbz-vip .shoot-complete-meta{ display:flex; align-items:center; gap:7px; flex-wrap:wrap; margin-top:11px; }
    #rmbz-vip .shoot-complete-chip{ display:inline-flex; align-items:center; gap:5px; min-height:29px; padding:5px 9px; border-radius:100px; background:var(--surface); color:var(--text2); font-size:10.5px; font-weight:700; }
    #rmbz-vip .shoot-complete-chip .ms{ color:var(--success); font-size:15px; }
    #rmbz-vip .shoot-actions{ display:flex; gap:9px; flex-wrap:wrap; margin-top:12px; }
    #rmbz-vip .shoot-form{ display:none; margin-top:12px; padding:15px; border:1px solid var(--border); border-radius:17px; background:var(--elev); }
    #rmbz-vip .location-card{ margin-bottom:12px; padding:20px; border:1px solid var(--border); border-radius:24px; background:var(--surface); box-shadow:0 1px 2px rgba(0,0,0,.04); }
    #rmbz-vip .location-head{ display:flex; align-items:center; gap:13px; margin-bottom:16px; }
    #rmbz-vip .location-head-icon{ width:46px; height:46px; flex:0 0 46px; border-radius:15px; display:flex; align-items:center; justify-content:center; background:var(--brand-soft); color:var(--brand-ink); }
    #rmbz-vip .location-head-icon .ms{ font-size:24px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .location-head-copy{ flex:1; min-width:0; }
    #rmbz-vip .location-title{ color:var(--text); font-size:15px; line-height:1.25; font-weight:780; }
    #rmbz-vip .location-subtitle{ margin-top:3px; color:var(--text2); font-size:12px; line-height:1.45; }
    #rmbz-vip .location-alert{ display:inline-flex; align-items:center; gap:6px; min-height:31px; padding:6px 11px; border-radius:100px; background:var(--rev-soft); color:var(--rev); font-size:11px; font-weight:750; white-space:nowrap; }
    #rmbz-vip .location-alert .ms{ font-size:16px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .location-options{ display:grid; grid-template-columns:repeat(auto-fit,minmax(300px,1fr)); gap:12px; }
    #rmbz-vip .location-option{ display:flex; flex-direction:column; min-width:0; padding:16px; border:1.5px solid var(--border); border-radius:20px; background:var(--elev); transition:border-color .16s ease,background .16s ease,transform .16s ease; }
    #rmbz-vip .location-option:hover{ border-color:var(--brand); background:var(--hover); transform:translateY(-1px); }
    #rmbz-vip .location-option-head{ display:flex; align-items:center; gap:11px; }
    #rmbz-vip .location-pin{ width:38px; height:38px; flex:0 0 38px; border-radius:12px; align-items:center; justify-content:center; background:var(--surface); color:var(--brand-ink); font-size:20px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .location-option-label{ color:var(--muted); font-size:9.5px; line-height:1.2; font-weight:750; letter-spacing:.08em; text-transform:uppercase; }
    #rmbz-vip .location-option-name{ margin-top:2px; color:var(--text); font-size:15px; line-height:1.25; font-weight:780; }
    #rmbz-vip .location-items{ margin:13px 0; padding:10px 12px; border:1px solid var(--border); border-radius:14px; background:var(--surface); }
    #rmbz-vip .location-item{ display:flex; align-items:flex-start; justify-content:space-between; gap:16px; padding:7px 0; color:var(--text2); font-size:11.5px; line-height:1.4; }
    #rmbz-vip .location-item+.location-item{ border-top:1px solid var(--border); }
    #rmbz-vip .location-item .mono{ flex:0 0 auto; color:var(--text); font-size:11px; font-weight:650; }
    #rmbz-vip .location-total{ display:flex; align-items:flex-end; justify-content:space-between; gap:16px; margin-top:auto; padding:2px 2px 13px; }
    #rmbz-vip .location-total-label{ color:var(--muted); font-size:10.5px; font-weight:650; }
    #rmbz-vip .location-total-value{ color:var(--text); font-family:'JetBrains Mono',monospace; font-size:19px; line-height:1; font-weight:700; white-space:nowrap; }
    #rmbz-vip .location-total-value small{ color:var(--muted); font-family:'Geist',system-ui,sans-serif; font-size:10px; font-weight:700; }
    #rmbz-vip .location-select{ width:100%; min-height:44px; justify-content:center; background:var(--brand); color:var(--on-brand); font-size:12.5px; transition:filter .15s ease,transform .15s ease; }
    #rmbz-vip .location-select:hover{ filter:brightness(.97); transform:translateY(-1px); }
    #rmbz-vip .project-card{ padding:22px; border-radius:28px; }
    #rmbz-vip .project-accordion-toggle{ width:100%; padding:0; border:0; background:transparent; color:inherit; font:inherit; text-align:left; cursor:pointer; }
    #rmbz-vip .project-accordion-toggle:focus-visible{ outline:3px solid var(--brand-soft); outline-offset:7px; border-radius:15px; }
    #rmbz-vip .project-accordion-toggle .project-top{ width:100%; }
    #rmbz-vip .project-heading{ display:block; min-width:0; }
    #rmbz-vip .project-kicker,#rmbz-vip .project-name{ display:block; }
    #rmbz-vip .project-header-side{ display:flex; align-items:flex-start; justify-content:flex-end; gap:10px; margin-left:auto; }
    #rmbz-vip .project-accordion-chevron{ width:36px; height:36px; flex:0 0 36px; display:inline-flex; align-items:center; justify-content:center; border-radius:50%; background:var(--elev); color:var(--text2); transition:transform .2s ease,background .2s ease; }
    #rmbz-vip .project-accordion-chevron .ms{ font-size:21px; }
    #rmbz-vip .project-card.is-open .project-accordion-chevron{ transform:rotate(180deg); background:var(--brand-soft); color:var(--brand-ink); }
    #rmbz-vip .project-card:not(.is-open) .project-accordion-toggle:hover .project-accordion-chevron{ background:var(--hover); }
    #rmbz-vip .project-accordion-body[hidden]{ display:none !important; }
    #rmbz-vip .project-empty{ min-height:250px; display:flex; flex-direction:column; align-items:center; justify-content:center; text-align:center; }
    #rmbz-vip .project-empty-icon{ width:64px; height:64px; border-radius:20px; align-items:center; justify-content:center; background:var(--brand-soft); color:var(--brand-ink); font-size:31px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .project-top{ display:flex; justify-content:space-between; align-items:flex-start; gap:16px; flex-wrap:wrap; }
    #rmbz-vip .project-kicker{ color:var(--muted); font-size:10px; font-weight:750; letter-spacing:.09em; text-transform:uppercase; }
    #rmbz-vip .project-name{ margin-top:3px; color:var(--text); font-family:'Bricolage Grotesque',sans-serif; font-size:21px; line-height:1.25; font-weight:750; }
    #rmbz-vip .project-meta{ display:flex; align-items:center; gap:7px; flex-wrap:wrap; margin-top:5px; color:var(--muted); font-size:11.5px; }
    #rmbz-vip .project-meta .ms{ font-size:15px; }
    #rmbz-vip .project-badges{ display:flex; align-items:center; justify-content:flex-end; gap:7px; flex-wrap:wrap; }
    #rmbz-vip .project-stage-panel{ --stage-color:var(--brand-ink); --stage-soft:var(--brand-soft); margin:17px 0 14px; padding:18px; overflow:hidden; border:1px solid color-mix(in srgb,var(--stage-color) 25%,var(--border)); border-radius:22px; background:linear-gradient(135deg,var(--stage-soft),var(--surface) 54%); box-shadow:0 8px 30px -28px rgba(0,0,0,.7); }
    #rmbz-vip .project-stage-panel.tone-info{ --stage-color:var(--info); --stage-soft:var(--info-soft); }
    #rmbz-vip .project-stage-panel.tone-warning{ --stage-color:var(--rev); --stage-soft:var(--rev-soft); }
    #rmbz-vip .project-stage-panel.tone-success{ --stage-color:var(--success); --stage-soft:var(--success-soft); }
    #rmbz-vip .project-stage-panel.tone-danger{ --stage-color:var(--danger); --stage-soft:var(--danger-soft); }
    #rmbz-vip .project-stage-panel.tone-neutral{ --stage-color:var(--text2); --stage-soft:var(--elev); }
    #rmbz-vip .project-stage-head{ display:flex; align-items:center; gap:13px; }
    #rmbz-vip .project-stage-icon{ width:48px; height:48px; flex:0 0 48px; align-items:center; justify-content:center; border-radius:16px; background:var(--stage-color); color:#fff; font-size:24px; font-variation-settings:'FILL' 1; box-shadow:0 10px 24px -18px var(--stage-color); }
    #rmbz-vip .project-stage-copy{ flex:1; min-width:0; }
    #rmbz-vip .project-stage-kicker{ color:var(--stage-color); font-size:9.5px; line-height:1.2; font-weight:800; letter-spacing:.09em; text-transform:uppercase; }
    #rmbz-vip .project-stage-title{ margin-top:3px; color:var(--text); font-family:'Bricolage Grotesque',sans-serif; font-size:18px; line-height:1.25; font-weight:780; }
    #rmbz-vip .project-stage-description{ margin-top:3px; color:var(--text2); font-size:11.5px; line-height:1.5; }
    #rmbz-vip .project-stage-percent{ min-width:58px; padding:8px 10px; border-radius:14px; background:var(--surface); color:var(--stage-color); font-family:'JetBrains Mono',monospace; font-size:13px; line-height:1; font-weight:750; text-align:center; }
    #rmbz-vip .project-stage-track{ position:relative; display:grid; grid-template-columns:repeat(5,minmax(0,1fr)); margin-top:18px; }
    #rmbz-vip .project-stage-rail{ position:absolute; z-index:0; top:14px; left:10%; right:10%; height:3px; overflow:hidden; border-radius:100px; background:var(--border2); }
    #rmbz-vip .project-stage-rail span{ display:block; width:var(--stage-progress); height:100%; border-radius:inherit; background:var(--stage-color); transition:width .35s ease; }
    #rmbz-vip .project-stage-step{ position:relative; z-index:1; display:flex; flex-direction:column; align-items:center; min-width:0; color:var(--muted); }
    #rmbz-vip .project-stage-dot{ width:30px; height:30px; align-items:center; justify-content:center; border:2px solid var(--border2); border-radius:50%; background:var(--surface); color:var(--muted); font-size:15px; }
    #rmbz-vip .project-stage-step.is-complete .project-stage-dot{ border-color:var(--success); background:var(--success); color:#fff; }
    #rmbz-vip .project-stage-step.is-active .project-stage-dot{ border-color:var(--stage-color); background:var(--stage-color); color:#fff; box-shadow:0 0 0 5px var(--stage-soft); font-variation-settings:'FILL' 1; }
    #rmbz-vip .project-stage-step-label{ max-width:100%; margin-top:7px; overflow:hidden; font-size:9.5px; line-height:1.25; font-weight:700; text-align:center; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .project-stage-step.is-complete .project-stage-step-label{ color:var(--text2); }
    #rmbz-vip .project-stage-step.is-active .project-stage-step-label{ color:var(--stage-color); font-weight:800; }
    #rmbz-vip .project-state{ display:flex; align-items:flex-start; gap:13px; margin-bottom:12px; padding:15px 16px; border:1px solid transparent; border-radius:20px; background:var(--elev); }
    #rmbz-vip .project-state.neutral{ border-color:var(--border); }
    #rmbz-vip .project-state.info{ background:var(--info-soft); }
    #rmbz-vip .project-state.success{ background:var(--success-soft); }
    #rmbz-vip .project-state.warning{ background:var(--rev-soft); }
    #rmbz-vip .project-state.danger{ background:var(--danger-soft); }
    #rmbz-vip .project-state-icon{ width:40px; height:40px; flex:0 0 40px; border-radius:13px; align-items:center; justify-content:center; background:var(--surface); color:var(--text2); font-size:21px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .project-state.info .project-state-icon,#rmbz-vip .project-state.info .project-state-title{ color:var(--info); }
    #rmbz-vip .project-state.success .project-state-icon,#rmbz-vip .project-state.success .project-state-title{ color:var(--success); }
    #rmbz-vip .project-state.warning .project-state-icon,#rmbz-vip .project-state.warning .project-state-title{ color:var(--rev); }
    #rmbz-vip .project-state.danger .project-state-icon,#rmbz-vip .project-state.danger .project-state-title{ color:var(--danger); }
    #rmbz-vip .project-state-body{ flex:1; min-width:0; }
    #rmbz-vip .project-state-title{ color:var(--text); font-size:13px; line-height:1.35; font-weight:750; }
    #rmbz-vip .project-state-text{ margin-top:3px; color:var(--text2); font-size:12px; line-height:1.55; }
    #rmbz-vip .project-state-facts{ display:flex; align-items:center; gap:8px 14px; flex-wrap:wrap; margin-top:8px; color:var(--text2); font-size:11.5px; }
    #rmbz-vip .project-state-facts span{ display:inline-flex; align-items:center; gap:5px; }
    #rmbz-vip .project-state-facts .ms{ color:var(--muted); font-size:16px; }
    #rmbz-vip .project-actions{ display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin-top:11px; }
    #rmbz-vip .project-btn{ min-height:40px; padding:9px 16px; font-size:12px; text-decoration:none; }
    #rmbz-vip .project-btn .ms{ font-size:18px; }
    #rmbz-vip .project-btn.filled{ background:var(--brand); color:var(--on-brand); }
    #rmbz-vip .project-btn.success{ background:var(--success); color:#fff; }
    #rmbz-vip .project-btn.danger{ background:var(--danger); color:#fff; }
    #rmbz-vip .project-btn.tonal{ background:var(--brand-soft); color:var(--brand-ink); }
    #rmbz-vip .project-btn.outlined{ border:1px solid var(--border2); background:transparent; color:var(--text2); }
    #rmbz-vip .project-section-card{ margin-bottom:12px; padding:17px; border:1px solid var(--border); border-radius:21px; background:var(--elev); }
    #rmbz-vip .project-section-head{ display:flex; align-items:center; gap:10px; margin-bottom:12px; }
    #rmbz-vip .project-section-icon{ width:36px; height:36px; flex:0 0 36px; border-radius:12px; align-items:center; justify-content:center; background:var(--surface); color:var(--brand-ink); font-size:19px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .project-section-title{ color:var(--text); font-size:13px; line-height:1.3; font-weight:750; }
    #rmbz-vip .project-section-subtitle{ margin-top:2px; color:var(--muted); font-size:11px; line-height:1.4; }
    #rmbz-vip .project-team-card{ background:var(--surface); }
    #rmbz-vip .project-team-count{ margin-left:auto; display:inline-flex; align-items:center; min-height:28px; padding:5px 10px; border-radius:100px; background:var(--brand-soft); color:var(--brand-ink); font-size:10.5px; font-weight:750; white-space:nowrap; }
    #rmbz-vip .project-team-grid{ display:grid; grid-template-columns:repeat(auto-fit,minmax(230px,1fr)); gap:9px; }
    #rmbz-vip .project-team-member{ display:flex; align-items:flex-start; gap:11px; min-width:0; padding:12px; border:1px solid var(--border); border-radius:17px; background:var(--elev); }
    #rmbz-vip .project-team-avatar{ width:44px; height:44px; flex:0 0 44px; overflow:hidden; display:flex; align-items:center; justify-content:center; border-radius:14px; background:var(--brand-soft); color:var(--brand-ink); font-size:16px; font-weight:800; }
    #rmbz-vip .project-team-avatar img{ width:100%; height:100%; object-fit:cover; }
    #rmbz-vip .project-team-copy{ min-width:0; flex:1; }
    #rmbz-vip .project-team-name-row{ display:flex; align-items:center; gap:7px; min-width:0; flex-wrap:wrap; }
    #rmbz-vip .project-team-name{ overflow:hidden; color:var(--text); font-size:12.5px; line-height:1.35; font-weight:780; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .project-team-origin{ display:inline-flex; align-items:center; gap:3px; padding:3px 6px; border:1px solid var(--border2); border-radius:100px; color:var(--muted); font-size:8.5px; font-weight:800; letter-spacing:.05em; text-transform:uppercase; }
    #rmbz-vip .project-team-origin .ms{ font-size:11px; }
    #rmbz-vip .project-team-roles{ display:flex; gap:5px; flex-wrap:wrap; margin-top:8px; }
    #rmbz-vip .project-team-role{ display:inline-flex; align-items:center; min-height:24px; padding:4px 8px; border-radius:8px; background:var(--brand-soft); color:var(--brand-ink); font-size:9.5px; line-height:1.2; font-weight:700; }
    #rmbz-vip .project-card.is-filming-live .project-accordion-chevron{ transform:none; background:var(--danger-soft); color:var(--danger); }
    #rmbz-vip .project-card.is-filming-live .project-accordion-toggle{ cursor:default; }
    #rmbz-vip .project-filming-lock{ position:relative; min-height:410px; overflow:hidden; display:flex; flex-direction:column; align-items:center; justify-content:center; margin-top:17px; padding:38px 22px; border:1px solid color-mix(in srgb,var(--danger) 34%,var(--border)); border-radius:24px; background:radial-gradient(circle at 50% 12%,color-mix(in srgb,var(--danger) 18%,transparent),transparent 34%),linear-gradient(155deg,#171417,#0d0c0e); color:#fff; text-align:center; box-shadow:0 18px 42px -30px rgba(0,0,0,.85); }
    #rmbz-vip .project-filming-lock::before{ content:''; position:absolute; inset:0; pointer-events:none; background:linear-gradient(115deg,transparent 20%,rgba(255,255,255,.035) 48%,transparent 70%); }
    #rmbz-vip .project-filming-live-badge{ position:relative; display:inline-flex; align-items:center; gap:8px; min-height:30px; padding:6px 11px; border-radius:100px; background:rgba(229,72,77,.16); color:#ffaaa8; font-size:10px; font-weight:800; letter-spacing:.08em; text-transform:uppercase; }
    #rmbz-vip .project-filming-live-dot{ width:8px; height:8px; border-radius:50%; background:#ff5b57; box-shadow:0 0 0 5px rgba(255,91,87,.13); animation:rmbzVipRec 1.25s ease-in-out infinite; }
    #rmbz-vip .project-filming-live-icon{ position:relative; width:62px; height:62px; display:flex; align-items:center; justify-content:center; margin:20px 0 13px; border-radius:21px; background:rgba(255,255,255,.09); color:#fff; }
    #rmbz-vip .project-filming-live-icon .ms{ font-size:31px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .project-filming-live-title{ position:relative; margin:0; color:#fff; font-family:'Bricolage Grotesque',sans-serif; font-size:clamp(20px,3vw,29px); line-height:1.2; font-weight:780; }
    #rmbz-vip .project-filming-clock{ position:relative; margin:14px 0 12px; color:#fff; font-family:'JetBrains Mono',monospace; font-size:clamp(38px,7vw,66px); line-height:1; font-weight:650; letter-spacing:.05em; font-variant-numeric:tabular-nums; text-shadow:0 0 28px rgba(255,255,255,.12); }
    #rmbz-vip .project-filming-live-copy{ position:relative; max-width:560px; margin:0; color:#bdb6bf; font-size:12.5px; line-height:1.65; }
    #rmbz-vip .project-filming-live-foot{ position:relative; display:flex; align-items:center; gap:7px; margin-top:18px; color:#e4dfe5; font-size:10.5px; font-weight:700; }
    #rmbz-vip .project-filming-live-foot .ms{ color:#ffaaa8; font-size:16px; }
    @keyframes rmbzVipRec{ 0%,100%{ opacity:1; transform:scale(1); } 50%{ opacity:.42; transform:scale(.82); } }
    #rmbz-vip .project-filming-history{ background:var(--surface); }
    #rmbz-vip .project-filming-summary{ margin-left:auto; display:inline-flex; align-items:center; gap:6px; min-height:28px; padding:5px 10px; border-radius:100px; background:var(--success-soft); color:var(--success); font-size:10px; font-weight:780; white-space:nowrap; }
    #rmbz-vip .project-filming-days{ display:flex; flex-direction:column; gap:8px; }
    #rmbz-vip .project-filming-day{ overflow:hidden; border:1px solid var(--border); border-radius:17px; background:var(--elev); }
    #rmbz-vip .project-filming-day>summary{ list-style:none; display:flex; align-items:center; gap:11px; min-height:68px; padding:11px 13px; cursor:pointer; }
    #rmbz-vip .project-filming-day>summary::-webkit-details-marker{ display:none; }
    #rmbz-vip .project-filming-day-number{ width:40px; height:40px; flex:0 0 40px; display:flex; align-items:center; justify-content:center; border-radius:13px; background:var(--brand-soft); color:var(--brand-ink); font-family:'JetBrains Mono',monospace; font-size:11px; font-weight:800; }
    #rmbz-vip .project-filming-day-copy{ flex:1; min-width:0; }
    #rmbz-vip .project-filming-day-title{ color:var(--text); font-size:12px; line-height:1.35; font-weight:780; }
    #rmbz-vip .project-filming-day-meta{ display:flex; align-items:center; gap:6px; flex-wrap:wrap; margin-top:3px; color:var(--muted); font-size:10px; }
    #rmbz-vip .project-filming-day-meta .ms{ font-size:14px; }
    #rmbz-vip .project-filming-result{ display:inline-flex; align-items:center; gap:5px; min-height:27px; padding:5px 9px; border-radius:100px; background:var(--success-soft); color:var(--success); font-size:9.5px; font-weight:780; }
    #rmbz-vip .project-filming-result.continue{ background:var(--rev-soft); color:var(--rev); }
    #rmbz-vip .project-filming-result .ms{ font-size:14px; }
    #rmbz-vip .project-filming-expand{ color:var(--muted); font-size:20px; transition:transform .18s ease; }
    #rmbz-vip .project-filming-day[open] .project-filming-expand{ transform:rotate(180deg); }
    #rmbz-vip .project-filming-day-body{ padding:0 13px 13px 64px; }
    #rmbz-vip .project-filming-group+.project-filming-group{ margin-top:11px; }
    #rmbz-vip .project-filming-group-head{ display:flex; align-items:center; gap:6px; margin-bottom:7px; color:var(--text2); font-size:10.5px; font-weight:760; }
    #rmbz-vip .project-filming-group-head .ms{ color:var(--brand-ink); font-size:16px; }
    #rmbz-vip .project-filming-people{ display:flex; gap:7px; flex-wrap:wrap; }
    #rmbz-vip .project-filming-person{ display:inline-flex; align-items:center; gap:8px; max-width:100%; min-height:42px; padding:4px 10px 4px 4px; border:1px solid var(--border); border-radius:100px; background:var(--surface); }
    #rmbz-vip .project-filming-person-photo{ width:34px; height:34px; flex:0 0 34px; overflow:hidden; display:flex; align-items:center; justify-content:center; border-radius:50%; background:var(--brand-soft); color:var(--brand-ink); font-size:11px; font-weight:800; }
    #rmbz-vip .project-filming-person-photo img{ width:100%; height:100%; object-fit:cover; }
    #rmbz-vip .project-filming-person-copy{ min-width:0; text-align:left; }
    #rmbz-vip .project-filming-person-name{ display:block; overflow:hidden; max-width:180px; color:var(--text); font-size:10.5px; line-height:1.25; font-weight:750; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .project-filming-person-role{ display:block; overflow:hidden; max-width:180px; margin-top:1px; color:var(--muted); font-size:9px; line-height:1.2; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .project-filming-empty{ padding:10px 0 2px; color:var(--muted); font-size:10.5px; }
    #rmbz-vip .project-choice{ display:flex; align-items:center; gap:8px; min-height:38px; padding:8px 11px; border:1px solid var(--border); border-radius:12px; background:var(--surface); color:var(--text2); font-size:11.5px; font-weight:650; cursor:pointer; }
    #rmbz-vip .project-choice:has(input:checked){ border-color:var(--brand); background:var(--brand-soft); color:var(--brand-ink); }
    #rmbz-vip .project-choice input{ width:17px; height:17px; margin:0; accent-color:var(--brand); }
    #rmbz-vip .project-decision-row{ display:flex; align-items:center; gap:10px; padding:11px 0; border-top:1px solid var(--border); flex-wrap:wrap; }
    #rmbz-vip .project-decision-row:first-of-type{ border-top:0; }
    #rmbz-vip .project-decision-name{ flex:1; min-width:190px; color:var(--text2); font-size:12px; line-height:1.45; }
    #rmbz-vip .project-decision-name .mono{ color:var(--text); font-size:11px; font-weight:650; }
    #rmbz-vip .project-metrics{ display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:9px; }
    #rmbz-vip .project-metric{ min-width:0; padding:12px 13px; border:1px solid var(--border); border-radius:15px; background:var(--surface); }
    #rmbz-vip .project-metric-label{ color:var(--muted); font-size:9.5px; font-weight:750; letter-spacing:.07em; text-transform:uppercase; }
    #rmbz-vip .project-metric-value{ margin-top:5px; color:var(--text); font-family:'JetBrains Mono',monospace; font-size:16px; line-height:1.2; font-weight:700; white-space:nowrap; }
    #rmbz-vip .project-metric.success .project-metric-value{ color:var(--success); }
    #rmbz-vip .project-metric.danger .project-metric-value{ color:var(--danger); }
    #rmbz-vip .project-checklist{ margin-top:12px; padding-top:11px; border-top:1px solid var(--border); }
    #rmbz-vip .project-check-row{ display:flex; align-items:center; gap:8px; padding:7px 0; color:var(--text2); font-size:11.5px; }
    #rmbz-vip .project-check-row>.ms{ color:var(--muted); font-size:18px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .project-check-row.done>.ms{ color:var(--success); }
    #rmbz-vip .project-check-row .mono{ margin-left:auto; color:var(--text); font-size:11px; }
    #rmbz-vip .project-modal-head{ display:flex; align-items:center; gap:11px; margin-bottom:12px; }
    #rmbz-vip .project-modal-icon{ width:40px; height:40px; flex:0 0 40px; border-radius:13px; align-items:center; justify-content:center; background:var(--brand-soft); color:var(--brand-ink); font-size:21px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .project-subform{ display:none; margin-top:14px; padding:16px; border:1px solid var(--border2); border-radius:17px; background:var(--surface); }
    #rmbz-vip .project-icon-btn{ width:38px; height:38px; flex:0 0 38px; border:0; border-radius:50%; display:inline-flex; align-items:center; justify-content:center; background:transparent; color:var(--muted); cursor:pointer; }
    #rmbz-vip .project-icon-btn:hover{ background:var(--hover); color:var(--text); }
    #rmbz-vip .project-doc-empty{ height:100%; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:12px; padding:24px; text-align:center; }
    #rmbz-vip .project-doc-empty>.ms{ width:56px; height:56px; border-radius:18px; align-items:center; justify-content:center; background:var(--brand-soft); color:var(--brand-ink); font-size:28px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .project-complete-head{ display:flex; align-items:center; gap:9px; margin:26px 0 12px; color:var(--text); font-size:13px; font-weight:750; }
    #rmbz-vip .project-complete-head .ms{ width:30px; height:30px; border-radius:10px; align-items:center; justify-content:center; background:var(--success-soft); color:var(--success); font-size:17px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .project-complete-card{ display:flex; align-items:center; gap:14px; flex-wrap:wrap; padding:17px 18px; border-radius:20px; }
    #rmbz-vip .project-chat-list{ max-height:320px; overflow-y:auto; display:flex; flex-direction:column; gap:9px; padding:5px 3px 9px; margin-bottom:10px; }
    #rmbz-vip .project-chat-message{ max-width:78%; padding:10px 13px; border:1px solid var(--border); color:var(--text2); }
    #rmbz-vip .project-chat-message.team{ align-self:flex-start; border-radius:5px 16px 16px 16px; background:var(--surface); }
    #rmbz-vip .project-chat-message.artist{ align-self:flex-end; border-color:transparent; border-radius:16px 5px 16px 16px; background:var(--brand-soft); }
    #rmbz-vip .project-chat-sender{ color:var(--muted); font-size:9.5px; font-weight:750; letter-spacing:.06em; text-transform:uppercase; }
    #rmbz-vip .project-chat-message.team .project-chat-sender{ color:var(--brand-ink); }
    #rmbz-vip .project-chat-text{ margin-top:4px; font-size:12.5px; line-height:1.5; word-break:break-word; }
    #rmbz-vip .project-chat-message-actions{ display:flex; justify-content:flex-end; margin-top:6px; padding-top:5px; border-top:1px solid color-mix(in srgb,var(--border2) 70%,transparent); }
    #rmbz-vip .project-chat-delete{ display:inline-flex; align-items:center; gap:4px; padding:3px 6px; border:0; border-radius:8px; background:transparent; color:var(--muted); font-family:inherit; font-size:9.5px; font-weight:700; cursor:pointer; }
    #rmbz-vip .project-chat-delete:hover{ background:var(--danger-soft); color:var(--danger); }
    #rmbz-vip .project-chat-delete:disabled{ opacity:.45; cursor:wait; }
    #rmbz-vip .project-chat-delete .ms{ font-size:14px; }
    #rmbz-vip .project-chat-event{ align-self:center; width:min(92%,560px); display:flex; align-items:center; gap:10px; padding:9px 12px; border:1px solid var(--border); border-radius:15px; background:var(--surface); }
    #rmbz-vip .project-chat-event>.ms{ width:34px; height:34px; flex:0 0 34px; border-radius:11px; align-items:center; justify-content:center; background:var(--success-soft); color:var(--success); font-size:18px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .project-chat-event.proposal>.ms{ background:var(--brand-soft); color:var(--brand-ink); }
    #rmbz-vip .project-chat-event-title{ color:var(--text); font-size:11.5px; line-height:1.35; font-weight:750; }
    #rmbz-vip .project-chat-event-meta{ margin-top:2px; color:var(--muted); font-size:10px; line-height:1.4; }
    #rmbz-vip .project-chat-live{ display:inline-flex; align-items:center; gap:6px; padding:5px 9px; border-radius:100px; background:var(--success-soft); color:var(--success); font-size:9.5px; font-weight:750; text-transform:uppercase; letter-spacing:.05em; }
    #rmbz-vip .project-chat-live::before{ content:''; width:6px; height:6px; border-radius:50%; background:currentColor; box-shadow:0 0 0 3px rgba(16,185,129,.13); }
    #rmbz-vip .project-chat-live.offline{ background:var(--danger-soft); color:var(--danger); }
    #rmbz-vip .project-chat-live.offline::before{ box-shadow:none; }
    #rmbz-vip .project-chat-unread{ display:inline-flex; min-width:22px; height:22px; padding:0 6px; align-items:center; justify-content:center; border-radius:100px; background:var(--danger); color:#fff; font-size:10px; font-weight:800; line-height:1; box-shadow:0 0 0 3px var(--danger-soft); }
    #rmbz-vip .project-chat-unread[hidden]{ display:none; }
    #rmbz-vip .project-chat-empty{ padding:22px 12px; color:var(--muted); font-size:11.5px; text-align:center; }
    #rmbz-vip .project-chat-feedback{ display:none; flex:0 0 100%; padding:2px 4px 0; color:var(--muted); font-size:10.5px; }
    #rmbz-vip .project-chat-feedback.show{ display:block; }
    #rmbz-vip .project-chat-feedback.error{ color:var(--danger); }
    #rmbz-vip .project-chat-message.sending{ opacity:.6; }
    #rmbz-vip .project-chat-attachment{ display:inline-flex; align-items:center; gap:6px; max-width:240px; margin-top:7px; padding:7px 10px; border:1px solid var(--border2); border-radius:11px; color:var(--text2); font-size:11px; text-decoration:none; }
    #rmbz-vip .project-chat-attachment .ms{ font-size:16px; }
    #rmbz-vip .project-chat-image-preview{ position:relative; display:block; width:min(270px,100%); margin-top:8px; padding:0; overflow:hidden; border:1px solid var(--border2); border-radius:15px; background:var(--elev); color:var(--text2); cursor:zoom-in; font-family:inherit; text-align:left; }
    #rmbz-vip .project-chat-image-frame{ position:relative; display:flex; min-height:120px; max-height:230px; align-items:center; justify-content:center; overflow:hidden; background:var(--hover); }
    #rmbz-vip .project-chat-image-frame img{ display:block; width:100%; height:auto; min-height:120px; max-height:230px; object-fit:cover; transition:transform .2s ease; }
    #rmbz-vip .project-chat-image-preview:hover .project-chat-image-frame img{ transform:scale(1.025); }
    #rmbz-vip .project-chat-image-zoom{ position:absolute; right:9px; bottom:9px; width:34px; height:34px; align-items:center; justify-content:center; border-radius:11px; background:rgba(17,17,17,.72); color:#fff; font-size:19px; backdrop-filter:blur(8px); }
    #rmbz-vip .project-chat-image-caption{ display:flex; align-items:center; gap:7px; min-width:0; padding:9px 11px; color:var(--text2); font-size:10.5px; }
    #rmbz-vip .project-chat-image-caption .ms{ flex:0 0 auto; color:var(--brand-ink); font-size:16px; }
    #rmbz-vip .project-chat-image-caption span:last-child{ overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .project-chat-image-preview.broken{ cursor:pointer; }
    #rmbz-vip .project-chat-image-preview.broken .project-chat-image-frame{ min-height:110px; flex-direction:column; gap:7px; color:var(--muted); font-size:10.5px; }
    #rmbz-vip .project-chat-image-preview.broken .project-chat-image-frame>.ms{ font-size:30px; }
    #rmbz-vip .project-chat-image-dialog{ width:min(1040px,96vw); max-height:94vh; overflow:hidden; padding:16px; }
    #rmbz-vip .project-chat-image-head{ display:flex; align-items:center; gap:11px; min-height:46px; padding:0 2px 13px; }
    #rmbz-vip .project-chat-image-head-icon{ width:40px; height:40px; flex:0 0 40px; align-items:center; justify-content:center; border-radius:13px; background:var(--brand-soft); color:var(--brand-ink); font-size:21px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .project-chat-image-title{ overflow:hidden; color:var(--text); font-size:13px; font-weight:800; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .project-chat-image-subtitle{ margin-top:2px; color:var(--muted); font-size:10.5px; }
    #rmbz-vip .project-chat-image-stage{ position:relative; display:flex; height:min(76vh,820px); min-height:260px; align-items:center; justify-content:center; overflow:hidden; border-radius:20px; background:#0d0d0f; }
    #rmbz-vip .project-chat-image-stage>img{ display:block; width:100%; height:100%; object-fit:contain; }
    #rmbz-vip .project-chat-image-stage>img[hidden]{ display:none; }
    #rmbz-vip .project-chat-image-loading,#rmbz-vip .project-chat-image-error{ display:flex; flex-direction:column; align-items:center; gap:8px; color:#d7d7dc; font-size:11.5px; text-align:center; }
    #rmbz-vip .project-chat-image-loading>.ms{ font-size:30px; animation:rmbzChatSpin 1s linear infinite; }
    #rmbz-vip .project-chat-image-error>.ms{ color:#f87171; font-size:36px; }
    #rmbz-vip .project-chat-image-error>span:last-child{ color:#9a9aa2; }
    #rmbz-vip .project-chat-image-error[hidden],#rmbz-vip .project-chat-image-loading[hidden]{ display:none; }
    @keyframes rmbzChatSpin{ to{ transform:rotate(360deg); } }
    @media(max-width:640px){ #rmbz-vip .project-chat-image-dialog{ width:100%; max-height:96vh; padding:10px; border-radius:22px; } #rmbz-vip .project-chat-image-stage{ height:72vh; border-radius:16px; } #rmbz-vip .project-chat-image-original{ width:40px; height:40px; min-width:40px; padding:0; font-size:0; } #rmbz-vip .project-chat-image-original .ms{ font-size:19px; } }
    #rmbz-vip .project-chat-attach-btn{ width:46px; height:46px; flex:0 0 46px; padding:0; display:inline-flex; align-items:center; justify-content:center; border:1px solid var(--border2); border-radius:15px; background:var(--elev); color:var(--brand-ink); cursor:pointer; transition:background .18s,border-color .18s,transform .18s; }
    #rmbz-vip .project-chat-attach-btn:hover{ background:var(--brand-soft); border-color:var(--brand); }
    #rmbz-vip .project-chat-attach-btn:active{ transform:scale(.96); }
    #rmbz-vip .project-chat-attach-btn:disabled{ opacity:.45; cursor:not-allowed; transform:none; }
    #rmbz-vip .project-chat-attach-btn[hidden]{ display:none; }
    #rmbz-vip .project-chat-upload{ flex:0 0 100%; display:flex; align-items:center; gap:11px; min-width:0; padding:10px 12px; border:1px solid var(--border2); border-radius:15px; background:var(--surface); }
    #rmbz-vip .project-chat-upload[hidden]{ display:none; }
    #rmbz-vip .project-chat-upload-icon{ width:38px; height:38px; flex:0 0 38px; display:inline-flex; align-items:center; justify-content:center; border-radius:12px; background:var(--brand-soft); color:var(--brand-ink); font-size:20px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .project-chat-upload-copy{ min-width:0; flex:1; }
    #rmbz-vip .project-chat-upload-name{ display:block; overflow:hidden; color:var(--text); font-size:11.5px; font-weight:750; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .project-chat-upload-meta{ display:block; margin-top:2px; color:var(--muted); font-size:10px; }
    #rmbz-vip .project-chat-upload.uploading .project-chat-upload-meta{ color:var(--brand-ink); }
    #rmbz-vip .project-chat-upload-remove{ width:34px; height:34px; flex:0 0 34px; padding:0; display:inline-flex; align-items:center; justify-content:center; border:0; border-radius:11px; background:var(--danger-soft); color:var(--danger); cursor:pointer; }
    #rmbz-vip .project-chat-upload-remove .ms{ font-size:18px; }
    #rmbz-vip .inp{ width:100%; border:1px solid var(--border2); background:var(--elev); color:var(--text); border-radius:14px; padding:12px 16px; font-size:15px; font-weight:600; font-family:inherit; outline:none; }
    #rmbz-vip .inp:focus{ border-color:var(--brand); }
    #rmbz-vip .grid2{ display:grid; grid-template-columns:1fr 1fr; gap:20px; }
    #rmbz-vip .grid3{ display:grid; grid-template-columns:repeat(3,1fr); gap:20px; }
    #rmbz-vip .scrim{ position:fixed; inset:0; background:var(--scrim); display:none; align-items:center; justify-content:center; z-index:100; padding:16px; }
    #rmbz-vip .scrim.open{ display:flex; }
    #rmbz-vip .dialog{ background:var(--surface); border:1px solid var(--border); border-radius:28px; width:440px; max-width:100%; max-height:92vh; overflow-y:auto; padding:28px 30px; animation:rmbzVipPop .22s ease; }
    #rmbz-vip .deposit-proof-trigger{ width:100%; display:block; overflow:hidden; margin-top:12px; padding:0; border:1px solid var(--border); border-radius:16px; background:var(--elev); color:var(--brand-ink); font-family:inherit; cursor:pointer; }
    #rmbz-vip .deposit-proof-trigger img{ width:100%; max-height:300px; display:block; object-fit:contain; background:var(--elev); }
    #rmbz-vip .deposit-proof-trigger-label{ min-height:43px; display:flex; align-items:center; justify-content:center; gap:7px; padding:9px 12px; border-top:1px solid var(--border); font-size:12px; font-weight:750; }
    #rmbz-vip .deposit-proof-trigger-label>.ms{ font-size:17px; }
    #rmbz-vip .deposit-proof-id-note{ display:flex; align-items:flex-start; gap:9px; margin-top:12px; padding:11px 12px; border:1px solid color-mix(in srgb,var(--info) 30%,var(--border)); border-radius:14px; background:var(--info-soft); color:var(--text2); }
    #rmbz-vip .deposit-proof-id-note>.ms{ flex:0 0 auto; margin-top:1px; color:var(--info); font-size:19px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .deposit-proof-id-note strong{ display:block; color:var(--text); font-size:11.5px; }
    #rmbz-vip .deposit-proof-id-note span:last-child{ display:block; margin-top:2px; color:var(--text2); font-size:10.5px; line-height:1.45; }
    #rmbz-vip .deposit-proof-viewer{ z-index:140; padding:0; background:rgba(0,0,0,.94); }
    #rmbz-vip .deposit-proof-dialog{ width:100vw; height:100vh; max-width:none; max-height:none; display:grid; grid-template-rows:auto minmax(0,1fr); overflow:hidden; padding:0; border:0; border-radius:0; background:#08090b; color:#fff; }
    #rmbz-vip .deposit-proof-toolbar{ min-height:64px; display:flex; align-items:center; gap:12px; padding:10px 16px; border-bottom:1px solid rgba(255,255,255,.12); background:rgba(16,17,20,.96); }
    #rmbz-vip .deposit-proof-toolbar-icon{ width:40px; height:40px; display:flex; align-items:center; justify-content:center; flex:0 0 40px; border-radius:13px; background:rgba(240,185,11,.16); color:#f0b90b; font-size:21px; }
    #rmbz-vip .deposit-proof-toolbar-copy{ flex:1; min-width:0; }
    #rmbz-vip .deposit-proof-title{ margin:0; overflow:hidden; color:#fff; font-size:15px; font-weight:780; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .deposit-proof-subtitle{ margin-top:2px; color:rgba(255,255,255,.62); font-size:10.5px; }
    #rmbz-vip .deposit-proof-original,#rmbz-vip .deposit-proof-close{ min-height:40px; display:inline-flex; align-items:center; justify-content:center; gap:6px; padding:8px 12px; border:1px solid rgba(255,255,255,.15); border-radius:100px; background:rgba(255,255,255,.08); color:#fff; font-family:inherit; font-size:11px; font-weight:700; cursor:pointer; text-decoration:none; }
    #rmbz-vip .deposit-proof-original>.ms,#rmbz-vip .deposit-proof-close>.ms{ font-size:18px; }
    #rmbz-vip .deposit-proof-close{ width:40px; padding:0; }
    #rmbz-vip .deposit-proof-stage{ min-width:0; min-height:0; display:flex; align-items:center; justify-content:center; overflow:auto; padding:18px; }
    #rmbz-vip .deposit-proof-full{ max-width:100%; max-height:100%; display:block; object-fit:contain; border-radius:4px; box-shadow:0 22px 70px rgba(0,0,0,.55); }
    @media(max-width:600px){ #rmbz-vip .deposit-proof-toolbar{ min-height:58px; padding:8px 10px; } #rmbz-vip .deposit-proof-toolbar-icon{ width:36px; height:36px; flex-basis:36px; font-size:19px; } #rmbz-vip .deposit-proof-original{ width:40px; padding:0; font-size:0; } #rmbz-vip .deposit-proof-stage{ padding:10px; } }
    #rmbz-vip .wstep{ display:none; } #rmbz-vip .wstep.on{ display:block; }
    #rmbz-vip .met{ display:flex; align-items:center; gap:14px; width:100%; border:2px solid var(--border); background:var(--elev); border-radius:18px; padding:14px 16px; text-align:left; cursor:pointer; font-family:inherit; margin-bottom:10px; }
    #rmbz-vip .met.on{ border-color:var(--brand); background:var(--brand-soft); }
    #rmbz-vip .chip{ border:1px solid var(--border2); background:transparent; color:var(--text2); font-family:inherit; font-size:12.5px; font-weight:650; padding:9px 17px; border-radius:100px; cursor:pointer; }
    #rmbz-vip .chip:hover{ background:var(--hover); }
    #rmbz-vip :where(button,a,input,select,textarea,[tabindex]):focus-visible{ outline:3px solid var(--brand); outline-offset:3px; }
    #rmbz-vip .rvd-tabs{ display:flex; gap:5px; margin-bottom:18px; padding:5px; overflow-x:auto; border:1px solid var(--border); border-radius:18px; background:var(--surface); scrollbar-width:none; }
    #rmbz-vip .rvd-tabs::-webkit-scrollbar{ display:none; }
    #rmbz-vip .rvd-tab{ min-height:39px; display:inline-flex; align-items:center; justify-content:center; gap:7px; flex:0 0 auto; padding:8px 14px; border:0; border-radius:13px; background:transparent; color:var(--text2); font-family:inherit; font-size:12px; font-weight:700; cursor:pointer; transition:background .16s,color .16s; }
    #rmbz-vip .rvd-tab .ms{ font-size:17px; }
    #rmbz-vip .rvd-tab:hover{ background:var(--hover); color:var(--text); }
    #rmbz-vip .rvd-tab.on{ background:var(--brand-soft); color:var(--brand-ink); font-weight:800; }
    #rmbz-vip .rvd-tab.on .ms{ font-variation-settings:'FILL' 1; }
    #rmbz-vip .distro-summary-grid{ display:grid; grid-template-columns:1.3fr 1fr 1fr; gap:14px; }
    #rmbz-vip .distro-balance-card{ position:relative; overflow:hidden; min-height:172px; padding:22px 24px; border:1px solid rgba(255,255,255,.06); border-radius:25px; background:linear-gradient(145deg,#32485e,#26394c); color:#fff; }
    #rmbz-vip .distro-balance-card::after{ content:''; position:absolute; width:155px; height:155px; right:-60px; top:-70px; border-radius:50%; background:rgba(255,255,255,.045); }
    #rmbz-vip .distro-summary-head{ position:relative; display:flex; align-items:center; gap:9px; }
    #rmbz-vip .distro-summary-icon{ width:38px; height:38px; flex:0 0 38px; align-items:center; justify-content:center; border-radius:13px; background:var(--brand-soft); color:var(--brand-ink); font-size:20px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .distro-balance-card .distro-summary-icon{ background:rgba(255,255,255,.11); color:#fff; }
    #rmbz-vip .distro-summary-label{ color:var(--muted); font-size:9.5px; line-height:1.25; font-weight:800; letter-spacing:.08em; text-transform:uppercase; }
    #rmbz-vip .distro-balance-card .distro-summary-label{ color:rgba(255,255,255,.68); }
    #rmbz-vip .distro-summary-value{ position:relative; margin-top:16px; color:var(--text); font-family:'JetBrains Mono',monospace; font-size:25px; line-height:1.1; font-weight:680; letter-spacing:-.025em; }
    #rmbz-vip .distro-balance-card .distro-summary-value{ color:#fff; font-size:30px; }
    #rmbz-vip .distro-summary-meta{ position:relative; margin-top:7px; color:var(--muted); font-size:10.5px; line-height:1.45; }
    #rmbz-vip .distro-balance-card .distro-summary-meta{ color:rgba(255,255,255,.6); }
    #rmbz-vip .distro-summary-card{ min-height:172px; padding:20px; border:1px solid var(--border); border-radius:25px; background:var(--surface); }
    #rmbz-vip .distro-create-banner{ display:grid; grid-template-columns:48px minmax(0,1fr) auto; gap:14px; align-items:center; margin-top:14px; padding:17px 18px; border:1px solid color-mix(in srgb,var(--brand) 45%,var(--border)); border-radius:22px; background:linear-gradient(120deg,var(--brand-soft),var(--surface) 70%); }
    #rmbz-vip .distro-create-icon{ width:48px; height:48px; align-items:center; justify-content:center; border-radius:16px; background:var(--brand); color:var(--on-brand); font-size:24px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .distro-create-title{ color:var(--text); font-family:'Bricolage Grotesque',sans-serif; font-size:16px; line-height:1.25; font-weight:780; }
    #rmbz-vip .distro-create-title span{ color:var(--brand-ink); }
    #rmbz-vip .distro-create-text{ margin-top:3px; color:var(--text2); font-size:10.5px; line-height:1.45; }
    #rmbz-vip .distro-create-action{ min-height:42px; justify-content:center; padding:9px 16px; background:var(--brand); color:var(--on-brand); font-size:11px; }
    #rmbz-vip .distro-create-action .ms{ font-size:18px; }
    #rmbz-vip .distro-dsp-grid{ display:grid; grid-template-columns:1fr 1fr; gap:12px; margin-top:14px; }
    #rmbz-vip .distro-dsp-card{ position:relative; overflow:hidden; min-height:78px; display:flex; align-items:center; gap:12px; padding:15px 17px; border-radius:20px; color:#fff !important; text-decoration:none; transition:transform .17s ease,filter .17s ease; }
    #rmbz-vip .distro-dsp-card:hover{ transform:translateY(-2px); filter:brightness(1.04); }
    #rmbz-vip .distro-dsp-card.spotify{ background:linear-gradient(120deg,#1db954,#0c6a32); }
    #rmbz-vip .distro-dsp-card.apple{ background:linear-gradient(120deg,#fa2d48,#891729); }
    #rmbz-vip .distro-dsp-logo{ width:42px; height:42px; flex:0 0 42px; display:flex; align-items:center; justify-content:center; }
    #rmbz-vip .distro-dsp-copy{ flex:1; min-width:0; }
    #rmbz-vip .distro-dsp-title{ color:#fff; font-size:12.5px; font-weight:780; }
    #rmbz-vip .distro-dsp-text{ margin-top:3px; color:rgba(255,255,255,.82); font-size:10px; }
    #rmbz-vip .distro-dsp-arrow{ color:rgba(255,255,255,.82); font-size:20px; }
    #rmbz-vip .distro-catalog-head{ display:flex; align-items:center; gap:11px; margin:24px 0 11px; }
    #rmbz-vip .distro-catalog-icon{ width:38px; height:38px; align-items:center; justify-content:center; border-radius:12px; background:var(--brand-soft); color:var(--brand-ink); font-size:19px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .distro-catalog-copy{ flex:1; min-width:0; }
    #rmbz-vip .distro-catalog-title{ color:var(--text); font-size:13px; line-height:1.3; font-weight:780; }
    #rmbz-vip .distro-catalog-subtitle{ margin-top:2px; color:var(--muted); font-size:10px; }
    #rmbz-vip .distro-catalog-count{ display:inline-flex; min-height:29px; align-items:center; padding:5px 9px; border-radius:100px; background:var(--elev); color:var(--text2); font-size:9.5px; font-weight:750; white-space:nowrap; }
    #rmbz-vip .distro-filter{ display:grid; grid-template-columns:minmax(220px,1fr) 150px 160px auto; gap:8px; margin-bottom:14px; padding:10px; border:1px solid var(--border); border-radius:19px; background:var(--surface); }
    #rmbz-vip .distro-search{ position:relative; }
    #rmbz-vip .distro-search>.ms{ position:absolute; z-index:1; left:12px; top:50%; transform:translateY(-50%); color:var(--muted); font-size:18px; }
    #rmbz-vip .distro-filter .inp{ min-height:42px; margin:0; padding:9px 12px; border-radius:12px; font-size:11.5px; }
    #rmbz-vip .distro-filter .distro-search .inp{ padding-left:38px; }
    #rmbz-vip .distro-filter-submit{ min-height:42px; justify-content:center; padding:9px 16px; background:var(--brand); color:var(--on-brand); font-size:11px; }
    #rmbz-vip .distro-release-grid{ display:grid; grid-template-columns:repeat(auto-fill,minmax(175px,1fr)); gap:14px; }
    #rmbz-vip .distro-release-link{ min-width:0; color:inherit !important; text-decoration:none; }
    #rmbz-vip .distro-release-card{ height:100%; overflow:hidden; border:1px solid var(--border); border-radius:20px; background:var(--surface); box-shadow:0 8px 26px -27px rgba(0,0,0,.7); transition:transform .17s ease,border-color .17s ease,box-shadow .17s ease; }
    #rmbz-vip .distro-release-card:hover{ transform:translateY(-3px); border-color:var(--brand); box-shadow:0 18px 34px -30px rgba(0,0,0,.8); }
    #rmbz-vip .distro-release-cover{ position:relative; aspect-ratio:1/1; overflow:hidden; background:var(--elev); }
    #rmbz-vip .distro-release-cover img{ width:100%; height:100%; display:block; object-fit:cover; transition:transform .2s ease; }
    #rmbz-vip .distro-release-card:hover .distro-release-cover img{ transform:scale(1.025); }
    #rmbz-vip .distro-release-placeholder{ width:100%; height:100%; display:flex; align-items:center; justify-content:center; color:var(--muted); }
    #rmbz-vip .distro-release-placeholder .ms{ font-size:34px; }
    #rmbz-vip .distro-release-status{ position:absolute; top:9px; left:9px; display:inline-flex; align-items:center; gap:5px; min-height:26px; padding:5px 8px; border-radius:100px; background:rgba(12,12,14,.78); color:#fff; font-size:9px; font-weight:780; backdrop-filter:blur(8px); }
    #rmbz-vip .distro-release-status-dot{ width:6px; height:6px; flex:0 0 6px; border-radius:50%; }
    #rmbz-vip .distro-release-body{ padding:11px 12px 12px; }
    #rmbz-vip .distro-release-title{ overflow:hidden; color:var(--text); font-size:12px; line-height:1.35; font-weight:760; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .distro-release-type{ display:flex; align-items:center; gap:5px; margin-top:4px; color:var(--muted); font-size:9.5px; text-transform:capitalize; }
    #rmbz-vip .distro-release-type .ms{ font-size:13px; }
    #rmbz-vip .distro-new-release{ min-height:100%; padding:0; border:0; background:transparent; font-family:inherit; cursor:pointer; }
    #rmbz-vip .distro-new-release-inner{ height:100%; min-height:220px; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:9px; border:2px dashed var(--border2); border-radius:20px; background:var(--elev); color:var(--muted); transition:border-color .17s,color .17s,background .17s; }
    #rmbz-vip .distro-new-release:hover .distro-new-release-inner{ border-color:var(--brand); background:var(--brand-soft); color:var(--brand-ink); }
    #rmbz-vip .distro-new-release-icon{ width:42px; height:42px; align-items:center; justify-content:center; border-radius:14px; background:var(--surface); font-size:23px; }
    #rmbz-vip .distro-new-release-label{ font-size:10.5px; font-weight:750; }
    #rmbz-vip .distro-empty{ min-height:240px; display:flex; flex-direction:column; align-items:center; justify-content:center; padding:30px 22px; border:1px solid var(--border); border-radius:23px; background:var(--surface); text-align:center; }
    #rmbz-vip .distro-empty>.ms{ width:56px; height:56px; align-items:center; justify-content:center; border-radius:18px; background:var(--elev); color:var(--muted); font-size:28px; }
    #rmbz-vip .distro-empty-title{ margin-top:12px; color:var(--text); font-size:13px; font-weight:780; }
    #rmbz-vip .distro-empty-text{ max-width:420px; margin:5px 0 14px; color:var(--muted); font-size:10.5px; line-height:1.5; }
    #rmbz-vip .distro-quick-grid{ display:grid; grid-template-columns:1fr 1fr; gap:12px; margin-top:22px; }
    #rmbz-vip .distro-quick-card{ display:flex; align-items:center; gap:12px; min-height:78px; padding:15px 17px; border:1px solid var(--border); border-radius:20px; background:var(--surface); color:var(--text); font-family:inherit; text-align:left; cursor:pointer; transition:background .16s,border-color .16s; }
    #rmbz-vip .distro-quick-card:hover{ border-color:var(--brand); background:var(--brand-soft); }
    #rmbz-vip .distro-quick-icon{ width:40px; height:40px; flex:0 0 40px; align-items:center; justify-content:center; border-radius:13px; background:var(--brand-soft); color:var(--brand-ink); font-size:20px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .distro-quick-copy{ flex:1; min-width:0; }
    #rmbz-vip .distro-quick-title{ color:var(--text); font-size:11.5px; font-weight:780; }
    #rmbz-vip .distro-quick-text{ margin-top:2px; color:var(--muted); font-size:9.5px; line-height:1.4; }
    #rmbz-vip .distro-quick-arrow{ color:var(--muted); font-size:18px; }
    #rmbz-vip .release-detail-back{ min-height:40px; margin-bottom:12px; padding:8px 13px; border:1px solid var(--border); background:var(--surface); color:var(--text2); font-size:10.5px; }
    #rmbz-vip .release-detail-back .ms{ font-size:17px; }
    #rmbz-vip .release-hero{ display:grid; grid-template-columns:170px minmax(0,1fr); gap:21px; padding:20px; border:1px solid var(--border); border-radius:27px; background:var(--surface); box-shadow:0 10px 32px -31px rgba(0,0,0,.72); }
    #rmbz-vip .release-hero-cover{ width:170px; aspect-ratio:1/1; overflow:hidden; display:flex; align-items:center; justify-content:center; border-radius:21px; background:var(--elev); color:var(--muted); }
    #rmbz-vip .release-hero-cover img{ width:100%; height:100%; display:block; object-fit:cover; }
    #rmbz-vip .release-hero-cover>.ms{ font-size:42px; }
    #rmbz-vip .release-hero-content{ min-width:0; display:flex; flex-direction:column; }
    #rmbz-vip .release-hero-top{ display:flex; align-items:flex-start; gap:12px; }
    #rmbz-vip .release-hero-heading{ flex:1; min-width:0; }
    #rmbz-vip .release-status{ display:inline-flex; align-items:center; gap:6px; min-height:27px; padding:5px 9px; border-radius:100px; font-size:9.5px; font-weight:800; }
    #rmbz-vip .release-status::before{ content:''; width:6px; height:6px; border-radius:50%; background:currentColor; }
    #rmbz-vip .release-hero-title{ margin-top:8px; color:var(--text); font-family:'Bricolage Grotesque',sans-serif; font-size:25px; line-height:1.2; font-weight:780; letter-spacing:-.02em; }
    #rmbz-vip .release-hero-artist{ margin-top:4px; color:var(--text2); font-size:11.5px; }
    #rmbz-vip .release-meta{ display:flex; gap:6px; flex-wrap:wrap; margin-top:11px; }
    #rmbz-vip .release-meta-chip{ display:inline-flex; align-items:center; gap:5px; min-height:28px; padding:5px 8px; border:1px solid var(--border); border-radius:9px; background:var(--elev); color:var(--text2); font-size:9.5px; }
    #rmbz-vip .release-meta-chip .ms{ color:var(--brand-ink); font-size:14px; }
    #rmbz-vip .release-hero-metrics{ display:flex; gap:8px; flex-wrap:wrap; margin-top:12px; }
    #rmbz-vip .release-hero-metric{ min-width:120px; padding:10px 11px; border:1px solid var(--border); border-radius:14px; background:var(--elev); }
    #rmbz-vip .release-hero-metric-label{ color:var(--muted); font-size:8.5px; font-weight:780; letter-spacing:.07em; text-transform:uppercase; }
    #rmbz-vip .release-hero-metric-value{ margin-top:4px; color:var(--text); font-family:'JetBrains Mono',monospace; font-size:17px; line-height:1.15; font-weight:700; }
    #rmbz-vip .release-hero-metric.success .release-hero-metric-value{ color:var(--success); }
    #rmbz-vip .release-actions{ grid-column:1 / -1; display:flex; gap:8px; flex-wrap:wrap; padding-top:15px; border-top:1px solid var(--border); }
    #rmbz-vip .release-action{ min-height:40px; padding:8px 13px; font-size:10.5px; }
    #rmbz-vip .release-action .ms{ font-size:17px; }
    #rmbz-vip .release-action.primary{ background:var(--brand); color:var(--on-brand); }
    #rmbz-vip .release-action.tonal{ background:var(--brand-soft); color:var(--brand-ink); }
    #rmbz-vip .release-action.outlined{ border:1px solid var(--border2); background:transparent; color:var(--text2); }
    #rmbz-vip .release-action.danger{ border:1px solid color-mix(in srgb,var(--danger) 45%,var(--border)); background:var(--danger-soft); color:var(--danger); }
    #rmbz-vip .release-action.locked{ border:1px solid var(--border); background:var(--elev); color:var(--muted); cursor:default; }
    #rmbz-vip .release-feedback{ display:flex; align-items:center; gap:8px; margin-top:11px; padding:10px 12px; border-radius:14px; font-size:10.5px; font-weight:700; }
    #rmbz-vip .release-feedback.success{ background:var(--success-soft); color:var(--success); }
    #rmbz-vip .release-feedback.danger{ background:var(--danger-soft); color:var(--danger); }
    #rmbz-vip .release-license-box{ margin-top:12px; }
    #rmbz-vip .release-license-box>.card{ padding:17px 18px !important; border-radius:21px !important; box-shadow:none; }
    #rmbz-vip .release-license-head{ display:flex; align-items:center; gap:11px; }
    #rmbz-vip .release-license-icon{ width:40px; height:40px; display:flex; align-items:center; justify-content:center; flex:0 0 40px; border-radius:13px; background:var(--brand-soft); color:var(--brand-ink); font-size:20px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .release-license-head-copy{ flex:1; min-width:0; }
    #rmbz-vip .release-license-title{ color:var(--text); font-size:11.5px; font-weight:800; }
    #rmbz-vip .release-license-subtitle{ margin-top:2px; color:var(--muted); font-size:9px; line-height:1.45; }
    #rmbz-vip .release-license-registration{ display:flex; align-items:center; gap:22px; }
    #rmbz-vip .release-license-registration-copy{ flex:1; min-width:0; }
    #rmbz-vip .release-license-registration-copy p{ margin:9px 0 0; color:var(--text2); font-size:9.5px; line-height:1.5; }
    #rmbz-vip .release-license-registration-action{ min-width:164px; min-height:42px; display:inline-flex; align-items:center; justify-content:center; gap:7px; flex:0 0 auto; margin-left:auto; padding:10px 17px; border-radius:100px; background:var(--brand); color:var(--on-brand); font-size:10px; font-weight:780; text-align:center; text-decoration:none; }
    #rmbz-vip .release-license-registration-action>.ms{ font-size:16px; }
    #rmbz-vip .release-tracker{ margin-top:12px; padding:19px; border:1px solid var(--border); border-radius:24px; background:var(--surface); }
    #rmbz-vip .release-tracker-head{ display:flex; align-items:center; gap:11px; }
    #rmbz-vip .release-tracker-icon{ width:40px; height:40px; flex:0 0 40px; align-items:center; justify-content:center; border-radius:13px; background:var(--brand-soft); color:var(--brand-ink); font-size:20px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .release-tracker-copy{ flex:1; min-width:0; }
    #rmbz-vip .release-tracker-kicker{ color:var(--muted); font-size:8.5px; font-weight:800; letter-spacing:.1em; text-transform:uppercase; }
    #rmbz-vip .release-tracker-title{ margin-top:2px; color:var(--text); font-size:12.5px; font-weight:780; }
    #rmbz-vip .release-tracker-state{ display:inline-flex; align-items:center; gap:5px; min-height:28px; padding:5px 9px; border-radius:100px; font-size:9.5px; font-weight:780; white-space:nowrap; }
    #rmbz-vip .release-tracker-state .ms{ font-size:14px; }
    #rmbz-vip .release-tracker-steps{ position:relative; display:grid; grid-template-columns:repeat(5,minmax(0,1fr)); margin-top:19px; }
    #rmbz-vip .release-tracker-rail{ position:absolute; z-index:0; top:14px; left:10%; right:10%; height:3px; overflow:hidden; border-radius:100px; background:var(--border2); }
    #rmbz-vip .release-tracker-rail span{ display:block; width:var(--release-progress); height:100%; border-radius:inherit; background:var(--success); }
    #rmbz-vip .release-tracker-step{ position:relative; z-index:1; display:flex; flex-direction:column; align-items:center; min-width:0; color:var(--muted); text-align:center; }
    #rmbz-vip .release-tracker-dot{ width:30px; height:30px; align-items:center; justify-content:center; border:2px solid var(--border2); border-radius:50%; background:var(--surface); color:var(--muted); font-size:15px; }
    #rmbz-vip .release-tracker-step.done .release-tracker-dot{ border-color:var(--success); background:var(--success); color:#fff; }
    #rmbz-vip .release-tracker-step.current .release-tracker-dot{ border-color:var(--brand); background:var(--brand); color:var(--on-brand); box-shadow:0 0 0 5px var(--brand-soft); font-variation-settings:'FILL' 1; }
    #rmbz-vip .release-tracker-step-title{ margin-top:7px; color:var(--text2); font-size:9.5px; line-height:1.25; font-weight:750; }
    #rmbz-vip .release-tracker-step.current .release-tracker-step-title{ color:var(--brand-ink); }
    #rmbz-vip .release-tracker-step-sub{ margin-top:2px; color:var(--muted); font-size:8px; line-height:1.25; }
    #rmbz-vip .release-listen{ margin-top:18px; padding-top:15px; border-top:1px solid var(--border); }
    #rmbz-vip .release-listen-head{ display:flex; align-items:center; gap:8px; margin-bottom:9px; color:var(--text); font-size:10.5px; font-weight:780; }
    #rmbz-vip .release-listen-head .ms{ color:var(--success); font-size:17px; }
    #rmbz-vip .release-listen-note{ margin-left:auto; color:var(--muted); font-size:8.5px; font-weight:600; }
    #rmbz-vip .release-store-chips{ display:flex; flex-wrap:wrap; gap:7px; }
    #rmbz-vip .release-store-chip{ display:inline-flex; align-items:center; gap:6px; min-height:32px; padding:6px 10px; border:1px solid var(--border); border-radius:100px; background:var(--elev); color:var(--text); font-size:9.5px; font-weight:700; text-decoration:none; }
    #rmbz-vip .release-store-chip:hover{ border-color:var(--brand); background:var(--brand-soft); }
    #rmbz-vip .release-store-chip.pending{ color:var(--muted); opacity:.5; }
    #rmbz-vip .release-store-chip .ms{ color:var(--muted); font-size:13px; }
    #rmbz-vip .release-history{ margin-top:16px; padding-top:14px; border-top:1px solid var(--border); }
    #rmbz-vip .release-history>summary{ list-style:none; display:flex; align-items:center; gap:9px; min-height:42px; padding:8px 10px; border-radius:14px; background:var(--elev); color:var(--text); cursor:pointer; }
    #rmbz-vip .release-history>summary::-webkit-details-marker{ display:none; }
    #rmbz-vip .release-history-summary-icon{ width:30px; height:30px; align-items:center; justify-content:center; border-radius:10px; background:var(--surface); color:var(--brand-ink); font-size:16px; }
    #rmbz-vip .release-history-summary-copy{ flex:1; min-width:0; }
    #rmbz-vip .release-history-title{ font-size:10.5px; font-weight:780; }
    #rmbz-vip .release-history-subtitle{ margin-top:1px; color:var(--muted); font-size:8.5px; }
    #rmbz-vip .release-history-chevron{ color:var(--muted); font-size:18px; transition:transform .17s; }
    #rmbz-vip .release-history[open] .release-history-chevron{ transform:rotate(180deg); }
    #rmbz-vip .release-timeline{ position:relative; display:flex; flex-direction:column; gap:8px; margin-top:10px; padding-left:17px; }
    #rmbz-vip .release-timeline::before{ content:''; position:absolute; left:6px; top:10px; bottom:10px; width:2px; border-radius:2px; background:var(--border2); }
    #rmbz-vip .release-event{ position:relative; display:grid; grid-template-columns:34px minmax(0,1fr) auto; gap:9px; align-items:start; padding:10px 11px; border:1px solid var(--border); border-radius:15px; background:var(--elev); }
    #rmbz-vip .release-event::before{ content:''; position:absolute; left:-15px; top:19px; width:8px; height:8px; border:3px solid var(--surface); border-radius:50%; background:var(--event-color,var(--brand)); }
    #rmbz-vip .release-event-icon{ width:34px; height:34px; align-items:center; justify-content:center; border-radius:11px; background:var(--surface); color:var(--event-color,var(--brand-ink)); font-size:17px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .release-event-copy{ min-width:0; }
    #rmbz-vip .release-event-title{ color:var(--text); font-size:10.5px; line-height:1.35; font-weight:760; }
    #rmbz-vip .release-event-text{ margin-top:2px; color:var(--text2); font-size:9.5px; line-height:1.45; }
    #rmbz-vip .release-event-time{ color:var(--muted); font-size:8.5px; white-space:nowrap; }
    #rmbz-vip .release-event-reason{ grid-column:2 / -1; padding:7px 8px; border:1px solid var(--border); border-radius:9px; background:var(--surface); color:var(--muted); font-family:'JetBrains Mono',monospace; font-size:8.5px; line-height:1.45; word-break:break-word; }
    #rmbz-vip .release-info-grid{ display:grid; grid-template-columns:1fr 1fr; gap:12px; margin-top:12px; align-items:start; }
    #rmbz-vip .release-info-card{ min-width:0; padding:17px; border:1px solid var(--border); border-radius:21px; background:var(--surface); }
    #rmbz-vip .release-info-card.attention{ border-style:dashed; border-color:color-mix(in srgb,var(--rev) 55%,var(--border)); }
    #rmbz-vip .release-section-head{ display:flex; align-items:center; gap:9px; margin-bottom:12px; }
    #rmbz-vip .release-section-icon{ width:35px; height:35px; flex:0 0 35px; align-items:center; justify-content:center; border-radius:11px; background:var(--brand-soft); color:var(--brand-ink); font-size:18px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .release-section-copy{ flex:1; min-width:0; }
    #rmbz-vip .release-section-title{ color:var(--text); font-size:11.5px; line-height:1.3; font-weight:780; }
    #rmbz-vip .release-section-subtitle{ margin-top:2px; color:var(--muted); font-size:8.5px; line-height:1.4; }
    #rmbz-vip .release-link-list{ display:flex; flex-direction:column; gap:7px; }
    #rmbz-vip .release-link-row{ min-width:0; padding:9px 10px; border:1px solid var(--border); border-radius:12px; background:var(--elev); }
    #rmbz-vip .release-link-label{ color:var(--muted); font-size:8px; font-weight:800; letter-spacing:.08em; text-transform:uppercase; }
    #rmbz-vip .release-link-value{ display:flex; align-items:center; gap:5px; overflow:hidden; margin-top:3px; color:var(--text2); font-family:'JetBrains Mono',monospace; font-size:8.5px; line-height:1.4; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .release-link-value.is-empty{ color:var(--muted); font-family:inherit; }
    #rmbz-vip a.release-link-value{ color:var(--brand-ink); }
    #rmbz-vip .release-link-value>.ms{ flex:0 0 auto; font-size:13px; }
    #rmbz-vip .release-profile-state{ display:flex; align-items:flex-start; gap:9px; padding:10px 11px; border-radius:14px; background:var(--elev); }
    #rmbz-vip .release-profile-state>.ms{ margin-top:1px; color:var(--rev); font-size:18px; }
    #rmbz-vip .release-profile-state.success>.ms{ color:var(--success); }
    #rmbz-vip .release-profile-state strong{ display:block; color:var(--text); font-size:10.5px; }
    #rmbz-vip .release-profile-state span:last-child{ display:block; margin-top:2px; color:var(--text2); font-size:9px; line-height:1.45; }
    #rmbz-vip .release-profile-action{ min-height:37px; display:inline-flex; align-items:center; justify-content:center; gap:6px; margin-top:10px; padding:8px 12px; border:0; border-radius:100px; background:var(--brand); color:var(--on-brand); font-family:inherit; font-size:9.5px; font-weight:750; cursor:pointer; }
    #rmbz-vip .release-profile-action>.ms{ font-size:14px; }
    #rmbz-vip .release-profile-action.outlined{ border:1px solid var(--border2); background:transparent; color:var(--brand-ink); }
    #rmbz-vip .release-content-section{ margin-top:18px; }
    #rmbz-vip .release-content-section>.release-section-head{ margin-bottom:9px; }
    #rmbz-vip .release-data-grid{ display:grid; grid-template-columns:repeat(auto-fill,minmax(185px,1fr)); overflow:hidden; border:1px solid var(--border); border-radius:19px; background:var(--surface); }
    #rmbz-vip .release-data-cell{ min-width:0; padding:12px 14px; border-right:1px solid var(--border); border-bottom:1px solid var(--border); }
    #rmbz-vip .release-data-label{ color:var(--muted); font-size:8px; font-weight:800; letter-spacing:.08em; text-transform:uppercase; }
    #rmbz-vip .release-data-value{ margin-top:4px; overflow:hidden; color:var(--text); font-size:10.5px; line-height:1.4; font-weight:700; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .release-data-value.is-empty{ color:var(--muted); font-weight:500; }
    #rmbz-vip .release-track-list{ display:flex; flex-direction:column; gap:7px; }
    #rmbz-vip .release-track{ display:grid; grid-template-columns:34px minmax(0,1fr) auto; gap:10px; align-items:center; padding:10px 12px; border:1px solid var(--border); border-radius:15px; background:var(--surface); }
    #rmbz-vip .release-track-number{ width:34px; height:34px; display:flex; align-items:center; justify-content:center; border-radius:11px; background:var(--elev); color:var(--muted); font-family:'JetBrains Mono',monospace; font-size:10px; font-weight:800; }
    #rmbz-vip .release-track-copy{ min-width:0; }
    #rmbz-vip .release-track-title{ overflow:hidden; color:var(--text); font-size:10.5px; font-weight:750; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .release-track-isrc{ margin-top:2px; color:var(--muted); font-family:'JetBrains Mono',monospace; font-size:8.5px; }
    #rmbz-vip .release-track-duration{ color:var(--muted); font-family:'JetBrains Mono',monospace; font-size:9px; }
    #rmbz-vip .release-track-explicit{ display:inline-flex; margin-left:5px; padding:1px 4px; border-radius:3px; background:var(--text2); color:var(--surface); font-size:7px; vertical-align:middle; }
    #rmbz-vip .release-dsp-list{ display:flex; flex-wrap:wrap; gap:7px; }
    #rmbz-vip .release-dsp-chip{ display:inline-flex; align-items:center; gap:6px; min-height:31px; padding:6px 10px; border:1px solid var(--border); border-radius:100px; background:var(--elev); color:var(--text2); font-size:9.5px; font-weight:650; }
    #rmbz-vip .release-dsp-logo{ width:18px; height:18px; display:inline-flex; flex:0 0 18px; }
    #rmbz-vip .release-dsp-logo svg{ width:100%; height:100%; }
    #rmbz-vip .release-territories{ display:flex; align-items:flex-start; gap:7px; margin-top:10px; padding:9px 11px; border-radius:12px; background:var(--elev); color:var(--muted); font-size:9px; line-height:1.45; }
    #rmbz-vip .release-territories>.ms{ color:var(--brand-ink); font-size:15px; }
    #rmbz-vip .release-territories strong{ display:block; margin-bottom:1px; color:var(--text2); font-size:8px; letter-spacing:.06em; text-transform:uppercase; }
    #rmbz-vip .release-services{ display:flex; flex-direction:column; gap:9px; }
    #rmbz-vip .release-service-card{ padding:15px 16px; border:1px solid var(--border); border-radius:18px; background:var(--surface); }
    #rmbz-vip .release-service-head{ display:flex; align-items:center; gap:11px; }
    #rmbz-vip .release-service-logo{ width:36px; height:36px; display:flex; align-items:center; justify-content:center; flex:0 0 36px; padding:7px; border-radius:11px; background:var(--elev); }
    #rmbz-vip .release-service-logo svg{ width:100%; height:100%; }
    #rmbz-vip .release-service-copy{ flex:1; min-width:0; }
    #rmbz-vip .release-service-name{ color:var(--text); font-size:10.5px; font-weight:780; }
    #rmbz-vip .release-service-status{ display:inline-flex; align-items:center; gap:4px; margin-top:4px; padding:4px 8px; border-radius:100px; font-size:8.5px; font-weight:750; }
    #rmbz-vip .release-service-status>.ms{ font-size:12px; }
    #rmbz-vip .release-service-body{ margin:10px 0 0; color:var(--text2); font-size:9.5px; line-height:1.55; }
    #rmbz-vip .release-service-note{ display:flex; align-items:flex-start; gap:7px; margin-top:8px; padding:9px 10px; border-radius:11px; background:var(--elev); color:var(--text2); font-size:9px; line-height:1.5; }
    #rmbz-vip .release-service-note>.ms{ flex:0 0 auto; color:var(--brand-ink); font-size:15px; }
    @media (max-width:760px){ #rmbz-vip .release-hero{ grid-template-columns:130px minmax(0,1fr); gap:16px; padding:17px; } #rmbz-vip .release-hero-cover{ width:130px; } #rmbz-vip .release-hero-title{ font-size:21px; } #rmbz-vip .release-action{ flex:1; justify-content:center; } #rmbz-vip .release-tracker-step-sub{ display:none; } }
    @media (max-width:560px){ #rmbz-vip .release-hero{ grid-template-columns:1fr; } #rmbz-vip .release-hero-cover{ width:118px; } #rmbz-vip .release-actions{ grid-column:1; } #rmbz-vip .release-hero-metric{ flex:1; min-width:100px; } #rmbz-vip .release-license-registration{ flex-direction:column; align-items:stretch; gap:14px; } #rmbz-vip .release-license-registration-action{ width:100%; margin-left:0; } #rmbz-vip .release-tracker{ padding:15px; border-radius:20px; } #rmbz-vip .release-tracker-head{ align-items:flex-start; flex-wrap:wrap; } #rmbz-vip .release-tracker-state{ margin-left:51px; } #rmbz-vip .release-tracker-dot{ width:27px; height:27px; font-size:14px; } #rmbz-vip .release-tracker-rail{ top:12px; } #rmbz-vip .release-tracker-step-title{ font-size:8px; } #rmbz-vip .release-event{ grid-template-columns:30px minmax(0,1fr); } #rmbz-vip .release-event-icon{ width:30px; height:30px; } #rmbz-vip .release-event-time{ grid-column:2; } #rmbz-vip .release-event-reason{ grid-column:1 / -1; } #rmbz-vip .release-info-grid{ grid-template-columns:1fr; } #rmbz-vip .release-data-grid{ grid-template-columns:1fr 1fr; } }
    @media (max-width:1100px){ #rmbz-vip .distro-summary-grid{ grid-template-columns:1fr 1fr; } #rmbz-vip .distro-balance-card{ grid-column:1 / -1; } #rmbz-vip .distro-filter{ grid-template-columns:minmax(180px,1fr) 140px 150px auto; } }
    @media (max-width:760px){ #rmbz-vip .rvd-tabs{ margin-left:-2px; margin-right:-2px; border-radius:15px; } #rmbz-vip .distro-summary-grid,#rmbz-vip .distro-dsp-grid,#rmbz-vip .distro-quick-grid{ grid-template-columns:1fr; } #rmbz-vip .distro-balance-card{ grid-column:auto; } #rmbz-vip .distro-create-banner{ grid-template-columns:44px minmax(0,1fr); } #rmbz-vip .distro-create-icon{ width:44px; height:44px; } #rmbz-vip .distro-create-action{ grid-column:1 / -1; width:100%; } #rmbz-vip .distro-filter{ grid-template-columns:1fr 1fr; } #rmbz-vip .distro-search{ grid-column:1 / -1; } #rmbz-vip .distro-filter-submit{ grid-column:1 / -1; } }
    @media (max-width:520px){ #rmbz-vip .distro-summary-card,#rmbz-vip .distro-balance-card{ min-height:154px; padding:18px; border-radius:21px; } #rmbz-vip .distro-filter{ grid-template-columns:1fr; } #rmbz-vip .distro-search,#rmbz-vip .distro-filter-submit{ grid-column:auto; } #rmbz-vip .distro-release-grid{ grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px; } #rmbz-vip .distro-new-release-inner{ min-height:190px; } #rmbz-vip .distro-catalog-head{ align-items:flex-start; } }
    #rmbz-vip .rvd-somas-native .rmbz-somas-chooser{ padding:18px; border:1px solid var(--border); border-radius:23px; background:var(--surface); color:var(--text); }
    #rmbz-vip .rvd-somas-native .rmbz-somas-chooser__title{ margin:0; color:var(--text); font-family:'Bricolage Grotesque',sans-serif; font-size:18px; font-weight:780; letter-spacing:-.015em; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-chooser__intro{ margin:6px 0 15px; color:var(--text2); font-size:12px; line-height:1.5; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-chooser__options{ display:grid; grid-template-columns:1fr 1fr; gap:12px; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-chooser__option{ min-width:0; display:flex; flex-direction:column; padding:16px; border:1px solid var(--border); border-radius:18px; background:var(--elev); color:var(--text); text-decoration:none; transition:border-color .16s,background .16s,transform .16s; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-chooser__option:hover{ border-color:var(--brand); background:var(--brand-soft); transform:translateY(-2px); }
    #rmbz-vip .rvd-somas-native .rmbz-somas-chooser__option-icon{ width:40px; height:40px; display:flex; align-items:center; justify-content:center; margin:0 0 10px; border-radius:13px; background:var(--surface); color:var(--brand-ink); font-size:20px; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-chooser__option h4{ margin:0 0 6px; color:var(--text); font-size:11.5px; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-chooser__option p{ flex:1; margin:0 0 11px; color:var(--text2); font-size:11.5px; line-height:1.5; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-chooser__option-price{ margin:0 0 10px; padding:9px 10px; border:1px solid var(--border); border-radius:11px; background:var(--surface); color:var(--muted); font-size:11px; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-chooser__option-price strong{ color:var(--text); font-size:12px; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-chooser__option-cta{ display:inline-flex; align-items:center; color:var(--brand-ink); font-size:11.5px; font-weight:780; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-chooser__footnote{ margin:14px 0 0; color:var(--muted); font-size:10.5px; text-align:center; }
    #rmbz-vip .rvd-somas-native{ width:100%; max-width:1040px; margin:0 auto; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-back{ display:inline-flex; align-items:center; gap:6px; min-height:38px; margin:0 0 10px; padding:8px 12px; border:1px solid var(--border); border-radius:100px; background:var(--surface); color:var(--text2); font-size:11px; font-weight:700; text-decoration:none; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-back .ms{ font-size:15px; }
    #rmbz-vip .rvd-somas-native .rmbz-licensing-form-intro{ margin:0 0 12px; padding:17px 18px; border:1px solid var(--border); border-radius:21px; background:var(--surface); }
    #rmbz-vip .rvd-somas-native .rmbz-somas-intro-heading{ display:grid; grid-template-columns:36px minmax(0,1fr); align-items:center; gap:10px; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-intro-icon{ width:36px; height:36px; display:grid; place-items:center; border-radius:11px; background:var(--brand-soft); color:var(--brand-ink); }
    #rmbz-vip .rvd-somas-native .rmbz-somas-intro-icon>.ms{ width:20px; height:20px; display:block; overflow:hidden; font-size:20px; line-height:20px; text-align:center; font-variation-settings:'FILL' 1; }
    #rmbz-vip .rvd-somas-native .rmbz-licensing-form-intro h3{ margin:0; color:var(--text); font-family:'Bricolage Grotesque',sans-serif; font-size:17px; line-height:1.25; font-weight:780; letter-spacing:-.015em; }
    #rmbz-vip .rvd-somas-native .rmbz-licensing-form-intro>p{ margin:8px 0 0; color:var(--text2); font-size:11.5px; line-height:1.55; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-free{ display:flex; align-items:center; gap:8px; margin:12px 0 0; padding:10px 12px; border:1px solid color-mix(in srgb,var(--success) 32%,var(--border)); border-radius:13px; background:var(--success-soft); color:var(--success); font-size:11px; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-free>.ms{ font-size:17px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .rvd-somas-native .rmbz-licensing-balance-row{ display:flex; align-items:center; gap:9px; flex-wrap:wrap; margin-top:12px; padding:10px 12px; border-radius:13px; background:var(--elev); color:var(--text2); font-size:11px; }
    #rmbz-vip .rvd-somas-native .rmbz-licensing-balance-row strong{ margin-left:auto; color:var(--text); font-family:'JetBrains Mono',monospace; font-size:11px; }
    #rmbz-vip .rvd-somas-native .rmbz-licensing-balance-warn{ display:inline-flex; align-items:center; gap:4px; color:var(--danger); font-weight:750; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-form{ display:grid; grid-template-columns:1fr 1fr; gap:12px; margin:0; padding:18px; border:1px solid var(--border); border-radius:23px; background:var(--surface); }
    #rmbz-vip .rvd-somas-native .rmbz-somas-fieldset{ min-width:0; grid-column:1 / -1; margin:0; padding:15px; border:1px solid var(--border); border-radius:17px; background:var(--elev); }
    #rmbz-vip .rvd-somas-native .rmbz-somas-fieldset--half{ grid-column:auto; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-fieldset legend{ display:inline-flex; align-items:center; gap:6px; margin-left:-4px; padding:0 7px; color:var(--text); font-size:12px; font-weight:780; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-fieldset legend>.ms{ color:var(--brand-ink); font-size:16px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-grid{ display:grid; grid-template-columns:1fr 1fr; gap:11px; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-grid__full{ grid-column:1 / -1; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-grid label{ min-width:0; display:flex; flex-direction:column; gap:6px; color:var(--text2); font-size:11px; font-weight:700; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-grid input,
    #rmbz-vip .rvd-somas-native .rmbz-somas-grid select,
    #rmbz-vip .rvd-somas-native .rmbz-somas-fieldset textarea{ width:100%; min-height:47px; box-sizing:border-box; margin:0; padding:10px 12px; border:1px solid var(--border2); border-radius:12px; outline:0; background:var(--surface); color:var(--text); font:inherit; font-size:12px; transition:border-color .16s,box-shadow .16s,background .16s; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-grid input:focus,
    #rmbz-vip .rvd-somas-native .rmbz-somas-grid select:focus,
    #rmbz-vip .rvd-somas-native .rmbz-somas-fieldset textarea:focus{ border-color:var(--brand); background:var(--surface); box-shadow:0 0 0 3px color-mix(in srgb,var(--brand) 18%,transparent); }
    #rmbz-vip .rvd-somas-native .rmbz-field-warn{ min-height:0; color:var(--danger); font-size:10px; line-height:1.35; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-bi-help{ margin:4px 0 11px; color:var(--muted); font-size:10.5px; line-height:1.5; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-bi-input{ width:100%; min-height:60px; box-sizing:border-box; padding:8px; border:1px dashed var(--border2); border-radius:14px; background:var(--surface); color:var(--text2); font-family:inherit; font-size:11px; cursor:pointer; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-bi-input::file-selector-button{ min-height:41px; margin-right:10px; padding:8px 13px; border:0; border-radius:10px; background:var(--brand-soft); color:var(--brand-ink); font-family:inherit; font-size:11px; font-weight:780; cursor:pointer; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-bi-current{ margin:0 0 9px; padding:9px 11px; border:1px solid var(--border); border-radius:12px; background:var(--surface); color:var(--text2); font-size:11px; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-bi-current__label{ display:block; color:var(--muted); font-size:10px; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-bi-current__link{ display:inline-flex; margin-top:3px; color:var(--brand-ink); font-weight:750; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-bi-current__hint{ margin:4px 0 0; color:var(--muted); font-size:10px; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-actions{ grid-column:1 / -1; display:flex; align-items:center; justify-content:space-between; gap:18px; padding:3px 2px 0; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-actions .rmbz-btn{ min-width:200px; min-height:45px; order:2; display:inline-flex; align-items:center; justify-content:center; gap:7px; padding:10px 18px; border:0; border-radius:100px; background:var(--brand); color:var(--on-brand); font-family:inherit; font-size:12px; font-weight:800; cursor:pointer; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-actions .rmbz-btn:disabled{ opacity:.45; cursor:not-allowed; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-disclaimer{ max-width:620px; order:1; display:flex; align-items:flex-start; gap:7px; margin:0; color:var(--muted); font-size:10.5px; line-height:1.5; }
    #rmbz-vip .rvd-somas-native .rmbz-somas-disclaimer>.ms{ flex:0 0 auto; color:var(--brand-ink); font-size:15px; }
    #rmbz-vip .rvd-somas-native .rmbz-licensing-status{ display:grid; grid-template-columns:40px minmax(0,1fr); gap:5px 12px; margin:0 0 12px; padding:15px 16px; border:1px solid var(--border); border-radius:18px; background:var(--surface); }
    #rmbz-vip .rvd-somas-native .rmbz-licensing-status__icon{ grid-row:1 / 4; width:40px; height:40px; display:flex; align-items:center; justify-content:center; border-radius:13px; background:var(--brand-soft); color:var(--brand-ink); font-size:20px; }
    #rmbz-vip .rvd-somas-native .rmbz-licensing-status h3{ margin:0; color:var(--text); font-size:12px; }
    #rmbz-vip .rvd-somas-native .rmbz-licensing-status p{ margin:0; color:var(--text2); font-size:11.5px; line-height:1.5; }
    #rmbz-vip .rvd-somas-native .rmbz-licensing-status__note{ color:var(--muted); font-size:10.5px; }
    @media (max-width:700px){ #rmbz-vip .rvd-somas-native .rmbz-somas-chooser__options{ grid-template-columns:1fr; } #rmbz-vip .rvd-somas-native .rmbz-somas-form{ grid-template-columns:1fr; padding:13px; } #rmbz-vip .rvd-somas-native .rmbz-somas-fieldset--half{ grid-column:1; } #rmbz-vip .rvd-somas-native .rmbz-somas-grid{ grid-template-columns:1fr; } #rmbz-vip .rvd-somas-native .rmbz-somas-grid__full{ grid-column:1; } #rmbz-vip .rvd-somas-native .rmbz-somas-actions{ flex-direction:column; align-items:stretch; } #rmbz-vip .rvd-somas-native .rmbz-somas-actions .rmbz-btn{ width:100%; order:1; } #rmbz-vip .rvd-somas-native .rmbz-somas-disclaimer{ order:2; } }
    /* [1.5.489] Escala tipográfica legível nas áreas modernas do painel. */
    #rmbz-vip :is(
        .home-card-eyebrow,.home-finance-label,.home-work-label,
        .shoot-eyebrow,.shoot-date-label,.shoot-complete-kicker,
        .location-option-label,.project-kicker,.project-stage-kicker,
        .project-team-origin,.project-metric-label,.project-chat-sender,
        .distro-summary-label,.release-hero-metric-label,.release-tracker-kicker,
        .release-link-label,.release-data-label,.release-territories strong,
        .account-restrictions-kicker,.account-restriction-label,
        .fine-debt-kicker,.fine-debt-status,.fine-debt-amount-label,
        .fine-pay-kicker,.fine-pay-summary-label,.fine-pay-label
    ){ font-size:11px !important; }
    #rmbz-vip :is(
        .home-panel-subtitle,.home-panel-link,.home-project-meta,.home-project-status,
        .home-empty small,.home-utility-badge,.project-stage-step-label,
        .project-team-role,.project-filming-live-badge,.project-filming-summary,
        .project-filming-day-meta,.project-filming-result,.project-filming-person-role,
        .project-chat-delete,.project-chat-event-meta,.project-chat-live,
        .project-chat-upload-meta,.distro-dsp-text,.distro-catalog-subtitle,
        .distro-catalog-count,.distro-release-status,.distro-release-type,
        .distro-quick-text,.release-status,.release-meta-chip,.release-license-subtitle,
        .release-license-registration-copy p,.release-tracker-state,
        .release-tracker-step-title,.release-tracker-step-sub,.release-listen-note,
        .release-store-chip,.release-history-subtitle,.release-event-text,
        .release-event-time,.release-event-reason,.release-section-subtitle,
        .release-link-value,.release-profile-state span:last-child,
        .release-profile-action,.release-track-isrc,.release-track-duration,
        .release-dsp-chip,.release-territories,.release-service-status,
        .release-service-body,.release-service-note
    ){ font-size:11.5px !important; }
    #rmbz-vip :is(.status,.chip){ font-size:11px !important; }
    #rmbz-vip .pill{ font-size:11.5px !important; }
    #rmbz-vip .stats-toolbar{ display:flex; align-items:flex-end; justify-content:space-between; gap:16px; flex-wrap:wrap; margin-bottom:15px; }
    #rmbz-vip .stats-toolbar-copy{ min-width:220px; }
    #rmbz-vip .stats-toolbar-title{ color:var(--text); font-family:'Bricolage Grotesque',sans-serif; font-size:20px; line-height:1.2; font-weight:780; letter-spacing:-.02em; }
    #rmbz-vip .stats-toolbar-subtitle{ margin-top:4px; color:var(--muted); font-size:11.5px; line-height:1.5; }
    #rmbz-vip .stats-toolbar-actions{ display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
    #rmbz-vip .stats-range{ min-height:38px; display:inline-flex; align-items:center; gap:6px; padding:8px 11px; border-radius:100px; background:var(--brand-soft); color:var(--brand-ink); font-size:11px; font-weight:750; }
    #rmbz-vip .stats-range.custom{ background:var(--info-soft); color:var(--info); }
    #rmbz-vip .stats-filter-action{ min-height:38px; border:1px solid var(--border2); background:var(--surface); color:var(--text2); }
    #rmbz-vip .stats-error{ display:flex; align-items:center; gap:9px; margin-bottom:14px; padding:11px 14px; border-radius:14px; background:var(--danger-soft); color:var(--danger); font-size:11.5px; font-weight:650; }
    #rmbz-vip .stats-insight-hero{ display:grid; grid-template-columns:50px minmax(0,1fr); gap:15px; align-items:center; margin-bottom:14px; padding:21px 23px; border-radius:24px; background:linear-gradient(125deg,var(--navy),#253c57); color:#fff; }
    #rmbz-vip .stats-insight-icon{ width:50px; height:50px; display:flex; align-items:center; justify-content:center; border-radius:16px; background:rgba(255,255,255,.12); color:#f0b90b; font-size:26px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .stats-insight-title{ font-family:'Bricolage Grotesque',sans-serif; font-size:19px; line-height:1.3; font-weight:750; }
    #rmbz-vip .stats-insight-summary{ margin-top:5px; color:rgba(255,255,255,.76); font-size:12px; line-height:1.6; }
    #rmbz-vip .stats-metric-grid{ display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:12px; }
    #rmbz-vip .stats-metric-card{ min-width:0; padding:17px; border:1px solid var(--border); border-radius:20px; background:var(--surface); }
    #rmbz-vip .stats-metric-head{ display:flex; align-items:center; gap:9px; }
    #rmbz-vip .stats-metric-icon{ width:36px; height:36px; display:flex; align-items:center; justify-content:center; flex:0 0 36px; border-radius:12px; background:var(--stat-soft,var(--brand-soft)); color:var(--stat-tone,var(--brand-ink)); font-size:19px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .stats-metric-label{ color:var(--muted); font-size:10px; font-weight:800; letter-spacing:.07em; text-transform:uppercase; }
    #rmbz-vip .stats-metric-value{ margin-top:13px; overflow:hidden; color:var(--stat-tone,var(--text)); font-family:'JetBrains Mono',monospace; font-size:25px; line-height:1.15; font-weight:700; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .stats-metric-detail{ min-height:16px; margin-top:6px; color:var(--muted); font-size:10.5px; line-height:1.45; }
    #rmbz-vip .stats-metric-detail.trend{ display:flex; align-items:center; gap:4px; color:var(--stat-tone,var(--muted)); }
    #rmbz-vip .stats-highlight-grid{ display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:12px; margin-top:12px; }
    #rmbz-vip .stats-highlight-card{ display:grid; grid-template-columns:40px minmax(0,1fr); gap:11px; align-items:center; padding:14px; border:1px solid var(--border); border-radius:18px; background:var(--surface); }
    #rmbz-vip .stats-highlight-icon{ width:40px; height:40px; display:flex; align-items:center; justify-content:center; border-radius:13px; background:var(--brand-soft); color:var(--brand-ink); font-size:21px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .stats-highlight-label{ color:var(--muted); font-size:9.5px; font-weight:800; letter-spacing:.06em; text-transform:uppercase; }
    #rmbz-vip .stats-highlight-value{ margin-top:3px; overflow:hidden; color:var(--text); font-size:13px; font-weight:750; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .stats-highlight-detail{ margin-top:2px; color:var(--muted); font-size:10px; }
    #rmbz-vip .stats-activity-hero{ display:grid; grid-template-columns:56px minmax(0,1fr) auto; gap:15px; align-items:center; margin-bottom:13px; padding:20px 22px; border:1px solid var(--border); border-radius:24px; background:linear-gradient(120deg,var(--brand-soft),var(--surface)); }
    #rmbz-vip .stats-activity-hero-icon{ width:56px; height:56px; display:flex; align-items:center; justify-content:center; border-radius:18px; background:var(--brand); color:var(--on-brand); font-size:28px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .stats-activity-hero-title{ color:var(--text); font-family:'Bricolage Grotesque',sans-serif; font-size:19px; font-weight:780; }
    #rmbz-vip .stats-activity-hero-copy{ margin-top:4px; color:var(--text2); font-size:11.5px; line-height:1.55; }
    #rmbz-vip .stats-activity-hero-badge{ display:inline-flex; align-items:center; gap:5px; padding:7px 10px; border-radius:100px; background:var(--surface); color:var(--brand-ink); font-size:10.5px; font-weight:750; white-space:nowrap; }
    #rmbz-vip .stats-activity-grid{ display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:11px; }
    #rmbz-vip .stats-activity-card{ min-width:0; display:grid; grid-template-columns:42px minmax(0,1fr) 22px; gap:11px; align-items:center; padding:14px; border:1px solid var(--border); border-radius:18px; background:var(--surface); color:var(--text); font-family:inherit; text-align:left; cursor:pointer; }
    #rmbz-vip .stats-activity-card:hover{ border-color:var(--activity-tone,var(--brand)); background:var(--hover); }
    #rmbz-vip .stats-activity-icon{ width:42px; height:42px; display:flex; align-items:center; justify-content:center; border-radius:13px; background:var(--activity-soft,var(--brand-soft)); color:var(--activity-tone,var(--brand-ink)); font-size:21px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .stats-activity-content{ min-width:0; display:flex; flex-direction:column; align-items:flex-start; justify-content:center; line-height:1.2; }
    #rmbz-vip .stats-activity-label{ display:block; width:100%; overflow:hidden; color:var(--muted); font-size:9.5px; font-weight:750; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .stats-activity-value{ display:block; width:100%; margin-top:3px; overflow:hidden; color:var(--text); font-size:16px; line-height:1.2; font-weight:820; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .stats-activity-detail{ display:block; width:100%; margin-top:3px; overflow:hidden; color:var(--muted); font-size:9.5px; line-height:1.35; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .stats-activity-arrow{ color:var(--muted); font-size:19px; }
    #rmbz-vip .stats-ai-card{ margin-top:16px; padding:17px 18px; border:1px solid var(--border); border-radius:21px; background:var(--surface); }
    #rmbz-vip .stats-ai-head{ display:flex; align-items:center; gap:12px; flex-wrap:wrap; }
    #rmbz-vip .stats-ai-icon{ width:44px; height:44px; display:flex; align-items:center; justify-content:center; border-radius:14px; background:var(--brand-soft); color:var(--brand-ink); font-size:23px; }
    #rmbz-vip .stats-ai-copy{ flex:1; min-width:220px; }
    #rmbz-vip .stats-ai-title{ font-size:14px; font-weight:800; }
    #rmbz-vip .stats-ai-subtitle{ margin-top:2px; color:var(--muted); font-size:11px; }
    #rmbz-vip .stats-achievements{ margin-top:16px; padding:18px; border:1px solid var(--border); border-radius:23px; background:var(--surface); }
    #rmbz-vip .stats-achievements-head{ display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; margin-bottom:11px; }
    #rmbz-vip .stats-achievements-title{ color:var(--text); font-size:14px; font-weight:800; }
    #rmbz-vip .stats-achievements-subtitle{ margin-top:2px; color:var(--muted); font-size:10.5px; }
    #rmbz-vip .stats-achievement-group{ border-top:1px solid var(--border); }
    #rmbz-vip .stats-achievement-group>summary{ min-height:48px; list-style:none; display:flex; align-items:center; gap:9px; padding:9px 3px; cursor:pointer; }
    #rmbz-vip .stats-achievement-group>summary::-webkit-details-marker{ display:none; }
    #rmbz-vip .stats-achievement-group-icon{ width:32px; height:32px; display:flex; align-items:center; justify-content:center; border-radius:10px; background:var(--elev); color:var(--brand-ink); font-size:17px; }
    #rmbz-vip .stats-achievement-group-name{ flex:1; color:var(--text); font-size:11.5px; font-weight:780; }
    #rmbz-vip .stats-achievement-group-count{ color:var(--muted); font-size:10px; }
    #rmbz-vip .stats-achievement-chevron{ color:var(--muted); font-size:19px; transition:transform .16s; }
    #rmbz-vip .stats-achievement-group[open] .stats-achievement-chevron{ transform:rotate(180deg); }
    #rmbz-vip .stats-achievement-grid{ display:grid; grid-template-columns:repeat(auto-fill,minmax(220px,1fr)); gap:9px; padding:2px 0 13px; }
    #rmbz-vip .stats-achievement-card{ min-width:0; display:grid; grid-template-columns:38px minmax(0,1fr); gap:10px; padding:12px; border:1px solid var(--border); border-radius:15px; background:var(--elev); }
    #rmbz-vip .stats-achievement-card.achieved{ border-color:color-mix(in srgb,var(--brand) 72%,var(--border)); }
    #rmbz-vip .stats-achievement-icon{ width:38px; height:38px; display:flex; align-items:center; justify-content:center; border-radius:12px; background:var(--surface); color:var(--muted); font-size:19px; }
    #rmbz-vip .stats-achievement-card.achieved .stats-achievement-icon{ background:var(--brand); color:var(--on-brand); }
    #rmbz-vip .stats-achievement-title{ color:var(--text); font-size:11px; font-weight:750; }
    #rmbz-vip .stats-achievement-description{ margin-top:2px; color:var(--muted); font-size:9.5px; line-height:1.4; }
    #rmbz-vip .stats-achievement-progress{ height:5px; overflow:hidden; margin-top:8px; border-radius:10px; background:var(--surface); }
    #rmbz-vip .stats-achievement-progress>span{ height:100%; display:block; border-radius:inherit; background:var(--info); }
    #rmbz-vip .stats-achievement-card.achieved .stats-achievement-progress>span{ background:var(--brand); }
    #rmbz-vip .stats-achievement-meta{ margin-top:4px; color:var(--muted); font-size:9px; }
    @media(max-width:900px){ #rmbz-vip .stats-metric-grid,#rmbz-vip .stats-highlight-grid,#rmbz-vip .stats-activity-grid{ grid-template-columns:repeat(2,minmax(0,1fr)); } }
    @media(max-width:600px){ #rmbz-vip .stats-toolbar{ align-items:flex-start; } #rmbz-vip .stats-toolbar-actions{ width:100%; } #rmbz-vip .stats-filter-action{ flex:1; } #rmbz-vip .stats-insight-hero{ grid-template-columns:43px minmax(0,1fr); padding:17px; } #rmbz-vip .stats-insight-icon{ width:43px; height:43px; font-size:22px; } #rmbz-vip .stats-metric-grid,#rmbz-vip .stats-highlight-grid,#rmbz-vip .stats-activity-grid{ grid-template-columns:1fr; } #rmbz-vip .stats-activity-hero{ grid-template-columns:50px minmax(0,1fr); padding:17px; } #rmbz-vip .stats-activity-hero-icon{ width:50px; height:50px; font-size:25px; } #rmbz-vip .stats-activity-hero-badge{ grid-column:2; justify-self:start; } #rmbz-vip .stats-achievements{ padding:15px; } }
    @keyframes rmbzVipIn{ from{ opacity:0; transform:translateY(10px);} to{ opacity:1; transform:none; } }
    @keyframes rmbzVipPop{ from{ opacity:0; transform:scale(.95);} to{ opacity:1; transform:none; } }
    @keyframes rmbzVipRec{ 50%{ opacity:.25; } }
    /* [1.5.416] Formulário de envio nativo (rvu-*) */
    #rmbz-vip .rvu-lbl{ display:block; font-size:12px; font-weight:650; color:var(--text2); margin-bottom:6px; }
    #rmbz-vip .rvu-type:hover{ border-color:var(--brand); transform:translateY(-2px); }
    #rmbz-vip .rvu-type.on{ border-color:var(--brand); background:var(--brand-soft); }
    #rmbz-vip .rvu-yn{ display:flex; gap:8px; }
    #rmbz-vip .rvu-yn label{ flex:1; display:flex; align-items:center; justify-content:center; gap:8px; min-height:46px; padding:11px 14px; border:1.5px solid var(--border); background:var(--elev); border-radius:100px; font-size:14px; font-weight:600; color:var(--text2); cursor:pointer; transition:.15s; }
    #rmbz-vip .rvu-yn input{ position:absolute; opacity:0; width:0; height:0; }
    #rmbz-vip .rvu-yn label:has(input:checked){ background:var(--brand-soft); border-color:var(--brand); color:var(--brand-ink); }
    #rmbz-vip .rvu-drop{ border:2px dashed var(--border2); border-radius:16px; padding:24px 16px; text-align:center; cursor:pointer; background:var(--elev); transition:.2s; display:flex; flex-direction:column; align-items:center; gap:6px; }
    #rmbz-vip .rvu-drop:hover{ border-color:var(--brand); background:var(--hover); }
    #rmbz-vip .rvu-prev{ margin-top:8px; font-size:12px; color:var(--success); }
    #rmbz-vip .rvu-prev img{ max-width:100px; max-height:100px; border-radius:10px; display:block; margin-bottom:4px; }
    #rmbz-vip .rvu-audio{ border:2px dashed var(--border2); border-radius:16px; padding:28px 16px; text-align:center; cursor:pointer; background:var(--elev); transition:.2s; }
    #rmbz-vip .rvu-audio:hover{ border-color:var(--brand); background:var(--hover); }
    #rmbz-vip .rvu-chk{ display:flex; align-items:flex-start; gap:12px; margin-top:10px; padding:13px 15px; border:1.5px solid var(--border); background:var(--elev); border-radius:14px; font-size:13px; color:var(--text2); line-height:1.5; cursor:pointer; }
    #rmbz-vip .rvu-chk input{ width:20px; height:20px; flex:0 0 20px; margin-top:1px; accent-color:var(--brand); cursor:pointer; }
    #rmbz-vip .rvu-chk:has(input:checked){ background:var(--brand-soft); border-color:var(--brand); }
    #rmbz-vip .rvu-scen.on{ border-color:var(--brand); background:var(--brand-soft); }
    #rmbz-vip .rvu-page-head{ display:flex; align-items:center; gap:16px; padding:20px 22px; flex-wrap:wrap; }
    #rmbz-vip .rvu-page-head-icon{ width:52px; height:52px; flex:0 0 52px; border-radius:17px; display:flex; align-items:center; justify-content:center; background:var(--brand-soft); color:var(--brand-ink); }
    #rmbz-vip .rvu-page-head-icon .ms{ font-size:27px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .rvu-list-toolbar{ display:flex; align-items:center; justify-content:space-between; gap:16px; flex-wrap:wrap; margin:4px 0 12px; }
    #rmbz-vip .rvu-kind-filter{ display:flex; align-items:center; gap:7px; padding:5px; border:1px solid var(--border); border-radius:100px; background:var(--surface); overflow-x:auto; }
    #rmbz-vip .rvu-kind{ display:inline-flex; align-items:center; gap:6px; flex:0 0 auto; min-height:34px; padding:7px 11px; border-radius:100px; color:var(--text2); font-size:11.5px; font-weight:700; text-decoration:none; }
    #rmbz-vip .rvu-kind .ms{ font-size:16px; }
    #rmbz-vip .rvu-kind .mono{ min-width:20px; height:20px; padding:0 5px; border-radius:10px; display:inline-flex; align-items:center; justify-content:center; background:var(--elev); color:var(--muted); font-size:9.5px; }
    #rmbz-vip .rvu-kind.on{ background:var(--brand); color:var(--on-brand); }
    #rmbz-vip .rvu-kind.on .mono{ background:rgba(0,0,0,.14); color:inherit; }
    #rmbz-vip .rvu-sub-card{ display:flex; align-items:center; gap:16px; padding:15px 18px; flex-wrap:wrap; border-radius:20px; transition:border-color .16s ease,transform .16s ease; }
    #rmbz-vip .rvu-sub-card:hover{ border-color:var(--border2); transform:translateY(-1px); }
    #rmbz-vip .rvu-sub-cover{ position:relative; width:62px; height:62px; flex:0 0 62px; border-radius:17px; display:flex; align-items:center; justify-content:center; background:var(--brand-soft); color:var(--brand-ink); }
    #rmbz-vip .rvu-sub-cover>img{ width:100%; height:100%; object-fit:cover; border-radius:17px; display:block; }
    #rmbz-vip .rvu-sub-cover>.ms:not(.rvu-sub-destination){ font-size:28px; }
    #rmbz-vip .rvu-sub-destination{ position:absolute; right:-5px; bottom:-5px; width:24px; height:24px; border:3px solid var(--surface); border-radius:50%; align-items:center; justify-content:center; background:var(--brand); color:var(--on-brand); font-size:13px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .rvu-sub-main{ flex:1; min-width:190px; }
    #rmbz-vip .rvu-sub-kind{ display:flex; align-items:center; gap:5px; color:var(--brand-ink); font-size:9.5px; line-height:1; font-weight:800; letter-spacing:.08em; }
    #rmbz-vip .rvu-sub-kind .ms{ font-size:14px; }
    #rmbz-vip .rvu-sub-actions{ display:flex; align-items:center; justify-content:flex-end; gap:8px; flex-wrap:wrap; }
    #rmbz-vip .rvu-sub-actions .chip{ display:inline-flex; align-items:center; gap:6px; }
    #rmbz-vip .rvu-brand-icon{ display:inline-block; flex:0 0 auto; vertical-align:-3px; }
    #rmbz-vip .wd-source-grid{ display:grid; grid-template-columns:1fr 1fr; gap:10px; margin:12px 0 16px; }
    #rmbz-vip .wd-source{ display:flex; align-items:center; gap:12px; min-height:86px; padding:13px 14px; border:1.5px solid var(--border2); border-radius:18px; background:var(--elev); color:var(--text); font-family:inherit; text-align:left; cursor:pointer; }
    #rmbz-vip .wd-source.on{ border-color:var(--brand); background:var(--brand-soft); }
    #rmbz-vip .wd-source:disabled{ opacity:.45; cursor:not-allowed; }
    #rmbz-vip .wd-source-icon{ width:40px; height:40px; border-radius:13px; align-items:center; justify-content:center; flex:0 0 40px; background:var(--surface); color:var(--brand-ink); font-size:21px; }
    #rmbz-vip .wd-contact{ display:flex; align-items:center; gap:8px; padding:8px 11px; border:1px solid var(--border); border-radius:12px; background:var(--elev); color:var(--text2); font-family:inherit; font-size:11.5px; cursor:pointer; }
    #rmbz-vip textarea.inp{ font-family:inherit; resize:vertical; min-height:90px; }
    #rmbz-vip .account-restrictions{ margin:0 0 18px; padding:20px; border:1px solid var(--border); border-radius:26px; background:var(--surface); box-shadow:0 1px 2px rgba(0,0,0,.04); }
    #rmbz-vip .account-restrictions-head{ display:flex; align-items:center; gap:13px; margin-bottom:16px; }
    #rmbz-vip .account-restrictions-head-icon{ width:46px; height:46px; flex:0 0 46px; align-items:center; justify-content:center; border-radius:15px; background:var(--danger-soft); color:var(--danger); font-size:23px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .account-restrictions-copy{ flex:1; min-width:0; }
    #rmbz-vip .account-restrictions-kicker{ color:var(--danger); font-size:10px; line-height:1.2; font-weight:800; letter-spacing:.09em; text-transform:uppercase; }
    #rmbz-vip .account-restrictions-title{ margin-top:3px; color:var(--text); font-size:17px; line-height:1.25; font-weight:780; }
    #rmbz-vip .account-restrictions-subtitle{ margin-top:3px; color:var(--muted); font-size:12px; line-height:1.45; }
    #rmbz-vip .account-restrictions-count{ display:inline-flex; align-items:center; min-height:30px; padding:6px 11px; border-radius:100px; background:var(--danger-soft); color:var(--danger); font-size:10.5px; font-weight:800; white-space:nowrap; }
    #rmbz-vip .account-restrictions-grid{ display:grid; grid-template-columns:repeat(auto-fit,minmax(300px,1fr)); gap:12px; }
    #rmbz-vip .account-restriction{ display:grid; grid-template-columns:46px minmax(0,1fr) auto; gap:0 13px; min-height:138px; padding:16px; border:1px solid var(--border); border-radius:20px; background:var(--elev); }
    #rmbz-vip .account-restriction-icon{ width:46px; height:46px; grid-row:1 / span 2; align-items:center; justify-content:center; border-radius:15px; background:var(--surface); color:var(--danger); font-size:23px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .account-restriction-main{ min-width:0; align-self:center; }
    #rmbz-vip .account-restriction-label{ color:var(--muted); font-size:9.5px; line-height:1.2; font-weight:800; letter-spacing:.08em; text-transform:uppercase; }
    #rmbz-vip .account-restriction-title{ margin-top:4px; color:var(--text); font-size:14px; line-height:1.3; font-weight:760; }
    #rmbz-vip .account-restriction-state{ align-self:start; display:inline-flex; align-items:center; gap:5px; min-height:28px; padding:5px 9px; border-radius:100px; background:var(--danger-soft); color:var(--danger); font-size:10px; font-weight:780; white-space:nowrap; }
    #rmbz-vip .account-restriction-state .ms{ font-size:14px; }
    #rmbz-vip .account-restriction-detail{ grid-column:2 / -1; margin-top:12px; padding-top:11px; border-top:1px solid var(--border); color:var(--text2); font-size:11.5px; line-height:1.5; }
    #rmbz-vip .account-restriction-meta{ display:flex; align-items:center; gap:7px; margin-top:9px; color:var(--muted); font-size:10.5px; line-height:1.35; }
    #rmbz-vip .account-restriction-meta>.ms{ color:var(--danger); font-size:16px; }
    #rmbz-vip .account-restriction-meta b{ color:var(--text); font-weight:700; }
    #rmbz-vip .account-restriction-support{ display:inline-flex; align-items:center; gap:5px; margin-left:auto; color:var(--brand-ink); font-size:10.5px; font-weight:750; white-space:nowrap; }
    #rmbz-vip .account-restriction-support .ms{ font-size:15px; }
    #rmbz-vip .fine-debt-card{ position:relative; display:grid; grid-template-columns:54px minmax(0,1fr) auto; gap:15px; align-items:start; margin-bottom:18px; padding:19px; overflow:hidden; border:1px solid color-mix(in srgb,var(--danger) 30%,var(--border)); border-radius:25px; background:linear-gradient(130deg,var(--danger-soft),var(--surface) 56%); box-shadow:0 8px 30px -28px rgba(0,0,0,.72); }
    #rmbz-vip .fine-debt-card::before{ content:''; position:absolute; inset:0 auto 0 0; width:4px; background:var(--danger); }
    #rmbz-vip .fine-debt-icon{ position:relative; width:54px; height:54px; align-items:center; justify-content:center; border-radius:18px; background:var(--danger); color:#fff; font-size:27px; font-variation-settings:'FILL' 1; box-shadow:0 12px 26px -20px var(--danger); }
    #rmbz-vip .fine-debt-content{ position:relative; min-width:0; }
    #rmbz-vip .fine-debt-heading{ display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
    #rmbz-vip .fine-debt-kicker{ color:var(--danger); font-size:9.5px; line-height:1.2; font-weight:800; letter-spacing:.09em; text-transform:uppercase; }
    #rmbz-vip .fine-debt-status{ display:inline-flex; align-items:center; gap:4px; min-height:25px; padding:4px 8px; border-radius:100px; background:var(--surface); color:var(--danger); font-size:9.5px; font-weight:780; white-space:nowrap; }
    #rmbz-vip .fine-debt-status .ms{ font-size:13px; }
    #rmbz-vip .fine-debt-title{ margin-top:5px; color:var(--text); font-family:'Bricolage Grotesque',sans-serif; font-size:17px; line-height:1.3; font-weight:780; }
    #rmbz-vip .fine-debt-description{ max-width:760px; margin-top:5px; color:var(--text2); font-size:11.5px; line-height:1.55; }
    #rmbz-vip .fine-debt-facts{ display:flex; align-items:center; gap:7px; flex-wrap:wrap; margin-top:12px; }
    #rmbz-vip .fine-debt-fact{ display:inline-flex; align-items:center; gap:5px; min-height:29px; max-width:100%; padding:5px 9px; border:1px solid var(--border); border-radius:10px; background:var(--surface); color:var(--text2); font-size:10.5px; line-height:1.35; }
    #rmbz-vip .fine-debt-fact .ms{ flex:0 0 auto; color:var(--danger); font-size:15px; }
    #rmbz-vip .fine-debt-fact b{ overflow:hidden; color:var(--text); font-weight:700; text-overflow:ellipsis; white-space:nowrap; }
    #rmbz-vip .fine-debt-side{ position:relative; min-width:190px; display:flex; flex-direction:column; align-items:flex-end; }
    #rmbz-vip .fine-debt-amount-label{ color:var(--muted); font-size:9.5px; line-height:1.2; font-weight:780; letter-spacing:.07em; text-transform:uppercase; }
    #rmbz-vip .fine-debt-amount{ margin-top:5px; color:var(--danger); font-family:'JetBrains Mono',monospace; font-size:24px; line-height:1.1; font-weight:750; white-space:nowrap; }
    #rmbz-vip .fine-debt-amount small{ color:var(--danger); font-family:'Geist',system-ui,sans-serif; font-size:11px; font-weight:750; }
    #rmbz-vip .fine-debt-action{ min-height:42px; margin-top:12px; justify-content:center; background:var(--danger); color:#fff; font-size:11.5px; box-shadow:0 10px 24px -18px var(--danger); }
    #rmbz-vip .fine-debt-action .ms{ font-size:17px; }
    #rmbz-vip .fine-pay-dialog{ width:440px; padding:22px; }
    #rmbz-vip .fine-pay-head{ display:flex; align-items:center; gap:12px; }
    #rmbz-vip .fine-pay-head-icon{ width:44px; height:44px; flex:0 0 44px; align-items:center; justify-content:center; border-radius:15px; background:var(--danger-soft); color:var(--danger); font-size:22px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .fine-pay-head-copy{ flex:1; min-width:0; }
    #rmbz-vip .fine-pay-kicker{ color:var(--muted); font-size:9px; font-weight:800; letter-spacing:.09em; text-transform:uppercase; }
    #rmbz-vip .fine-pay-title{ margin-top:3px; color:var(--text); font-family:'Bricolage Grotesque',sans-serif; font-size:18px; line-height:1.25; font-weight:780; }
    #rmbz-vip .fine-pay-close{ width:36px; height:36px; flex:0 0 36px; display:flex; align-items:center; justify-content:center; padding:0; border:0; border-radius:50%; background:var(--elev); color:var(--muted); cursor:pointer; }
    #rmbz-vip .fine-pay-summary{ margin-top:17px; padding:17px; border:1px solid color-mix(in srgb,var(--danger) 24%,var(--border)); border-radius:19px; background:linear-gradient(135deg,var(--danger-soft),var(--elev)); }
    #rmbz-vip .fine-pay-summary-label{ color:var(--muted); font-size:9.5px; font-weight:780; letter-spacing:.07em; text-transform:uppercase; }
    #rmbz-vip .fine-pay-summary-value{ margin-top:5px; color:var(--danger); font-family:'JetBrains Mono',monospace; font-size:28px; line-height:1.1; font-weight:750; }
    #rmbz-vip .fine-pay-summary-value small{ font-family:'Geist',system-ui,sans-serif; font-size:11px; }
    #rmbz-vip .fine-pay-wallet{ display:flex; align-items:center; justify-content:space-between; gap:12px; margin-top:11px; padding-top:11px; border-top:1px solid var(--border); color:var(--text2); font-size:11px; }
    #rmbz-vip .fine-pay-wallet span{ display:inline-flex; align-items:center; gap:5px; }
    #rmbz-vip .fine-pay-wallet .ms{ color:var(--brand-ink); font-size:16px; }
    #rmbz-vip .fine-pay-wallet b{ color:var(--text); font-family:'JetBrains Mono',monospace; }
    #rmbz-vip .fine-pay-note{ margin:14px 0; color:var(--text2); font-size:11.5px; line-height:1.55; }
    #rmbz-vip .fine-pay-balance-warning{ display:flex; align-items:flex-start; gap:8px; margin:12px 0; padding:11px 12px; border-radius:14px; background:var(--rev-soft); color:var(--text2); font-size:11px; line-height:1.45; }
    #rmbz-vip .fine-pay-balance-warning .ms{ margin-top:1px; color:var(--rev); font-size:17px; }
    #rmbz-vip .fine-pay-label{ display:block; margin:0 0 6px; color:var(--muted); font-size:10px; font-weight:750; letter-spacing:.06em; text-transform:uppercase; }
    #rmbz-vip .fine-pay-submit{ width:100%; min-height:46px; margin-top:12px; justify-content:center; background:var(--danger); color:#fff; }
    #rmbz-vip .fine-pay-submit .ms{ font-size:18px; }
    #rmbz-vip .service-access-gate{ position:relative; isolation:isolate; min-height:510px; display:grid; place-items:center; overflow:hidden; padding:54px 30px; border:1px solid var(--border); border-radius:32px; background:linear-gradient(145deg,color-mix(in srgb,var(--brand-soft) 42%,var(--surface)),var(--surface) 48%,color-mix(in srgb,var(--info-soft) 34%,var(--surface))); box-shadow:0 28px 70px -58px rgba(15,23,42,.8); }
    #rmbz-vip .service-access-aura{ position:absolute; z-index:-1; width:430px; height:430px; top:-230px; right:-110px; border-radius:50%; background:radial-gradient(circle,color-mix(in srgb,var(--brand) 24%,transparent),transparent 68%); pointer-events:none; }
    #rmbz-vip .service-access-content{ width:min(720px,100%); display:flex; flex-direction:column; align-items:center; text-align:center; }
    #rmbz-vip .service-access-badge{ min-height:30px; display:inline-flex; align-items:center; gap:7px; padding:5px 12px; border:1px solid color-mix(in srgb,var(--brand) 34%,var(--border)); border-radius:999px; background:color-mix(in srgb,var(--brand-soft) 72%,var(--surface)); color:var(--brand-ink); font-size:10px; font-weight:820; letter-spacing:.055em; text-transform:uppercase; }
    #rmbz-vip .service-access-badge .ms{ font-size:15px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .service-access-icon{ width:76px; height:76px; display:flex; align-items:center; justify-content:center; margin-top:24px; border-radius:25px; background:var(--brand); color:var(--on-brand); font-size:37px; font-variation-settings:'FILL' 1; box-shadow:0 20px 38px -27px color-mix(in srgb,var(--brand) 78%,#000); }
    #rmbz-vip .service-access-eyebrow{ margin-top:21px; color:var(--brand-ink); font-size:10px; font-weight:850; letter-spacing:.12em; text-transform:uppercase; }
    #rmbz-vip .service-access-title{ max-width:640px; margin:7px 0 0; color:var(--text); font-family:'Bricolage Grotesque',sans-serif; font-size:clamp(25px,3vw,36px); line-height:1.12; font-weight:800; letter-spacing:-.035em; }
    #rmbz-vip .service-access-message{ max-width:620px; margin:13px 0 0; color:var(--text2); font-size:13px; line-height:1.65; }
    #rmbz-vip .service-access-features{ width:100%; display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:9px; margin-top:24px; }
    #rmbz-vip .service-access-features>span{ min-height:52px; display:flex; align-items:center; justify-content:center; gap:8px; padding:10px 12px; border:1px solid var(--border); border-radius:17px; background:color-mix(in srgb,var(--elev) 88%,transparent); color:var(--text2); font-size:11px; font-weight:680; }
    #rmbz-vip .service-access-features .ms{ color:var(--brand-ink); font-size:18px; }
    #rmbz-vip .service-access-actions{ display:flex; justify-content:center; gap:10px; margin-top:24px; flex-wrap:wrap; }
    #rmbz-vip .service-access-primary{ min-height:46px; padding:11px 19px; background:var(--brand); color:var(--on-brand); border:0; box-shadow:0 14px 30px -23px color-mix(in srgb,var(--brand) 85%,#000); }
    #rmbz-vip .service-access-secondary{ min-height:46px; padding:11px 18px; border:1px solid var(--border2); background:var(--surface); color:var(--text2); }
    #rmbz-vip .service-access-actions .ms{ font-size:18px; }
    #rmbz-vip .service-access-foot{ display:flex; align-items:center; justify-content:center; gap:6px; margin-top:20px; color:var(--muted); font-size:10px; }
    #rmbz-vip .service-access-foot .ms{ font-size:15px; }
    #rmbz-vip .artists-native-shell{ min-width:0; }
    #rmbz-vip .artists-native-shell .artist-dashboard{ width:100%; max-width:none; margin:0; }
    #rmbz-vip .artists-native-missing{ min-height:280px; display:grid; place-items:center; padding:30px; border:1px dashed var(--border2); border-radius:24px; background:var(--surface); color:var(--text2); text-align:center; }
    #rmbz-vip .art-track-page{ display:grid; gap:18px; }
    #rmbz-vip .art-track-hero{ display:grid; grid-template-columns:92px minmax(0,1fr) auto; align-items:center; gap:20px; padding:22px; overflow:hidden; position:relative; }
    #rmbz-vip .art-track-hero:after{ content:""; position:absolute; inset:0 0 auto; height:3px; background:linear-gradient(90deg,var(--brand),#d3a900,var(--success)); }
    #rmbz-vip .art-track-avatar{ width:92px; height:92px; border-radius:27px; overflow:hidden; display:grid; place-items:center; background:var(--brand); color:#17120a; font:800 32px 'Bricolage Grotesque',sans-serif; box-shadow:inset 0 0 0 1px rgba(255,255,255,.28); }
    #rmbz-vip .art-track-avatar img{ width:100%; height:100%; object-fit:cover; }
    #rmbz-vip .art-track-label,#rmbz-vip .art-track-eyebrow{ color:var(--brand-ink); font-size:10.5px; font-weight:800; letter-spacing:.1em; }
    #rmbz-vip .art-track-label{ display:flex; align-items:center; gap:5px; }
    #rmbz-vip .art-track-label .ms{ font-size:16px; font-variation-settings:'FILL' 1; }
    #rmbz-vip .art-track-identity h2{ margin:5px 0 3px; font-size:25px; }
    #rmbz-vip .art-track-identity>p{ margin:0; color:var(--muted); font-size:12.5px; }
    #rmbz-vip .art-track-tags{ display:flex; gap:7px; flex-wrap:wrap; margin-top:11px; }
    #rmbz-vip .art-track-tags span{ padding:5px 9px; border-radius:999px; background:var(--elev); border:1px solid var(--border); color:var(--text2); font-size:10.5px; font-weight:650; }
    #rmbz-vip .art-track-linked{ display:flex; align-items:center; gap:9px; padding:11px 13px; border-radius:15px; background:var(--success-soft); color:var(--success); }
    #rmbz-vip .art-track-linked .ms{ font-size:21px; }
    #rmbz-vip .art-track-linked strong,#rmbz-vip .art-track-linked small{ display:block; }
    #rmbz-vip .art-track-linked strong{ font-size:11.5px; } #rmbz-vip .art-track-linked small{ margin-top:2px; font-size:9.5px; opacity:.8; }
    #rmbz-vip .art-track-metrics{ display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:12px; }
    #rmbz-vip .art-track-metrics article{ display:flex; align-items:center; gap:13px; padding:16px; }
    #rmbz-vip .art-track-metrics article>.ms{ width:42px; height:42px; border-radius:14px; display:grid; place-items:center; background:var(--brand-soft); color:var(--brand-ink); font-size:22px; }
    #rmbz-vip .art-track-metrics small{ display:block; color:var(--muted); font-size:9px; font-weight:800; letter-spacing:.07em; }
    #rmbz-vip .art-track-metrics strong{ display:block; margin-top:3px; font:750 20px 'JetBrains Mono',monospace; }
    #rmbz-vip .art-track-metrics p{ margin:2px 0 0; color:var(--muted); font-size:9.5px; }
    #rmbz-vip .art-track-catalog{ padding:22px; }
    #rmbz-vip .art-track-catalog-head{ display:flex; align-items:flex-end; justify-content:space-between; gap:16px; padding-bottom:17px; border-bottom:1px solid var(--border); }
    #rmbz-vip .art-track-catalog-head h3{ margin:4px 0 2px; font-size:18px; } #rmbz-vip .art-track-catalog-head p{ margin:0; color:var(--muted); font-size:11.5px; }
    #rmbz-vip .art-track-search{ width:min(280px,100%); display:flex; align-items:center; gap:8px; padding:0 12px; border:1px solid var(--border2); border-radius:14px; background:var(--elev); }
    #rmbz-vip .art-track-search .ms{ color:var(--muted); font-size:19px; } #rmbz-vip .art-track-search input{ width:100%; height:42px; border:0; outline:0; background:transparent; color:var(--text); font:inherit; }
    #rmbz-vip .art-track-list{ display:grid; gap:9px; padding-top:14px; }
    #rmbz-vip .art-track-song{ display:grid; grid-template-columns:58px minmax(0,1fr) auto 150px 112px; align-items:center; gap:13px; padding:10px; border:1px solid var(--border); border-radius:17px; background:var(--elev); transition:border-color .18s,transform .18s; }
    #rmbz-vip .art-track-song[hidden]{ display:none !important; }
    #rmbz-vip .art-track-song:hover{ border-color:var(--brand); transform:translateY(-1px); }
    #rmbz-vip .art-track-song-cover{ width:58px; height:58px; overflow:hidden; border-radius:13px; display:grid; place-items:center; background:var(--surface); color:var(--brand-ink); }
    #rmbz-vip .art-track-song-cover img{ width:100%; height:100%; object-fit:cover; } #rmbz-vip .art-track-song-cover .ms{ font-size:25px; }
    #rmbz-vip .art-track-song-copy h4{ margin:0; font-size:13.5px; } #rmbz-vip .art-track-song-copy p{ margin:4px 0 0; color:var(--muted); font-size:10.5px; }
    #rmbz-vip .art-track-role{ padding:5px 9px; border-radius:999px; font-size:9.5px; font-weight:750; } #rmbz-vip .art-track-role.primary{ background:var(--brand-soft); color:var(--brand-ink); } #rmbz-vip .art-track-role.feat{ background:var(--info-soft); color:var(--info); }
    #rmbz-vip .art-track-song-stats{ display:flex; justify-content:flex-end; gap:11px; color:var(--muted); font:600 10.5px 'JetBrains Mono',monospace; } #rmbz-vip .art-track-song-stats>span{ display:flex; align-items:center; gap:3px; } #rmbz-vip .art-track-song-stats .ms{ font-size:15px; }
    #rmbz-vip .art-track-open{ height:36px; display:flex; align-items:center; justify-content:center; gap:6px; border:1px solid var(--border2); border-radius:12px; color:var(--text); text-decoration:none; font-size:10.5px; font-weight:700; } #rmbz-vip .art-track-open .ms{ font-size:16px; }
    #rmbz-vip .art-track-empty,#rmbz-vip .art-track-catalog-empty{ min-height:250px; display:flex; align-items:center; justify-content:center; gap:18px; padding:32px; text-align:left; } #rmbz-vip .art-track-empty-icon,#rmbz-vip .art-track-catalog-empty>.ms{ width:62px; height:62px; flex:0 0 62px; display:grid; place-items:center; border-radius:20px; background:var(--brand-soft); color:var(--brand-ink); font-size:30px; } #rmbz-vip .art-track-empty h3,#rmbz-vip .art-track-catalog-empty h4{ margin:5px 0; } #rmbz-vip .art-track-empty p,#rmbz-vip .art-track-catalog-empty p{ max-width:580px; margin:0; color:var(--muted); font-size:12px; }
    #rmbz-vip .art-track-catalog-empty{ min-height:220px; text-align:center; flex-direction:column; }
    @media(max-width:1050px){ #rmbz-vip .art-track-metrics{ grid-template-columns:repeat(2,minmax(0,1fr)); } #rmbz-vip .art-track-song{ grid-template-columns:58px minmax(0,1fr) auto 100px; } #rmbz-vip .art-track-song-stats{ display:none; } }
    @media(max-width:700px){ #rmbz-vip .art-track-hero{ grid-template-columns:70px minmax(0,1fr); padding:17px; gap:14px; } #rmbz-vip .art-track-avatar{ width:70px;height:70px;border-radius:21px; } #rmbz-vip .art-track-linked{ grid-column:1/-1; } #rmbz-vip .art-track-metrics{ grid-template-columns:1fr 1fr; } #rmbz-vip .art-track-metrics article{ padding:13px; } #rmbz-vip .art-track-catalog{ padding:15px; } #rmbz-vip .art-track-catalog-head{ align-items:stretch; flex-direction:column; } #rmbz-vip .art-track-search{ width:100%; } #rmbz-vip .art-track-song{ grid-template-columns:50px minmax(0,1fr) auto; gap:10px; } #rmbz-vip .art-track-song-cover{ width:50px;height:50px; } #rmbz-vip .art-track-open{ grid-column:2/-1; } }
    @media (max-width:700px){ #rmbz-vip .fine-debt-card{ grid-template-columns:46px minmax(0,1fr); gap:12px; padding:16px; border-radius:21px; } #rmbz-vip .fine-debt-icon{ width:46px; height:46px; border-radius:15px; font-size:23px; } #rmbz-vip .fine-debt-side{ grid-column:1 / -1; min-width:0; display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:center; gap:11px; width:100%; padding-top:13px; border-top:1px solid var(--border); } #rmbz-vip .fine-debt-amount-label{ grid-column:1; } #rmbz-vip .fine-debt-amount{ grid-column:1; margin-top:-3px; font-size:22px; } #rmbz-vip .fine-debt-action{ grid-column:2; grid-row:1 / span 2; margin-top:0; } }
    @media (max-width:430px){ #rmbz-vip .fine-debt-side{ grid-template-columns:1fr; } #rmbz-vip .fine-debt-action{ grid-column:1; grid-row:auto; width:100%; margin-top:3px; } #rmbz-vip .fine-debt-fact{ width:100%; } }
    @media (max-width:700px){ #rmbz-vip .service-access-gate{ min-height:470px; padding:38px 17px; border-radius:24px; } #rmbz-vip .service-access-icon{ width:66px; height:66px; border-radius:21px; font-size:32px; } #rmbz-vip .service-access-features{ grid-template-columns:1fr; } #rmbz-vip .service-access-features>span{ min-height:46px; justify-content:flex-start; } #rmbz-vip .service-access-actions{ width:100%; } #rmbz-vip .service-access-actions .pill{ width:100%; justify-content:center; } }
    @media (max-width:900px){ #rmbz-vip .aside{ width:76px; } #rmbz-vip .aside .lbl{ display:none; } #rmbz-vip .wrap{ padding:22px 20px 60px; } #rmbz-vip .grid2,#rmbz-vip .grid3,#rmbz-vip .rmbz-vip-detail-grid,#rmbz-vip .rvd-catalog-filter{ grid-template-columns:1fr !important; } #rmbz-vip .rvu-page-head{ align-items:flex-start; } #rmbz-vip .wd-source-grid{ grid-template-columns:1fr; } }
    @media (max-width:600px){ #rmbz-vip .shoot-card,#rmbz-vip .location-card,#rmbz-vip .project-card{ padding:16px; border-radius:20px; } #rmbz-vip .shoot-head,#rmbz-vip .location-head{ align-items:flex-start; flex-wrap:wrap; } #rmbz-vip .shoot-head-copy{ min-width:calc(100% - 58px); } #rmbz-vip .shoot-badge{ margin-left:56px; } #rmbz-vip .shoot-dates,#rmbz-vip .location-options,#rmbz-vip .project-metrics,#rmbz-vip .project-team-grid{ grid-template-columns:1fr; } #rmbz-vip .location-alert{ margin-left:59px; } #rmbz-vip .project-state{ padding:13px; } #rmbz-vip .project-header-side{ width:100%; justify-content:space-between; margin-left:0; } #rmbz-vip .project-badges{ justify-content:flex-start; } #rmbz-vip .project-filming-lock{ min-height:360px; padding:30px 16px; border-radius:20px; } #rmbz-vip .project-filming-day>summary{ align-items:flex-start; flex-wrap:wrap; } #rmbz-vip .project-filming-result{ margin-left:51px; } #rmbz-vip .project-filming-day-body{ padding:0 11px 12px; } #rmbz-vip .account-restrictions{ padding:16px; border-radius:22px; } #rmbz-vip .account-restrictions-head{ align-items:flex-start; flex-wrap:wrap; } #rmbz-vip .account-restrictions-count{ margin-left:59px; } #rmbz-vip .account-restrictions-grid{ grid-template-columns:1fr; } #rmbz-vip .account-restriction{ grid-template-columns:42px minmax(0,1fr); } #rmbz-vip .account-restriction-icon{ width:42px; height:42px; } #rmbz-vip .account-restriction-state{ grid-column:2; margin-top:9px; justify-self:start; } #rmbz-vip .account-restriction-detail{ grid-column:1 / -1; } #rmbz-vip .account-restriction-meta{ align-items:flex-start; flex-wrap:wrap; } #rmbz-vip .account-restriction-support{ width:100%; margin:2px 0 0 23px; } #rmbz-vip .project-stage-panel{ padding:15px; border-radius:19px; } #rmbz-vip .project-stage-head{ align-items:flex-start; flex-wrap:wrap; } #rmbz-vip .project-stage-copy{ min-width:calc(100% - 64px); } #rmbz-vip .project-stage-percent{ margin-left:61px; } #rmbz-vip .project-stage-step-label{ font-size:10px !important; letter-spacing:-.02em; } #rmbz-vip .release-tracker-step-title{ font-size:10px !important; } #rmbz-vip .project-stage-dot{ width:27px; height:27px; font-size:14px; } #rmbz-vip .project-stage-rail{ top:12px; } #rmbz-vip .shoot-complete-card{ align-items:flex-start; padding:17px; border-radius:20px; } #rmbz-vip .shoot-complete-icon{ width:48px; height:48px; flex-basis:48px; border-radius:16px; font-size:25px; } #rmbz-vip .shoot-complete-title{ font-size:16px; } }
    </style>

    <!-- SIDEBAR -->
    <aside class="aside">
        <div style="display:flex; align-items:center; gap:12px; padding:4px 12px 20px;">
            <?php // [1.5.438] Logo REAL da 1MZ na marca da sidebar. ?>
            <img src="<?php echo esc_url( RMBZ_PLUGIN_URL . 'assets/pwa/icon-192.png' ); ?>" alt="1MZ" style="width:42px; height:42px; border-radius:12px; flex-shrink:0; object-fit:cover;">
            <div class="lbl"><div style="font-family:'Bricolage Grotesque',sans-serif; font-size:17px; font-weight:750;">1MZ For Artists</div><div style="font-size:11px; color:var(--muted);">Painel VIP · Desktop</div></div>
        </div>
        <?php
        $navs = [
            [ 'inicio','dashboard','Início',0,false ],
            [ 'musicas','library_music','Músicas & Ganhos',0,! $partnership_access ],
            [ 'arttracks','album','Art Tracks',0,false ],
            [ 'projetos','movie','Videoclipes',0,! $project_access ],
            [ 'distro','public','Distribuição',0,! $distro_access ],
            [ 'envios','upload','Envios',0,! $envios_access ],
            [ 'financas','receipt_long','Finanças',0,false ],
            [ 'stats','monitoring','Estatísticas',0,false ],
            [ 'notifs','notifications','Notificações',$n_por_ler,false ],
            [ 'perfil','person','Perfil & VIP',0,false ],
        ];
        foreach ( $navs as $i => $nv ): ?>
            <button type="button" class="navbtn<?php echo $nv[0] === $vip_sect ? ' on' : ''; ?>" data-nav="<?php echo esc_attr( $nv[0] ); ?>">
                <span class="ms" style="font-size:21px;"><?php echo esc_html( $nv[1] ); ?></span>
                <span class="lbl" style="flex:1;"><?php echo esc_html( $nv[2] ); ?></span>
                <?php if ( $nv[3] > 0 ): ?><span class="lbl" style="background:var(--danger); color:#fff; font-size:10.5px; font-weight:700; border-radius:100px; padding:2px 8px;"><?php echo (int) $nv[3]; ?></span><?php endif; ?>
                <?php if ( ! empty( $nv[4] ) ): ?><span class="ms lbl" title="<?php echo esc_attr( $nv[0] === 'musicas' ? 'Requer aprovação no Programa de Parceria' : 'Não incluído no plano' ); ?>" style="font-size:16px; color:var(--muted);">lock</span><?php endif; ?>
            </button>
        <?php endforeach; ?>

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

        <div class="lbl" style="background:linear-gradient(135deg,var(--vip1),var(--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:.05em;"><span class="ms" style="font-size:18px; color:#f0b90b; font-variation-settings:'FILL' 1;">workspace_premium</span> ARTISTA VIP</div>
            <div style="font-size:11.5px; color:rgba(255,255,255,.75); margin-top:5px;">Renova <?php echo esc_html( $vip_data ); ?> · <?php echo (int) $vip_dias; ?> dias</div>
        </div>

        <button type="button" id="rmbz-vip-theme" class="navbtn" style="border:1px solid var(--border); background:var(--elev);">
            <span class="ms" style="font-size:19px;">light_mode</span><span class="lbl">Tema claro</span>
        </button>

        <form method="post" action="<?php echo esc_url( $post_url ); ?>" style="margin-top:6px;">
            <input type="hidden" name="action" value="rmbz_vip_toggle_layout">
            <input type="hidden" name="vip_on" value="0">
            <?php wp_nonce_field( 'rmbz_vip_layout_nonce' ); ?>
            <button type="submit" class="navbtn" style="width:100%; color:var(--muted); font-size:12px;">
                <span class="ms" style="font-size:18px;">undo</span><span class="lbl">Voltar ao painel antigo</span>
            </button>
        </form>

        <div style="display:flex; align-items:center; gap:11px; padding:10px 12px 2px;">
            <div style="width:38px; height:38px; border-radius:50%; background:var(--brand); color:var(--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 class="lbl" 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(--muted);">+258 <?php echo esc_html( $tel9 ); ?></div></div>
            <a href="<?php echo esc_url( $logout_url ); ?>" class="ms lbl" style="font-size:19px; color:var(--muted);">logout</a>
        </div>
    </aside>

    <!-- MAIN -->
    <main class="main">
        <div class="wrap">
            <?php if ( $notice ): ?>
                <div style="border-radius:16px; padding:13px 20px; margin-bottom:18px; font-size:13.5px; font-weight:650; background:<?php echo $notice[0] === 'error' ? 'var(--danger-soft)' : 'var(--success-soft)'; ?>; color:<?php echo $notice[0] === 'error' ? 'var(--danger)' : 'var(--success)'; ?>;"><?php echo esc_html( $notice[1] ); ?></div>
            <?php endif; ?>

            <?php // ═══ [1.5.415] BANNERS GLOBAIS (portados do painel antigo) ═══ ?>
            <?php if ( ! $current_section_locked ): ?>

            <?php if ( $admin_popup ): ?>
                <div id="rmbz-vip-adminpop" class="card" style="border-color:var(--brand); margin-bottom:18px; display:flex; gap:16px; align-items:flex-start;">
                    <span style="font-size:26px;">📢</span>
                    <div style="flex:1;">
                        <div style="font-weight:750; font-size:15px;"><?php echo esc_html( $admin_popup['title'] ?? 'Mensagem da 1MZ' ); ?></div>
                        <div style="font-size:13px; color:var(--text2); margin-top:4px; line-height:1.55;"><?php echo esc_html( $admin_popup['message'] ?? '' ); ?></div>
                    </div>
                    <button type="button" class="pill" id="rmbz-vip-adminpop-ok" style="background:var(--brand); color:var(--on-brand);">OK, entendi</button>
                </div>
            <?php endif; ?>

            <?php if ( ! empty( $blocks ) ):
                $restriction_icons = [
                    'block_deposits'           => 'account_balance_wallet',
                    'block_withdrawals'        => 'payments',
                    'block_distribution'       => 'cloud_off',
                    'block_video_applications' => 'movie_off',
                    'block_promotions'         => 'campaign',
                    'ban_referral'             => 'group_off',
                ];
                $restriction_support_email = sanitize_email( (string) get_option( 'rmbz_support_email', '' ) );
                if ( $restriction_support_email === '' ) {
                    $restriction_support_email = sanitize_email( (string) get_option( 'admin_email', '' ) );
                }
            ?>
                <section class="account-restrictions" aria-labelledby="rmbz-account-restrictions-title">
                    <div class="account-restrictions-head">
                        <span class="ms account-restrictions-head-icon" aria-hidden="true">shield_lock</span>
                        <div class="account-restrictions-copy">
                            <div class="account-restrictions-kicker">Estado da conta</div>
                            <div class="account-restrictions-title" id="rmbz-account-restrictions-title">Acessos limitados</div>
                            <div class="account-restrictions-subtitle">Alguns serviços não estão disponíveis nesta conta.</div>
                        </div>
                        <span class="account-restrictions-count"><?php echo (int) count( $blocks ); ?> <?php echo count( $blocks ) === 1 ? 'limitação' : 'limitações'; ?></span>
                    </div>

                    <div class="account-restrictions-grid">
                        <?php foreach ( $blocks as $b ):
                            $restriction_key   = sanitize_key( (string) ( $b['key'] ?? '' ) );
                            $restriction_icon  = $restriction_icons[ $restriction_key ] ?? 'lock';
                            $restriction_label = function_exists( 'rmbz_block_public_label' )
                                ? rmbz_block_public_label( $restriction_key )
                                : (string) ( $b['label'] ?? 'Serviço limitado' );
                            $restriction_reason = trim( (string) ( $b['reason'] ?? '' ) );
                            $restriction_until  = (int) ( $b['until'] ?? 0 );
                        ?>
                            <article class="account-restriction">
                                <span class="ms account-restriction-icon" aria-hidden="true"><?php echo esc_html( $restriction_icon ); ?></span>
                                <div class="account-restriction-main">
                                    <div class="account-restriction-label">Serviço indisponível</div>
                                    <div class="account-restriction-title"><?php echo esc_html( $restriction_label ); ?></div>
                                </div>
                                <span class="account-restriction-state">
                                    <span class="ms" aria-hidden="true"><?php echo $restriction_until > 0 ? 'schedule' : 'lock_clock'; ?></span>
                                    <?php echo $restriction_until > 0 ? 'Temporária' : 'Sem prazo'; ?>
                                </span>
                                <div class="account-restriction-detail">
                                    <?php if ( $restriction_reason !== '' ): ?>
                                        <?php echo esc_html( $restriction_reason ); ?>
                                    <?php else: ?>
                                        Este serviço não está disponível na tua conta neste momento.
                                    <?php endif; ?>
                                    <div class="account-restriction-meta">
                                        <span class="ms" aria-hidden="true"><?php echo $restriction_until > 0 ? 'timer' : 'event_busy'; ?></span>
                                        <?php if ( $restriction_until > 0 ): ?>
                                            <span>Tempo restante: <b class="mono rmbz-vip-cd" data-until="<?php echo $restriction_until; ?>">—</b></span>
                                        <?php else: ?>
                                            <span>A reativação será feita pela equipa.</span>
                                        <?php endif; ?>
                                        <?php if ( $restriction_support_email !== '' ): ?>
                                            <a class="account-restriction-support" href="mailto:<?php echo esc_attr( $restriction_support_email ); ?>">
                                                <span class="ms" aria-hidden="true">support_agent</span> Contactar suporte
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </article>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endif; ?>

            <?php if ( ! empty( $fine['overdue'] ) && ! empty( $fine['enabled'] ) && (float) ( $fine['amount'] ?? 0 ) > 0 ):
                $fine_is_frozen   = ! empty( $fine['frozen'] );
                $fine_is_hourly   = ( $fine['unit'] ?? 'day' ) === 'hour';
                $fine_units       = max( 0, (int) ( $fine['units'] ?? 0 ) );
                $fine_unit_single = $fine_is_hourly ? 'hora' : 'dia';
                $fine_unit_plural = $fine_is_hourly ? 'horas' : 'dias';
                $fine_period      = $fine_units . ' ' . ( $fine_units === 1 ? $fine_unit_single : $fine_unit_plural );
                $fine_project     = trim( (string) ( $fine['project_title'] ?? '' ) );
                $fine_since_ts    = ! empty( $fine['since'] ) ? strtotime( (string) $fine['since'] ) : 0;
                $fine_carry       = max( 0, (float) ( $fine['carry'] ?? 0 ) );
            ?>
                <section class="fine-debt-card" aria-label="Dívida pendente da produção">
                    <span class="ms fine-debt-icon" aria-hidden="true">request_quote</span>
                    <div class="fine-debt-content">
                        <div class="fine-debt-heading">
                            <span class="fine-debt-kicker">Dívida do projeto</span>
                            <span class="fine-debt-status"><span class="ms" aria-hidden="true"><?php echo $fine_is_frozen ? 'pause_circle' : 'trending_up'; ?></span><?php echo $fine_is_frozen ? 'Valor congelado' : 'A acumular'; ?></span>
                        </div>
                        <div class="fine-debt-title"><?php echo $fine_is_frozen ? 'Multa pendente da produção' : 'Multa por atraso em curso'; ?></div>
                        <div class="fine-debt-description">
                            <?php echo $fine_is_frozen
                                ? 'Este valor já não está a aumentar, mas continua pendente. A produção é retomada depois da regularização.'
                                : 'A subscrição com o serviço Ganhar Vídeo está inativa. O valor continua a aumentar enquanto o projeto permanece em produção.'; ?>
                        </div>
                        <div class="fine-debt-facts">
                            <?php if ( $fine_project !== '' ): ?><span class="fine-debt-fact"><span class="ms">movie</span>Projeto: <b><?php echo esc_html( $fine_project ); ?></b></span><?php endif; ?>
                            <?php if ( $fine_units > 0 ): ?><span class="fine-debt-fact"><span class="ms">schedule</span>Período: <b><?php echo esc_html( $fine_period ); ?></b></span><?php endif; ?>
                            <span class="fine-debt-fact"><span class="ms">price_change</span>Taxa: <b><?php echo esc_html( $fmt( (float) ( $fine['rate'] ?? 0 ) ) ); ?> MT/<?php echo esc_html( $fine_unit_single ); ?></b></span>
                            <?php if ( $fine_carry > 0 ): ?><span class="fine-debt-fact"><span class="ms">history</span>Dívida anterior: <b><?php echo esc_html( $fmt( $fine_carry ) ); ?> MT</b></span><?php endif; ?>
                            <?php if ( $fine_since_ts > 0 ): ?><span class="fine-debt-fact"><span class="ms">calendar_today</span>Registada desde <b><?php echo esc_html( date_i18n( 'd/m/Y H:i', $fine_since_ts ) ); ?></b></span><?php endif; ?>
                        </div>
                    </div>
                    <div class="fine-debt-side">
                        <div class="fine-debt-amount-label">Total a regularizar</div>
                        <div class="fine-debt-amount"><?php echo esc_html( $fmt( (float) $fine['amount'] ) ); ?> <small>MT</small></div>
                        <button type="button" class="pill fine-debt-action" data-dialog="rmbz-vip-fine-scrim"><span class="ms">account_balance_wallet</span>Pagar dívida</button>
                    </div>
                </section>
            <?php endif; ?>

            <?php foreach ( $feat_invites as $fi ): $fi_id = (int) $fi['project_id']; ?>
                <div class="card" style="border-color:var(--brand); margin-bottom:14px;">
                    <div style="display:flex; gap:14px; align-items:center; flex-wrap:wrap;">
                        <span style="font-size:24px;">🎤</span>
                        <div style="flex:1; min-width:240px;">
                            <div style="font-weight:750; font-size:14.5px;">Foste adicionado como participação num Projecto de Vídeo</div>
                            <div style="font-size:12.5px; color:var(--text2); margin-top:3px;">
                                <b style="color:var(--brand-ink);"><?php echo esc_html( $fi['owner_name'] ); ?></b> adicionou-te ao vídeo de
                                <b>"<?php echo esc_html( $fi['title'] ); ?>"</b> (nível <?php echo esc_html( $fi['level'] ); ?>). Sem a tua resposta a produção não avança.
                            </div>
                        </div>
                        <button type="button" class="pill" data-dialog="rmbz-vip-feat-<?php echo $fi_id; ?>" style="background:var(--brand); color:var(--on-brand);">Ver convite e responder</button>
                    </div>
                </div>
                <div class="scrim" id="rmbz-vip-feat-<?php echo $fi_id; ?>">
                    <div class="dialog" style="width:580px;">
                        <div style="font-size:18px; font-weight:750;">🎤 Convite de Participação — 1MZ For Artists</div>
                        <p style="font-size:13px; color:var(--text2); margin:8px 0 12px;">
                            <b><?php echo esc_html( $fi['owner_name'] ); ?></b> declarou-te como participação
                            (<b><?php echo esc_html( $fi['feat_name'] ); ?></b>) no Projecto de Vídeo
                            <b>"<?php echo esc_html( $fi['title'] ); ?>"</b>. Lê os termos antes de responder:
                        </p>
                        <ol style="font-size:13px; color:var(--text2); line-height:1.65; padding-left:20px; margin:0 0 14px;">
                            <?php foreach ( ( function_exists( 'rmbz_feat_terms' ) ? rmbz_feat_terms() : [] ) as $ft ): ?>
                                <li><b style="color:var(--text);"><?php echo esc_html( $ft[0] ); ?></b> — <?php echo esc_html( $ft[1] ); ?></li>
                            <?php endforeach; ?>
                        </ol>
                        <label style="display:flex; gap:8px; align-items:flex-start; font-size:13px; font-weight:600; background:var(--brand-soft); border-radius:12px; padding:10px 12px; cursor:pointer;">
                            <input type="checkbox" onchange="document.getElementById('rmbz-vip-feat-ok-<?php echo $fi_id; ?>').disabled=!this.checked;" style="margin-top:2px;">
                            <span>Li e concordo com os Termos da Participação da 1MZ For Artists.</span>
                        </label>
                        <div style="display:flex; gap:10px; margin-top:14px; flex-wrap:wrap;">
                            <button type="button" class="pill rmbz-vip-dclose" style="flex:1; justify-content:center; border:1px solid var(--border); background:none; color:var(--text2);">Fechar</button>
                            <form method="post" action="<?php echo esc_url( $post_url ); ?>" style="flex:1; display:flex;"
                                  data-vip-confirm="⚠️ Tens a certeza que queres RECUSAR?&#10;&#10;Ao recusar, o projeto é CANCELADO automaticamente — sem o participante não há como fazer o vídeo. O dono será notificado.">
                                <input type="hidden" name="action" value="rmbz_feat_respond">
                                <input type="hidden" name="project_id" value="<?php echo $fi_id; ?>">
                                <input type="hidden" name="decision" value="reject">
                                <?php wp_nonce_field( 'rmbz_feat_respond_nonce' ); ?>
                                <button type="submit" class="pill" style="flex:1; justify-content:center; background:var(--danger-soft); color:var(--danger);">✕ Recusar</button>
                            </form>
                            <form method="post" action="<?php echo esc_url( $post_url ); ?>" style="flex:1.4; display:flex;">
                                <input type="hidden" name="action" value="rmbz_feat_respond">
                                <input type="hidden" name="project_id" value="<?php echo $fi_id; ?>">
                                <input type="hidden" name="decision" value="accept">
                                <input type="hidden" name="terms_accepted" value="1">
                                <?php wp_nonce_field( 'rmbz_feat_respond_nonce' ); ?>
                                <button type="submit" id="rmbz-vip-feat-ok-<?php echo $fi_id; ?>" disabled class="pill" style="flex:1; justify-content:center; background:var(--success); color:#fff;">✅ Concordo — aceitar</button>
                            </form>
                        </div>
                        <p style="font-size:11px; color:var(--muted); margin:12px 0 0;">⚠️ Se recusares, o projeto é cancelado automaticamente e o dono é avisado em todos os canais.</p>
                    </div>
                </div>
            <?php endforeach; ?>

            <?php // Ação obrigatória: email REAL quando há projeto aprovado (igual ao antigo). ?>
            <?php if ( $is_fake_email && $has_approved_project && ! $is_pending_otp ): ?>
                <div class="scrim open" style="z-index:200;">
                    <div class="dialog" style="width:440px; text-align:center; border-color:var(--brand);">
                        <div style="font-size:52px;">📧</div>
                        <h2 style="margin:8px 0 0; font-family:'Bricolage Grotesque',sans-serif; font-size:22px; font-weight:750; color:var(--brand-ink);">Ação Obrigatória</h2>
                        <p style="font-size:13px; color:var(--text2); line-height:1.6; margin:10px 0 16px;">
                            Parabéns! Tens um projeto de videoclipe <b>aprovado</b> e em andamento.<br><br>
                            Para comunicarmos contigo e enviar os orçamentos e detalhes de gravação, precisas de configurar um <b>email real</b> na tua conta.
                        </p>
                        <form method="post" action="<?php echo esc_url( $post_url ); ?>">
                            <input type="hidden" name="action" value="rmbz_update_profile_request">
                            <?php wp_nonce_field( 'rmbz_update_profile_nonce' ); ?>
                            <input type="hidden" name="user_provincia" value="<?php echo esc_attr( $user->user_provincia ?? '' ); ?>">
                            <input class="inp" type="email" name="user_email" required placeholder="O teu melhor email…" style="text-align:center;">
                            <button type="submit" class="pill" style="margin-top:14px; width:100%; justify-content:center; background:var(--brand); color:var(--on-brand);">Receber código de confirmação</button>
                        </form>
                    </div>
                </div>
            <?php endif; ?>

            <?php if ( $is_pending_otp ): ?>
                <div class="card" style="border-color:var(--brand); margin-bottom:18px;">
                    <div style="font-weight:750; font-size:14.5px;">📧 Confirma o teu email</div>
                    <p style="font-size:12.5px; color:var(--text2); margin:6px 0 12px;">Enviámos um código de 6 dígitos para o teu email (válido 15 minutos). Introduz aqui para validar.</p>
                    <form method="post" action="<?php echo esc_url( $post_url ); ?>" style="display:flex; gap:10px; flex-wrap:wrap;">
                        <input type="hidden" name="action" value="rmbz_verify_profile_otp">
                        <?php wp_nonce_field( 'rmbz_verify_profile_otp_nonce' ); ?>
                        <input class="inp mono" name="email_otp" inputmode="numeric" maxlength="6" placeholder="Código" required style="max-width:180px; text-align:center; letter-spacing:4px;">
                        <button type="submit" class="pill" style="background:var(--brand); color:var(--on-brand);">Validar email</button>
                        <button type="submit" name="cancel_otp" value="1" class="pill" formnovalidate style="border:1px solid var(--border); background:none; color:var(--muted);">Cancelar</button>
                    </form>
                </div>
            <?php endif; ?>
            <?php endif; ?>

            <header class="vip-page-head">
                <div class="vip-page-heading">
                    <h1 id="rmbz-vip-title" class="vip-page-title"><?php echo esc_html( $vip_title_init[0] ); ?></h1>
                    <div id="rmbz-vip-sub" class="vip-page-sub"><?php echo esc_html( $vip_title_init[1] ); ?></div>
                </div>
                <button type="button" class="pill vip-page-notif" data-nav="notifs" aria-label="Abrir notificações">
                    <span class="ms">notifications</span><span>Notificações</span>
                    <?php if ( $n_por_ler > 0 ): ?><span class="vip-page-notif-count"><?php echo (int) $n_por_ler; ?></span><?php endif; ?>
                </button>
            </header>

            <!-- ═══ INÍCIO ═══ -->
            <section class="sect<?php echo $vip_sect === 'inicio' ? ' on' : ''; ?>" data-sect="inicio" data-screen-label="Início">
                <div class="home-finance-grid">
                    <section class="home-wealth-card" aria-label="Património estimado">
                        <div class="home-card-eyebrow"><span class="ms">account_balance_wallet</span>Património estimado</div>
                        <div class="home-wealth-value"><?php echo esc_html( $fmt( $patrimonio_total ) ); ?> <small>MT</small></div>
                        <div class="home-wealth-caption">Carteira e royalties convertidos à taxa de câmbio atual.</div>
                        <div class="home-wealth-actions">
                            <button type="button" class="pill home-wealth-action primary" id="rmbz-vip-dep"><span class="ms">add_circle</span>Depositar</button>
                            <button type="button" class="pill home-wealth-action secondary" id="rmbz-vip-wd"><span class="ms">payments</span>Levantar</button>
                        </div>
                    </section>
                    <article class="home-finance-card">
                        <div class="home-finance-head"><span class="ms home-finance-icon">payments</span><div class="home-finance-label">Saldo retirável</div></div>
                        <div class="home-finance-value"><?php echo esc_html( $fmt( $retiravel ) ); ?> <small>MT</small></div>
                        <div class="home-finance-meta"><?php echo $promocional > 0 ? esc_html( $fmt( $promocional ) ) . ' MT em saldo promocional não retirável.' : 'Disponível para pedidos de levantamento.'; ?></div>
                        <span class="home-finance-link"><span class="ms">check_circle</span>Carteira atualizada</span>
                    </article>
                    <article class="home-finance-card">
                        <?php if ( $distro_access ): ?>
                            <div class="home-finance-head"><span class="ms home-finance-icon">music_note</span><div class="home-finance-label">Royalties de distribuição</div></div>
                            <div class="home-finance-value">$ <?php echo esc_html( number_format( $roy_usd, 2, ',', '.' ) ); ?></div>
                            <div class="home-finance-meta">≈ <?php echo esc_html( $fmt( $roy_mt ) ); ?> MT · câmbio <?php echo esc_html( number_format( $cambio, 2, ',', '.' ) ); ?></div>
                            <button type="button" class="home-finance-link" data-nav="distro">Ver relatórios <span class="ms">arrow_forward</span></button>
                        <?php else: ?>
                            <div class="home-finance-head"><span class="ms home-finance-icon">lock</span><div class="home-finance-label">Distribuição digital</div></div>
                            <div class="home-finance-value" style="font-family:'Bricolage Grotesque',sans-serif;font-size:21px;">Não incluída</div>
                            <div class="home-finance-meta">Os royalties e relatórios ficam protegidos neste plano.</div>
                            <button type="button" class="home-finance-link" data-nav="distro">Ver acesso <span class="ms">arrow_forward</span></button>
                        <?php endif; ?>
                    </article>
                </div>

                <?php if ( $filmando !== '' ): ?>
                    <div class="home-live-banner"><span class="ms home-live-icon">videocam</span><div class="home-live-copy"><b>Filmagem em direto</b><br>O videoclipe «<?php echo esc_html( $filmando ); ?>» está a ser produzido agora pela equipa 1MZ.</div></div>
                <?php endif; ?>

                <div class="home-main-grid">
                    <article class="home-panel">
                        <div class="home-panel-head">
                            <span class="ms home-panel-icon">movie</span>
                            <div class="home-panel-heading"><div class="home-panel-title">Os teus videoclipes</div><div class="home-panel-subtitle">Acompanha rapidamente as produções mais recentes.</div></div>
                            <button type="button" class="home-panel-link" data-nav="projetos">Ver todos <span class="ms">arrow_forward</span></button>
                        </div>
                        <?php if ( ! $project_access ): ?>
                            <div class="home-empty"><span class="ms">lock</span><div><strong>Serviço não incluído</strong><small>Os dados de videoclipes permanecem protegidos neste plano.</small></div></div>
                        <?php elseif ( empty( $projetos ) ): ?>
                            <div class="home-empty"><span class="ms">video_library</span><div><strong>Ainda não tens videoclipes</strong><small>Quando uma candidatura for aprovada, o acompanhamento aparece aqui.</small></div></div>
                        <?php else: ?>
                            <div class="home-project-list">
                            <?php foreach ( array_slice( $projetos, 0, 3 ) as $p ): ?>
                                <div class="home-project-row">
                                    <span class="ms home-project-icon">movie</span>
                                    <div class="home-project-copy">
                                        <div class="home-project-name"><?php echo esc_html( $p['titulo'] ); ?></div>
                                        <div class="home-project-meta"><span><?php echo esc_html( $p['data'] ); ?></span><span>·</span><span><?php echo (int) $p['pct']; ?>% concluído</span></div>
                                        <div class="home-project-progress"><span style="width:<?php echo (int) $p['pct']; ?>%;"></span></div>
                                    </div>
                                    <span class="home-project-status" style="background:var(--<?php echo esc_attr( $p['tone'] ); ?>-soft); color:var(--<?php echo esc_attr( $p['tone'] === 'muted' ? 'muted' : $p['tone'] ); ?>);"><?php echo esc_html( $p['estado'] ); ?></span>
                                </div>
                            <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </article>
                    <article class="home-panel">
                        <div class="home-panel-head"><span class="ms home-panel-icon">monitoring</span><div class="home-panel-heading"><div class="home-panel-title">O teu trabalho</div><div class="home-panel-subtitle">Resumo da atividade na plataforma.</div></div></div>
                        <div class="home-work-stats">
                            <div class="home-work-stat"><span class="ms"><?php echo $project_access ? 'video_library' : 'lock'; ?></span><div class="home-work-value"><?php echo $project_access ? (int) $project_total : '—'; ?></div><div class="home-work-label">Produções</div></div>
                            <div class="home-work-stat"><span class="ms"><?php echo $project_access ? 'motion_play' : 'lock'; ?></span><div class="home-work-value"><?php echo $project_access ? (int) $ativos : '—'; ?></div><div class="home-work-label">Em curso</div></div>
                            <div class="home-work-stat"><span class="ms"><?php echo $distro_access ? 'headphones' : 'lock'; ?></span><div class="home-work-value"><?php echo $distro_access ? esc_html( number_format( $streams_tot ) ) : '—'; ?></div><div class="home-work-label">Streams</div></div>
                        </div>
                        <div class="home-vip-note"><span class="ms">workspace_premium</span><div><b>Conta de Artista VIP ativa</b><br>Acesso prioritário à equipa e às ferramentas profissionais.</div></div>
                    </article>
                </div>

                <div class="home-utility-grid">
                    <article class="home-utility-card">
                        <div class="home-utility-head"><span class="ms home-utility-icon">confirmation_number</span><div><div class="home-utility-title">Cupão promocional</div><p class="home-utility-text">Resgata um código da 1MZ e recebe os benefícios associados.</p></div><span class="home-utility-badge">Benefício VIP</span></div>
                        <form method="post" action="<?php echo esc_url( $post_url ); ?>" class="home-utility-form">
                            <input type="hidden" name="action" value="rmbz_apply_coupon">
                            <?php wp_nonce_field( 'rmbz_apply_coupon_nonce' ); ?>
                            <input class="inp mono home-utility-input" name="coupon_code" maxlength="20" placeholder="Introduz o código" required style="flex:1; text-transform:uppercase;">
                            <button type="submit" class="pill home-utility-action"><span class="ms">redeem</span>Resgatar</button>
                        </form>
                    </article>
                    <article class="home-utility-card">
                        <div class="home-utility-head"><span class="ms home-utility-icon">group_add</span><div><div class="home-utility-title">Convida e ganha</div><p class="home-utility-text"><?php if ( $ref_stats ): ?><?php echo (int) ( $ref_stats['count'] ?? 0 ); ?> artista(s) já utilizaram o teu convite.<?php else: ?>Partilha o teu código com outros artistas.<?php endif; ?></p></div><span class="home-utility-badge"><?php echo $ref_type === 'days' ? (int) $ref_days . ' dias VIP' : esc_html( $fmt( (float) $ref_rate ) ) . ' MT'; ?> / convite</span></div>
                        <div class="home-utility-form">
                            <input class="inp mono home-utility-input" id="rmbz-vip-refcode" readonly value="<?php echo esc_attr( $telemovel ); ?>" style="flex:1;">
                            <button type="button" class="pill home-utility-action outlined" id="rmbz-vip-refcopy"><span class="ms">content_copy</span>Copiar</button>
                        </div>
                    </article>
                </div>
            </section>

            <!-- ═══ MÚSICAS & MONETIZAÇÃO ═══ -->
            <section class="sect<?php echo $vip_sect === 'musicas' ? ' on' : ''; ?>" data-sect="musicas" data-screen-label="Músicas & Ganhos">
                <?php if ( ! $partnership_access && function_exists( 'rmbz_render_partnership_program' ) ): ?>
                    <?php echo rmbz_render_partnership_program( $telemovel ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- renderer interno. ?>
                <?php else: ?>
                    <div class="artists-native-shell">
                        <?php if ( function_exists( 'imz_render_artist_dashboard_shortcode' ) ): ?>
                            <?php echo imz_render_artist_dashboard_shortcode(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- renderer interno já escapa os dados. ?>
                        <?php else: ?>
                            <div class="artists-native-missing"><div><span class="ms" style="font-size:34px;color:var(--brand-ink);">library_music</span><h3>Módulo Artists indisponível</h3><p>Não foi possível carregar as ferramentas de catálogo desta instalação.</p></div></div>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </section>

            <!-- ═══ ART TRACKS ═══ -->
            <section class="sect<?php echo $vip_sect === 'arttracks' ? ' on' : ''; ?>" data-sect="arttracks" data-screen-label="Art Tracks">
                <?php if ( $vip_sect === 'arttracks' && function_exists( 'rmbz_render_art_tracks_account' ) ): ?>
                    <?php echo rmbz_render_art_tracks_account( $telemovel ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- renderer interno. ?>
                <?php elseif ( $vip_sect === 'arttracks' ): ?>
                    <div class="artists-native-missing"><div><span class="ms" style="font-size:34px;color:var(--brand-ink);">album</span><h3>Art Tracks indisponível</h3><p>Não foi possível carregar o catálogo desta conta.</p></div></div>
                <?php endif; ?>
            </section>

            <!-- ═══ VIDEOCLIPES ═══ -->
            <section class="sect<?php echo $vip_sect === 'projetos' ? ' on' : ''; ?>" data-sect="projetos" data-screen-label="Videoclipes">
                <?php if ( ! $project_access ): ?>
                    <?php rmbz_vip_render_service_gate( 'video', $project_gate_reason ); ?>
                <?php else: ?>
                <?php if ( empty( $projetos ) ): ?>
                    <div class="card project-empty"><span class="ms project-empty-icon">movie</span><p style="font-weight:750; margin:14px 0 0;">Ainda não tens videoclipes</p><p style="font-size:12.5px; color:var(--muted); margin:5px 0 0;">Quando um projeto for aprovado, o acompanhamento da produção aparece aqui.</p></div>
                <?php else: ?>
                    <div style="display:flex; flex-direction:column; gap:18px;">
                    <?php
                    // Uma sessao live tem prioridade visual: abre esse projeto e
                    // mantem todos os outros compactos.
                    $filming_live_project_id = 0;
                    $filming_live_started_ts = 0;
                    foreach ( $em_producao as $project_candidate ) {
                        $candidate_sessions = isset( $project_candidate['extra']['filming_sessions'] ) && is_array( $project_candidate['extra']['filming_sessions'] )
                            ? $project_candidate['extra']['filming_sessions'] : [];
                        foreach ( $candidate_sessions as $candidate_session ) {
                            if ( is_array( $candidate_session ) && empty( $candidate_session['ended_at'] ) ) {
                                $filming_live_project_id = (int) $project_candidate['row']->id;
                                $filming_live_started_ts = (int) ( $candidate_session['started_ts'] ?? 0 );
                                break 2;
                            }
                        }
                    }
                    ?>
                    <span data-filming-monitor data-status-url="<?php echo esc_url( rest_url( '1mz/v1/artist-projects/filming-status' ) ); ?>" data-active-project="<?php echo $filming_live_project_id; ?>" data-active-started="<?php echo $filming_live_started_ts; ?>" hidden></span>
                    <?php $project_accordion_index = 0; ?>
                    <?php foreach ( $em_producao as $p ):
                        $pr = $p['row']; $px = $p['extra']; $pi = $p['items'];
                        $pid = (int) $pr->id;
                        $st  = $p['st'];
                        $project_filming_sessions = isset( $px['filming_sessions'] ) && is_array( $px['filming_sessions'] )
                            ? $px['filming_sessions'] : [];
                        $project_filming_active = null;
                        $project_filming_history = [];
                        foreach ( $project_filming_sessions as $project_filming_session ) {
                            if ( ! is_array( $project_filming_session ) ) continue;
                            if ( empty( $project_filming_session['ended_at'] ) ) $project_filming_active = $project_filming_session;
                            else $project_filming_history[] = $project_filming_session;
                        }
                        $project_filming_percent_left = isset( $px['filming_progress']['percent_left'] )
                            ? max( 0, min( 99, (int) $px['filming_progress']['percent_left'] ) ) : -1;
                        $project_is_open = $filming_live_project_id > 0
                            ? ( $pid === $filming_live_project_id )
                            : ( $project_accordion_index === 0 );
                        $project_team = function_exists( 'rmbz_team_for_project' ) ? rmbz_team_for_project( $px ) : [];
                        // Totais do orçamento (mesma regra do antigo: obrigatórios +
                        // negociáveis NÃO assumidos = a pagar à 1MZ).
                        $oblig = 0.0; $check_items = []; $undecided = [];
                        foreach ( $pi as $ii => $it ) {
                            if ( ! is_array( $it ) ) continue;
                            $mp = isset( $it['must_pay'] ) ? (int) $it['must_pay'] : 1;
                            $aa = ! empty( $it['artist_assumes'] );
                            if ( $mp === 1 || ! $aa ) $oblig += (float) ( $it['cost'] ?? 0 );
                            if ( $mp === 0 && $aa ) $check_items[ $ii ] = $it;
                            if ( $mp === 0 && isset( $it['decided'] ) && (int) $it['decided'] === 0 ) $undecided[ $ii ] = $it;
                        }
                        $pago  = (float) ( $pr->amount_paid ?? 0 );
                        if ( $pago <= 0 && ! empty( $pr->is_paid ) ) {
                            $pago = max( $oblig, (float) ( $pr->scenario_cost ?? 0 ) );
                        }
                        $falta = max( 0, $oblig - $pago );
                        $totalmente_pago = ( $oblig > 0 && $pago >= $oblig - 0.01 );
                        $contract_url      = (string) ( $px['contract_url'] ?? '' );
                        $contract_accepted = ! empty( $px['contract_accepted'] );
                        $contract_rejected = ! empty( $px['contract_rejected'] );
                        $kyc_status        = (string) ( $px['kyc_status'] ?? '' );
                        $is_kyc_ok         = ( $kyc_status === 'approved' );
                        // Multa DESTE projeto?
                        $fine_this = ( ! empty( $fine['overdue'] ) && ! empty( $fine['enabled'] ) && (float) ( $fine['amount'] ?? 0 ) > 0 && (int) ( $fine['project_id'] ?? 0 ) === $pid );
                        $project_stage = rmbz_vip_project_stage_meta( $st );
                        $project_stage_steps = [
                            1 => [ 'rate_review', 'Avaliação' ],
                            2 => [ 'video_settings', 'Pré-produção' ],
                            3 => [ 'videocam', 'Filmagem' ],
                            4 => [ 'movie_edit', 'Edição' ],
                            5 => [ 'task_alt', 'Concluído' ],
                        ];
                    ?>
                        <article class="card project-card<?php echo $project_is_open ? ' is-open' : ''; ?><?php echo $project_filming_active ? ' is-filming-live' : ''; ?>" data-project-accordion>
                            <button type="button" class="project-accordion-toggle" aria-expanded="<?php echo $project_is_open ? 'true' : 'false'; ?>" aria-controls="rmbz-vip-project-body-<?php echo $pid; ?>"<?php echo $project_filming_active ? ' disabled' : ''; ?>>
                            <span class="project-top">
                                <span class="project-heading">
                                    <span class="project-kicker">Projeto de videoclipe</span>
                                    <span class="project-name"><?php echo esc_html( $p['titulo'] ); ?></span>
                                    <span class="project-meta"><span class="ms">movie</span><span><?php echo esc_html( strtoupper( (string) ( $pr->scenario_type ?? '' ) ) ); ?></span><span>·</span><span class="ms">calendar_today</span><span><?php echo esc_html( $p['data'] ); ?></span></span>
                                </span>
                                <span class="project-header-side">
                                <span class="project-badges">
                                    <?php if ( ! in_array( $st, [ 'pending_review', 'rejected', 'cancelled_no_confirmation' ], true ) ): ?>
                                        <?php // [1.5.452] Badge M3 limpo: ícone Material em vez do emoji. ?>
                                        <span class="status" style="display:inline-flex; align-items:center; gap:5px; background:<?php echo $totalmente_pago ? 'var(--success-soft)' : 'var(--danger-soft)'; ?>; color:<?php echo $totalmente_pago ? 'var(--success)' : 'var(--danger)'; ?>;"><span class="ms" style="font-size:14px; font-variation-settings:'FILL' 1;"><?php echo $totalmente_pago ? 'check_circle' : 'schedule'; ?></span> <?php echo $totalmente_pago ? 'Totalmente pago' : 'Pagamento pendente'; ?></span>
                                    <?php endif; ?>
                                    <span class="status" style="background:var(--<?php echo esc_attr( $p['tone'] ); ?>-soft); color:var(--<?php echo esc_attr( $p['tone'] === 'muted' ? 'muted' : $p['tone'] ); ?>);"><?php echo esc_html( $p['estado'] ); ?></span>
                                </span>
                                <span class="project-accordion-chevron" aria-hidden="true"><span class="ms"><?php echo $project_filming_active ? 'lock' : 'expand_more'; ?></span></span>
                                </span>
                            </span>
                            </button>
                            <div class="project-accordion-body" id="rmbz-vip-project-body-<?php echo $pid; ?>"<?php echo $project_is_open ? '' : ' hidden'; ?>>
                            <?php if ( $project_filming_active ): ?>
                                <section class="project-filming-lock" data-filming-live-lock aria-live="polite">
                                    <span class="project-filming-live-badge"><span class="project-filming-live-dot"></span>Filmagem em direto · Dia <?php echo (int) ( $project_filming_active['day'] ?? 1 ); ?></span>
                                    <span class="project-filming-live-icon"><span class="ms">videocam</span></span>
                                    <h3 class="project-filming-live-title">O teu videoclipe está a ser filmado</h3>
                                    <div class="project-filming-clock rmbz-vip-fsclock" data-started="<?php echo (int) ( $project_filming_active['started_ts'] ?? 0 ); ?>" data-servernow="<?php echo (int) current_time( 'timestamp', true ); ?>">00:00:00</div>
                                    <p class="project-filming-live-copy">A produção está a decorrer agora. Para proteger o trabalho da equipa, as restantes funções deste projeto ficam temporariamente bloqueadas. O registo deste dia e os participantes serão publicados aqui quando o admin finalizar a sessão.</p>
                                    <span class="project-filming-live-foot"><span class="ms">lock</span>Projeto temporariamente bloqueado durante a filmagem</span>
                                </section>
                            <?php else: ?>
                            <section class="project-stage-panel tone-<?php echo esc_attr( $project_stage['tone'] ); ?>" style="--stage-progress:<?php echo (int) $project_stage['rail']; ?>%;" aria-label="Etapa atual do projeto: <?php echo esc_attr( $project_stage['title'] ); ?>">
                                <div class="project-stage-head">
                                    <span class="ms project-stage-icon" aria-hidden="true"><?php echo esc_html( $project_stage['icon'] ); ?></span>
                                    <div class="project-stage-copy">
                                        <div class="project-stage-kicker">Etapa atual do projeto</div>
                                        <div class="project-stage-title"><?php echo esc_html( $project_stage['title'] ); ?></div>
                                        <div class="project-stage-description"><?php echo esc_html( $project_stage['description'] ); ?></div>
                                    </div>
                                    <div class="project-stage-percent" aria-label="<?php echo (int) $p['pct']; ?> por cento concluído"><?php echo (int) $p['pct']; ?>%</div>
                                </div>
                                <div class="project-stage-track" aria-hidden="true">
                                    <div class="project-stage-rail"><span></span></div>
                                    <?php foreach ( $project_stage_steps as $stage_number => $stage_step ):
                                        $stage_class = $stage_number < (int) $project_stage['step'] ? ' is-complete' : ( $stage_number === (int) $project_stage['step'] ? ' is-active' : '' );
                                    ?>
                                        <div class="project-stage-step<?php echo esc_attr( $stage_class ); ?>">
                                            <span class="ms project-stage-dot"><?php echo $stage_number < (int) $project_stage['step'] ? 'check' : esc_html( $stage_step[0] ); ?></span>
                                            <span class="project-stage-step-label"><?php echo esc_html( $stage_step[1] ); ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </section>

                            <?php if ( ! empty( $project_team ) ): ?>
                                <div class="project-section-card project-team-card">
                                    <div class="project-section-head">
                                        <span class="ms project-section-icon">groups</span>
                                        <div><div class="project-section-title">Equipa do projeto</div><div class="project-section-subtitle">Profissionais confirmados para este videoclipe.</div></div>
                                        <span class="project-team-count"><?php echo count( $project_team ); ?> <?php echo count( $project_team ) === 1 ? 'pessoa' : 'pessoas'; ?></span>
                                    </div>
                                    <div class="project-team-grid">
                                        <?php foreach ( $project_team as $team_member ):
                                            $team_roles = isset( $team_member['roles'] ) && is_array( $team_member['roles'] ) ? $team_member['roles'] : [];
                                            $team_name = trim( (string) ( $team_member['name'] ?? '' ) );
                                            $team_initial = function_exists( 'mb_substr' ) ? mb_strtoupper( mb_substr( $team_name, 0, 1 ) ) : strtoupper( substr( $team_name, 0, 1 ) );
                                        ?>
                                            <div class="project-team-member">
                                                <span class="project-team-avatar">
                                                    <?php if ( ! empty( $team_member['photo_url'] ) ): ?><img src="<?php echo esc_url( $team_member['photo_url'] ); ?>" alt="<?php echo esc_attr( $team_name ); ?>" loading="lazy"><?php else: ?><?php echo esc_html( $team_initial ?: '1' ); ?><?php endif; ?>
                                                </span>
                                                <span class="project-team-copy">
                                                    <span class="project-team-name-row">
                                                        <span class="project-team-name"><?php echo esc_html( $team_name ); ?></span>
                                                        <?php if ( ( $team_member['origin'] ?? '1mz' ) === 'externo' ): ?><span class="project-team-origin"><span class="ms">public</span>Externo</span><?php endif; ?>
                                                    </span>
                                                    <?php if ( ! empty( $team_roles ) ): ?><span class="project-team-roles"><?php foreach ( $team_roles as $team_role ): ?><span class="project-team-role"><?php echo esc_html( $team_role ); ?></span><?php endforeach; ?></span><?php endif; ?>
                                                </span>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <?php rmbz_vip_render_filming_history( $project_filming_history, $project_filming_percent_left ); ?>

                            <?php if ( $fine_this ): ?>
                                <div class="project-state danger">
                                    <span class="ms project-state-icon">lock</span>
                                    <div class="project-state-body"><div class="project-state-title">Projeto suspenso por atraso</div><div class="project-state-text"><?php echo (int) ( $fine['units'] ?? 0 ); ?> <?php echo ( ( $fine['unit'] ?? 'day' ) === 'hour' ) ? 'hora(s)' : 'dia(s)'; ?> × <?php echo esc_html( $fmt( (float) ( $fine['rate'] ?? 0 ) ) ); ?> MT<?php echo ! empty( $fine['frozen'] ) ? ' · valor congelado' : ' · valor em acumulação'; ?>.</div><div class="project-state-facts"><span><span class="ms">payments</span><b class="mono"><?php echo esc_html( $fmt( (float) $fine['amount'] ) ); ?> MT</b></span></div><div class="project-actions"><button type="button" class="pill project-btn danger" data-dialog="rmbz-vip-fine-scrim"><span class="ms">account_balance_wallet</span>Regularizar multa</button></div></div>
                                </div>
                            <?php elseif ( $st === 'pending_review' ): ?>
                                <div class="project-state neutral">
                                    <span class="ms project-state-icon">hourglass_top</span>
                                    <div class="project-state-body"><div class="project-state-title">Em avaliação</div><div class="project-state-text">A curadoria está a analisar a candidatura. Receberás uma notificação quando houver uma decisão.</div><div class="project-actions"><button type="button" class="pill project-btn outlined" data-dialog="rmbz-vip-rules-scrim"><span class="ms">policy</span>Consultar regras</button></div></div>
                                </div>
                            <?php elseif ( $st === 'rejected' ): ?>
                                <div class="project-state danger">
                                    <span class="ms project-state-icon">block</span>
                                    <div class="project-state-body"><div class="project-state-title">Projeto rejeitado</div><div class="project-state-text"><b>Motivo:</b> <?php echo esc_html( $px['admin_rejection_reason'] ?? 'Incompatibilidade nos termos.' ); ?></div></div>
                                </div>
                            <?php elseif ( $st === 'cancelled_no_confirmation' ): ?>
                                <?php
                                $cancel_reason = (string) ( $px['cancelled_reason'] ?? ( $px['cancel_reason'] ?? ( $px['cancellation_reason'] ?? 'A ação solicitada não foi confirmada dentro do prazo.' ) ) );
                                ?>
                                <div class="project-state danger">
                                    <span class="ms project-state-icon">event_busy</span>
                                    <div class="project-state-body"><div class="project-state-title">Projeto cancelado por prazo</div><div class="project-state-text"><?php echo esc_html( $cancel_reason ); ?> Esta música não poderá ser reenviada.</div></div>
                                </div>
                            <?php elseif ( ! $has_subscription ): ?>
                                <div class="project-state warning">
                                    <span class="ms project-state-icon">workspace_premium</span>
                                    <div class="project-state-body"><div class="project-state-title">Subscrição necessária</div><div class="project-state-text">Renova a subscrição VIP para a produção continuar.</div><div class="project-actions"><button type="button" class="pill project-btn filled" data-nav="perfil"><span class="ms">autorenew</span>Renovar VIP</button></div></div>
                                </div>
                            <?php else: ?>

                                <?php // ── Vistoria bloqueada (fim da filmagem, taxa por pagar) ──
                                $vs = function_exists( 'rmbz_team_vistoria_status' ) ? rmbz_team_vistoria_status( $pr ) : [ 'blocked' => false ];
                                if ( ! empty( $vs['blocked'] ) ): ?>
                                    <div class="project-state danger">
                                        <span class="ms project-state-icon">lock</span>
                                        <div class="project-state-body"><div class="project-state-title">Taxa de vistoria pendente</div><div class="project-state-text">A gravação terminou, mas a edição e a entrega ficam bloqueadas até regularizares a taxa<?php echo ! empty( $vs['editor'] ) ? ' do editor externo' : ''; ?>.</div><div class="project-state-facts"><span><span class="ms">payments</span><b class="mono"><?php echo esc_html( $fmt( (float) $vs['left'] ) ); ?> MT</b></span></div></div>
                                    </div>
                                <?php endif; ?>

                                <?php // ── Entrega ao editor externo ──
                                $ed = function_exists( 'rmbz_editor_delivery_get' ) ? rmbz_editor_delivery_get( $px ) : null;
                                if ( $ed && $ed['files'] > 0 ):
                                    $ed_sz = function_exists( 'rmbz_editor_delivery_size_txt' ) ? rmbz_editor_delivery_size_txt( $ed['size_gb'] ) : $fmt( $ed['size_gb'] ) . ' GB';
                                ?>
                                    <div class="project-state <?php echo $ed['delivered'] ? 'success' : 'info'; ?>">
                                        <span class="ms project-state-icon"><?php echo $ed['delivered'] ? 'task_alt' : 'inventory_2'; ?></span>
                                        <div class="project-state-body"><div class="project-state-title"><?php echo $ed['delivered'] ? 'Ficheiros entregues ao editor' : 'Ficheiros preparados para entrega'; ?></div><div class="project-state-text"><?php echo $ed['delivered'] ? 'A produção aguarda a montagem e a aprovação do vídeo final.' : 'Receberás uma notificação quando o editor confirmar a receção.'; ?></div><div class="project-state-facts"><span><span class="ms">video_file</span><b><?php echo (int) $ed['files']; ?> ficheiro(s)</b></span><span><span class="ms">hard_drive</span><b><?php echo esc_html( $ed_sz ); ?></b></span><span><span class="ms">high_quality</span><b><?php echo esc_html( $ed['quality'] ); ?></b></span></div></div>
                                    </div>
                                <?php endif; ?>

                                <?php // ── Gravação ao vivo (REC) + progresso entre dias ──
                                $fs_list = ( isset( $px['filming_sessions'] ) && is_array( $px['filming_sessions'] ) ) ? $px['filming_sessions'] : [];
                                $fs_act = null; $fs_days = 0; $fs_next = '';
                                foreach ( $fs_list as $fs_s ) {
                                    if ( ! is_array( $fs_s ) ) continue;
                                    if ( empty( $fs_s['ended_at'] ) ) { $fs_act = $fs_s; }
                                    else { $fs_days++; if ( ! empty( $fs_s['next_date'] ) ) $fs_next = (string) $fs_s['next_date']; }
                                }
                                $fs_pleft = isset( $px['filming_progress']['percent_left'] ) ? (int) $px['filming_progress']['percent_left'] : -1;
                                if ( $fs_act ): ?>
                                    <div class="project-state danger">
                                        <span class="ms project-state-icon">fiber_manual_record</span>
                                        <div class="project-state-body"><div class="project-state-title"><span class="rec" style="margin-right:6px;"></span>Gravação em direto</div><div class="mono rmbz-vip-fsclock" data-started="<?php echo (int) ( $fs_act['started_ts'] ?? 0 ); ?>" data-servernow="<?php echo (int) current_time( 'timestamp', true ); ?>" style="font-size:27px; font-weight:600; letter-spacing:1px; margin-top:4px;">--:--:--</div><div class="project-state-text">Dia <?php echo (int) ( $fs_act['day'] ?? 1 ); ?> de gravação · equipa em produção.</div></div>
                                    </div>
                                <?php elseif ( $fs_pleft > 0 && $st === 'filming' ): ?>
                                    <div class="project-state warning">
                                        <span class="ms project-state-icon">movie</span>
                                        <div class="project-state-body"><div class="project-state-title">Gravação em curso</div><div class="project-state-text">Faltam <b><?php echo (int) $fs_pleft; ?>%</b> para concluir<?php if ( $fs_next !== '' ): ?> · próxima sessão em <b><?php echo esc_html( date_i18n( 'd/m/Y', strtotime( $fs_next . ' 12:00' ) ) ); ?></b><?php endif; ?><?php if ( $fs_days > 0 ): ?> · <?php echo (int) $fs_days; ?> dia(s) concluído(s)<?php endif; ?>.</div></div>
                                    </div>
                                <?php endif; ?>

                                <?php // ── Transferência de projeto (pendente/aceite) ──
                                $tr = ( isset( $px['transfer_request'] ) && is_array( $px['transfer_request'] ) ) ? $px['transfer_request'] : null;
                                if ( $tr && ( $tr['status'] ?? '' ) === 'pending' ): ?>
                                    <div class="project-state warning">
                                        <span class="ms project-state-icon">move_up</span>
                                        <div class="project-state-body"><div class="project-state-title">Transferência de titularidade</div><div class="project-state-text">A equipa indicou que este projeto deve pertencer a outra conta.<?php if ( ! empty( $tr['reason'] ) ): ?> <b>Motivo:</b> <?php echo esc_html( $tr['reason'] ); ?><?php endif; ?></div>
                                        <div class="project-actions">
                                            <button type="button" class="pill project-btn success" data-dialog="rmbz-vip-tr-<?php echo $pid; ?>"><span class="ms">check</span>Aceitar transferência</button>
                                            <form method="post" action="<?php echo esc_url( $post_url ); ?>">
                                                <input type="hidden" name="action" value="rmbz_project_transfer_respond">
                                                <input type="hidden" name="project_id" value="<?php echo $pid; ?>">
                                                <input type="hidden" name="decision" value="reject">
                                                <?php wp_nonce_field( 'rmbz_transfer_respond_nonce' ); ?>
                                                <button type="submit" class="pill project-btn outlined"><span class="ms">close</span>Recusar</button>
                                            </form>
                                        </div></div>
                                    </div>
                                    <div class="scrim" id="rmbz-vip-tr-<?php echo $pid; ?>">
                                        <div class="dialog" style="width:560px;">
                                            <div class="project-modal-head"><span class="ms project-modal-icon">move_up</span><div><div style="font-size:17px; font-weight:750;">Transferência de projeto</div><div style="font-size:11px; color:var(--muted);">Termos oficiais da 1MZ For Artists</div></div></div>
                                            <p style="font-size:12.5px; color:var(--text2); margin:8px 0 12px;">Lê com atenção antes de aceitar a transferência de <b>"<?php echo esc_html( $p['titulo'] ); ?>"</b>:</p>
                                            <ol style="font-size:12.5px; color:var(--text2); line-height:1.6; padding-left:20px; margin:0 0 14px;">
                                                <li><b>Definitiva e irreversível</b> — depois de concluída pela equipa 1MZ, a transferência não pode ser revertida.</li>
                                                <li><b>Perda total de acesso</b> — o projeto, o chat, os ficheiros e o histórico deixam de estar disponíveis na tua conta.</li>
                                                <li><b>Novo dono</b> — a equipa 1MZ nomeia a conta de destino; a transferência só se conclui após confirmação da equipa.</li>
                                                <li><b>Valores pagos</b> — os pagamentos já feitos ficam associados ao projeto e não são devolvidos à tua carteira, salvo decisão expressa da equipa 1MZ.</li>
                                                <li><b>Obrigações futuras</b> — multas, prazos e obrigações do projeto passam a ser da responsabilidade do novo dono a partir da conclusão.</li>
                                                <li><b>Contrato e KYC</b> — o contrato e a verificação de identidade atuais são anulados; o novo dono assina novo contrato.</li>
                                                <li><b>Notificações</b> — receberás confirmação (em todos os canais) quando a transferência for concluída, ou aviso se não for possível.</li>
                                                <li><b>Declaração</b> — ao aceitar, declaras que o fazes de forma voluntária e que compreendes estes termos.</li>
                                            </ol>
                                            <div style="background:var(--elev); border-radius:14px; padding:12px; margin-bottom:12px;">
                                                <div style="display:flex; align-items:center; gap:7px; font-size:12.5px; font-weight:700; margin-bottom:8px;"><span class="ms" style="font-size:18px; color:var(--brand-ink);">person</span>Conta de destino</div>
                                                <input class="inp rmbz-vip-tr-nm" placeholder="Nome do artista dono da música" style="margin-bottom:8px; font-size:13px;">
                                                <input class="inp rmbz-vip-tr-tl" type="tel" placeholder="Número (telemóvel) da conta dele" style="font-size:13px;">
                                            </div>
                                            <label style="display:flex; gap:8px; align-items:flex-start; font-size:12.5px; font-weight:600; background:var(--elev); border-radius:12px; padding:10px 12px; cursor:pointer;">
                                                <input type="checkbox" class="rmbz-vip-tr-ck" style="margin-top:2px;">
                                                <span>Li e concordo com os Termos da Transferência de Projeto da 1MZ For Artists.</span>
                                            </label>
                                            <form method="post" action="<?php echo esc_url( $post_url ); ?>" class="rmbz-vip-tr-form" style="display:flex; gap:10px; margin-top:14px;">
                                                <input type="hidden" name="action" value="rmbz_project_transfer_respond">
                                                <input type="hidden" name="project_id" value="<?php echo $pid; ?>">
                                                <input type="hidden" name="decision" value="accept">
                                                <input type="hidden" name="terms_accepted" value="1">
                                                <input type="hidden" name="suggested_name" value="">
                                                <input type="hidden" name="suggested_tel" value="">
                                                <?php wp_nonce_field( 'rmbz_transfer_respond_nonce' ); ?>
                                                <button type="button" class="pill rmbz-vip-dclose" style="flex:1; justify-content:center; border:1px solid var(--border); background:none; color:var(--text2);">Cancelar</button>
                                                <button type="submit" disabled class="pill project-btn success rmbz-vip-tr-ok" style="flex:1.4; justify-content:center;"><span class="ms">check</span>Concordo e aceito</button>
                                            </form>
                                        </div>
                                    </div>
                                <?php elseif ( $tr && ( $tr['status'] ?? '' ) === 'accepted' ): ?>
                                    <div class="project-state success"><span class="ms project-state-icon">task_alt</span><div class="project-state-body"><div class="project-state-title">Transferência aceite</div><div class="project-state-text">A equipa está a concluir a mudança de titularidade.</div></div></div>
                                <?php endif; ?>

                                <?php // ── Escolha de localização (orçamentos propostos) ──
                                $pb = ( isset( $px['proposed_budgets'] ) && is_array( $px['proposed_budgets'] ) ) ? $px['proposed_budgets'] : [];
                                $loc_ok = (string) ( $px['budget_accepted_location'] ?? '' );
                                if ( ! empty( $pb ) && $loc_ok === '' && empty( $px['budgets_locked'] ) ): ?>
                                    <div class="location-card">
                                        <div class="location-head">
                                            <span class="location-head-icon"><span class="ms">map</span></span>
                                            <div class="location-head-copy">
                                                <div class="location-title">Escolhe o local de gravação</div>
                                                <div class="location-subtitle">Compara as opções preparadas pela produção e seleciona uma localização.</div>
                                            </div>
                                            <span class="location-alert"><span class="ms">priority_high</span>Ação necessária</span>
                                        </div>
                                        <div class="location-options">
                                            <?php foreach ( $pb as $loc_name => $loc_data ): ?>
                                                <article class="location-option">
                                                    <div class="location-option-head">
                                                        <span class="ms location-pin">location_on</span>
                                                        <div><div class="location-option-label">Local de produção</div><div class="location-option-name"><?php echo esc_html( $loc_name ); ?></div></div>
                                                    </div>
                                                    <?php if ( ! empty( $loc_data['items'] ) ): ?>
                                                        <div class="location-items">
                                                            <?php foreach ( (array) $loc_data['items'] as $li ): ?>
                                                                <div class="location-item"><span><?php echo esc_html( $li['desc'] ?? '' ); ?></span><span class="mono"><?php echo esc_html( $fmt( (float) ( $li['cost'] ?? 0 ) ) ); ?> MT</span></div>
                                                            <?php endforeach; ?>
                                                        </div>
                                                    <?php endif; ?>
                                                    <div class="location-total">
                                                        <span class="location-total-label">Orçamento estimado</span>
                                                        <span class="location-total-value"><?php echo esc_html( $fmt( (float) ( $loc_data['total'] ?? 0 ) ) ); ?> <small>MT</small></span>
                                                    </div>
                                                    <form method="post" action="<?php echo esc_url( $post_url ); ?>" data-vip-confirm="Escolher <?php echo esc_attr( $loc_name ); ?> como local de gravação?">
                                                        <input type="hidden" name="action" value="onemz_artist_choose_budget">
                                                        <input type="hidden" name="project_id" value="<?php echo $pid; ?>">
                                                        <input type="hidden" name="chosen_location" value="<?php echo esc_attr( $loc_name ); ?>">
                                                        <?php wp_nonce_field( 'onemz_choose_budget_nonce' ); ?>
                                                        <button type="submit" class="pill location-select"><span class="ms" style="font-size:18px;">check_circle</span>Selecionar <?php echo esc_html( $loc_name ); ?></button>
                                                    </form>
                                                </article>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <?php // ── Itens negociáveis por decidir (adicionados pós-contrato) ──
                                if ( ! empty( $undecided ) ): ?>
                                    <div class="project-section-card">
                                        <div class="project-section-head"><span class="ms project-section-icon">rule</span><div><div class="project-section-title">Itens por decidir</div><div class="project-section-subtitle">Define quem assume cada item acrescentado ao orçamento.</div></div></div>
                                        <form method="post" action="<?php echo esc_url( $post_url ); ?>">
                                            <input type="hidden" name="action" value="onemz_decide_pending_items">
                                            <input type="hidden" name="project_id" value="<?php echo $pid; ?>">
                                            <?php wp_nonce_field( 'onemz_decide_pending_nonce' ); ?>
                                            <?php foreach ( $undecided as $ui => $uit ): ?>
                                                <div class="project-decision-row">
                                                    <div class="project-decision-name"><?php echo esc_html( $uit['desc'] ?? '' ); ?> <span class="mono"><?php echo esc_html( $fmt( (float) ( $uit['cost'] ?? 0 ) ) ); ?> MT</span></div>
                                                    <label class="project-choice"><input type="radio" name="item_assumes[<?php echo (int) $ui; ?>]" value="0" checked>1MZ assume</label>
                                                    <label class="project-choice"><input type="radio" name="item_assumes[<?php echo (int) $ui; ?>]" value="1">Eu assumo</label>
                                                </div>
                                            <?php endforeach; ?>
                                            <button type="submit" class="pill project-btn filled" style="margin-top:12px;"><span class="ms">save</span>Guardar decisões</button>
                                        </form>
                                    </div>
                                <?php endif; ?>

                                <?php // ── Orçamento (a pagar à 1MZ + checklist do artista) ──
                                if ( $oblig > 0 || ! empty( $check_items ) ): ?>
                                    <div class="project-section-card">
                                        <div class="project-section-head"><span class="ms project-section-icon">account_balance_wallet</span><div><div class="project-section-title">Orçamento da produção</div><div class="project-section-subtitle">Resumo financeiro atualizado do projeto.</div></div></div>
                                        <div class="project-metrics">
                                            <div class="project-metric"><div class="project-metric-label">Total devido</div><div class="project-metric-value"><?php echo esc_html( $fmt( $oblig ) ); ?> MT</div></div>
                                            <div class="project-metric success"><div class="project-metric-label">Valor pago</div><div class="project-metric-value"><?php echo esc_html( $fmt( $pago ) ); ?> MT</div></div>
                                            <div class="project-metric<?php echo $falta > 0.01 ? ' danger' : ' success'; ?>"><div class="project-metric-label"><?php echo $falta > 0.01 ? 'Valor pendente' : 'Estado'; ?></div><div class="project-metric-value"><?php echo $falta > 0.01 ? esc_html( $fmt( $falta ) ) . ' MT' : 'Pago'; ?></div></div>
                                        </div>
                                        <?php if ( ! empty( $check_items ) ): ?>
                                            <div class="project-checklist">
                                                <div class="project-section-subtitle" style="margin-bottom:4px;">Itens assumidos pelo artista</div>
                                                <?php foreach ( $check_items as $ci ): ?>
                                                    <div class="project-check-row<?php echo ! empty( $ci['checked'] ) ? ' done' : ''; ?>"><span class="ms"><?php echo ! empty( $ci['checked'] ) ? 'check_circle' : 'schedule'; ?></span><span><?php echo esc_html( $ci['desc'] ?? '' ); ?></span><span class="mono"><?php echo esc_html( $fmt( (float) ( $ci['cost'] ?? 0 ) ) ); ?> MT</span></div>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php endif; ?>
                                        <?php if ( $falta > 0.01 && $contract_accepted && $is_kyc_ok ): ?>
                                            <form method="post" action="<?php echo esc_url( $post_url ); ?>" style="margin-top:12px;" data-vip-confirm="Pagar <?php echo esc_attr( $fmt( $falta ) ); ?> MT com o saldo da carteira?">
                                                <input type="hidden" name="action" value="onemz_pay_project_cost">
                                                <input type="hidden" name="project_id" value="<?php echo $pid; ?>">
                                                <?php wp_nonce_field( 'onemz_pay_project_nonce' ); ?>
                                                <button type="submit" class="pill project-btn success"><span class="ms">account_balance_wallet</span>Pagar <?php echo esc_html( $fmt( $falta ) ); ?> MT</button>
                                            </form>
                                        <?php elseif ( $falta > 0.01 ): ?>
                                            <div class="project-state-text" style="margin-top:10px;">O pagamento fica disponível depois da assinatura do contrato e da validação da identidade.</div>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>

                                <?php // ── Datas de gravação (confirmar / propor / progresso) ──
                                $f_s = (string) ( $px['filming_start'] ?? '' );
                                $f_e = (string) ( $px['filming_end'] ?? '' );
                                $f_conf = ! empty( $px['filming_confirmed_by_artist'] );
                                $f_prop = ( isset( $px['filming_proposed_by_artist'] ) && is_array( $px['filming_proposed_by_artist'] ) ) ? $px['filming_proposed_by_artist'] : null;
                                $filming_finished = in_array( $st, [ 'editing', 'done' ], true ) || ( $fs_days > 0 && $fs_pleft === 0 );
                                $filming_section_allowed = ! in_array( $st, [ 'pending_review', 'rejected', 'correction', 'cancelled_deadline', 'cancelled_no_confirmation' ], true );
                                if ( $filming_finished && $filming_section_allowed ): ?>
                                    <section class="shoot-complete-card" aria-label="Filmagem finalizada">
                                        <span class="ms shoot-complete-icon" aria-hidden="true">check_circle</span>
                                        <div class="shoot-complete-copy">
                                            <div class="shoot-complete-kicker">Filmagem concluída</div>
                                            <div class="shoot-complete-title">Parabéns, a filmagem do teu videoclipe foi finalizada</div>
                                            <div class="shoot-complete-text"><?php echo $st === 'done' ? 'A captação das imagens e a produção deste videoclipe foram concluídas com sucesso.' : 'A captação das imagens terminou e o projeto já avançou para a fase de edição.'; ?></div>
                                            <div class="shoot-complete-meta">
                                                <?php if ( $fs_days > 0 ): ?>
                                                    <span class="shoot-complete-chip"><span class="ms">videocam</span><?php echo (int) $fs_days; ?> <?php echo $fs_days === 1 ? 'dia filmado' : 'dias filmados'; ?></span>
                                                <?php endif; ?>
                                                <span class="shoot-complete-chip"><span class="ms"><?php echo $st === 'done' ? 'task_alt' : 'movie_edit'; ?></span><?php echo $st === 'done' ? 'Projeto concluído' : 'Agora em edição'; ?></span>
                                            </div>
                                        </div>
                                    </section>
                                <?php elseif ( ( $f_s !== '' || $f_e !== '' ) && $filming_section_allowed ): ?>
                                    <div class="shoot-card">
                                        <div class="shoot-head">
                                            <span class="shoot-head-icon"><span class="ms">calendar_month</span></span>
                                            <div class="shoot-head-copy">
                                                <div class="shoot-eyebrow">Planeamento da produção</div>
                                                <div class="shoot-title">Datas de gravação</div>
                                            </div>
                                            <span class="shoot-badge<?php echo $f_conf ? ' success' : ''; ?>">
                                                <span class="ms"><?php echo $f_conf ? 'verified' : ( $f_prop ? 'schedule' : 'priority_high' ); ?></span>
                                                <?php echo esc_html( $f_conf ? 'Confirmado' : ( $f_prop ? 'Em análise' : 'Ação necessária' ) ); ?>
                                            </span>
                                        </div>
                                        <div class="shoot-dates">
                                            <div class="shoot-date">
                                                <span class="ms">start</span>
                                                <div><div class="shoot-date-label">Início</div><div class="shoot-date-value"><?php echo $f_s !== '' ? esc_html( date_i18n( 'd/m/Y', strtotime( $f_s ) ) ) : '—'; ?></div></div>
                                            </div>
                                            <div class="shoot-date">
                                                <span class="ms">flag</span>
                                                <div><div class="shoot-date-label">Fim</div><div class="shoot-date-value"><?php echo $f_e !== '' ? esc_html( date_i18n( 'd/m/Y', strtotime( $f_e ) ) ) : '—'; ?></div></div>
                                            </div>
                                        </div>
                                        <?php if ( $f_conf ): ?>
                                            <div class="shoot-notice">
                                                <span class="ms">check_circle</span>
                                                <div><strong>Datas confirmadas</strong><small>A equipa de produção foi notificada.</small></div>
                                            </div>
                                            <?php
                                            // A data é apenas planeamento. A filmagem só termina quando o admin
                                            // finaliza a sessão e o projeto avança para edição.
                                            if ( $f_s !== '' && $f_e !== '' ):
                                                $fp_end_ts = strtotime( $f_e . ' 00:00:00' ) + DAY_IN_SECONDS;
                                                $fp_now = current_time( 'timestamp' );
                                                if ( $fp_now >= $fp_end_ts ): ?>
                                                    <div class="shoot-notice pending">
                                                        <span class="ms">update</span>
                                                        <div><strong>Período previsto terminado</strong><small>A equipa ainda precisa de finalizar a filmagem no sistema.</small></div>
                                                    </div>
                                                <?php else: ?>
                                                    <div class="shoot-notice pending">
                                                        <span class="ms">schedule</span>
                                                        <div><strong>Término previsto</strong><small>Tempo restante: <b class="mono rmbz-vip-cd" data-until="<?php echo (int) $fp_end_ts; ?>" style="color:var(--text);">—</b></small></div>
                                                    </div>
                                                <?php endif;
                                            endif; ?>
                                        <?php elseif ( $f_prop ): ?>
                                            <div class="shoot-notice pending">
                                                <span class="ms">pending_actions</span>
                                                <div><strong>Nova data enviada</strong><small><?php echo esc_html( date_i18n( 'd/m/Y', strtotime( $f_prop['start'] ?? '' ) ) ); ?> a <?php echo esc_html( date_i18n( 'd/m/Y', strtotime( $f_prop['end'] ?? '' ) ) ); ?>. Aguardando validação da produção.</small></div>
                                            </div>
                                        <?php else: ?>
                                            <p style="font-size:12.5px; color:var(--text2); margin:12px 0 0;">Verifica o período antes de confirmar. Também podes enviar uma nova proposta.</p>
                                            <div class="shoot-actions">
                                                <form method="post" action="<?php echo esc_url( $post_url ); ?>">
                                                    <input type="hidden" name="action" value="onemz_confirm_filming_dates">
                                                    <input type="hidden" name="project_id" value="<?php echo $pid; ?>">
                                                    <?php wp_nonce_field( 'onemz_filming_nonce' ); ?>
                                                    <button type="submit" class="pill" style="background:var(--success); color:#fff; font-size:12.5px;"><span class="ms" style="font-size:18px;">check</span>Confirmar datas</button>
                                                </form>
                                                <button type="button" class="pill rmbz-vip-toggle" data-target="rmbz-vip-prop-<?php echo $pid; ?>" style="border:1px solid var(--border2); background:var(--elev); color:var(--text2); font-size:12.5px;"><span class="ms" style="font-size:18px;">edit_calendar</span>Propor outras datas</button>
                                            </div>
                                            <form method="post" action="<?php echo esc_url( $post_url ); ?>" id="rmbz-vip-prop-<?php echo $pid; ?>" class="shoot-form">
                                                <input type="hidden" name="action" value="onemz_propose_filming_dates">
                                                <input type="hidden" name="project_id" value="<?php echo $pid; ?>">
                                                <?php wp_nonce_field( 'onemz_filming_nonce' ); ?>
                                                <div style="display:flex; gap:10px; flex-wrap:wrap;">
                                                    <label style="flex:1; min-width:140px; font-size:11px; color:var(--muted); font-weight:700;">Novo início<input class="inp" type="date" name="propose_start" required style="margin-top:5px; background:var(--surface);"></label>
                                                    <label style="flex:1; min-width:140px; font-size:11px; color:var(--muted); font-weight:700;">Novo fim<input class="inp" type="date" name="propose_end" required style="margin-top:5px; background:var(--surface);"></label>
                                                </div>
                                                <button type="submit" class="pill" style="margin-top:10px; background:var(--brand); color:var(--on-brand); font-size:12.5px;"><span class="ms" style="font-size:18px;">send</span>Enviar proposta</button>
                                            </form>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>

                                <?php // ── Contrato & identidade (KYC) ──
                                $is_contract_sent = ( $contract_url !== '' );
                                $dl = ! empty( $px['contract_deadline'] ) ? (int) $px['contract_deadline'] : ( ! empty( $px['contract_sent_date'] ) ? (int) $px['contract_sent_date'] + 259200 : 0 );
                                ?>
                                <div class="project-section-card">
                                    <div class="project-section-head"><span class="ms project-section-icon">contract</span><div><div class="project-section-title">Contrato e identidade</div><div class="project-section-subtitle">Documento oficial e validação do titular.</div></div></div>
                                    <?php if ( ! $is_contract_sent ): ?>
                                        <div class="project-state neutral"><span class="ms project-state-icon">draft</span><div class="project-state-body"><div class="project-state-title">Contrato em preparação</div><div class="project-state-text">O documento oficial ficará disponível nesta área.</div></div></div>
                                    <?php elseif ( $contract_rejected ): ?>
                                        <div class="project-state danger"><span class="ms project-state-icon">contract_delete</span><div class="project-state-body"><div class="project-state-title">Contrato recusado</div><div class="project-state-text">Aguarda um documento retificado.<?php if ( ! empty( $px['contract_rejected_reason'] ) ): ?> <b>Motivo enviado:</b> <?php echo esc_html( $px['contract_rejected_reason'] ); ?><?php endif; ?></div></div></div>
                                    <?php elseif ( $kyc_status === 'pending_admin_review' ): ?>
                                        <div class="project-state info"><span class="ms project-state-icon">shield_person</span><div class="project-state-body"><div class="project-state-title">Identidade em análise</div><div class="project-state-text">A equipa de segurança está a validar a fotografia e o documento enviados.</div></div></div>
                                    <?php elseif ( $is_kyc_ok ): ?>
                                        <div class="project-state success"><span class="ms project-state-icon">verified_user</span><div class="project-state-body"><div class="project-state-title">Contrato ativo</div><div class="project-state-text">Identidade validada em nome de <b><?php echo esc_html( $px['contract_real_name'] ?? '' ); ?></b>.</div><div class="project-actions"><button type="button" class="pill project-btn outlined" data-dialog="rmbz-vip-ctr-<?php echo $pid; ?>"><span class="ms">description</span>Ver contrato original</button></div></div></div>
                                    <?php endif; ?>

                                    <?php if ( $is_contract_sent && ( ! $contract_accepted || $kyc_status === 'rejected' ) && ! $contract_rejected ): ?>
                                        <?php if ( $kyc_status === 'rejected' ): ?>
                                            <div class="project-state danger"><span class="ms project-state-icon">no_photography</span><div class="project-state-body"><div class="project-state-title">Fotografia rejeitada</div><div class="project-state-text"><?php echo esc_html( $px['kyc_rejection_reason'] ?? '' ); ?> Envia uma imagem mais nítida.</div></div></div>
                                        <?php endif; ?>
                                        <?php if ( $dl > 0 && ( $dl - time() ) <= 86400 ): ?>
                                            <div class="project-state danger"><span class="ms project-state-icon">timer</span><div class="project-state-body"><div class="project-state-title">Prazo a terminar</div><div class="project-state-text">Tempo restante: <b class="mono rmbz-vip-cd" data-until="<?php echo (int) $dl; ?>">—</b>. Sem aceitação, o projeto será cancelado.</div></div></div>
                                        <?php endif; ?>
                                        <p class="project-state-text" style="margin:6px 0 10px;">Lê o documento antes de aceitar e iniciar a validação da identidade.</p>
                                        <div class="project-actions">
                                            <button type="button" class="pill project-btn filled" data-dialog="rmbz-vip-ctr-<?php echo $pid; ?>"><span class="ms">description</span>Ler contrato</button>
                                            <button type="button" class="pill project-btn success rmbz-vip-toggle" data-target="rmbz-vip-kyc-<?php echo $pid; ?>"><span class="ms">how_to_reg</span>Aceitar e validar</button>
                                            <button type="button" class="pill project-btn outlined rmbz-vip-toggle" data-target="rmbz-vip-rej-<?php echo $pid; ?>"><span class="ms">close</span>Recusar</button>
                                        </div>

                                        <form method="post" action="<?php echo esc_url( $post_url ); ?>" enctype="multipart/form-data" id="rmbz-vip-kyc-<?php echo $pid; ?>" class="project-subform">
                                            <input type="hidden" name="action" value="onemz_accept_contract">
                                            <input type="hidden" name="project_id" value="<?php echo $pid; ?>">
                                            <input type="hidden" name="payment_choice" value="pay_producer">
                                            <?php wp_nonce_field( 'onemz_accept_contract_nonce' ); ?>
                                            <div class="project-section-head"><span class="ms project-section-icon">add_a_photo</span><div><div class="project-section-title">Validação de identidade</div><div class="project-section-subtitle">Fotografia oficial para confirmar o titular.</div></div></div>
                                            <ul style="font-size:12px; color:var(--text2); line-height:1.6; padding-left:16px; margin:8px 0 12px;">
                                                <li>Segura o teu <b>Bilhete de Identidade (BI)</b> na mão ao lado do rosto.</li>
                                                <li>Segura um papel escrito <b>"Aceito o Contrato 1MZ"</b> com a <b>data</b> de hoje.</li>
                                                <li>A foto tem de ser nítida — o nome e o rosto no documento têm de ser legíveis.</li>
                                            </ul>
                                            <?php
                                            // Itens negociáveis: decisão do artista no momento do contrato.
                                            $neg_ct = array_filter( $pi, fn( $it ) => is_array( $it ) && isset( $it['must_pay'] ) && (int) $it['must_pay'] === 0 );
                                            if ( ! empty( $neg_ct ) ): ?>
                                                <div class="project-section-subtitle" style="margin-bottom:6px;">Responsabilidade pelos itens negociáveis</div>
                                                <?php foreach ( $pi as $ci_i => $cit ): if ( ! is_array( $cit ) || ! isset( $cit['must_pay'] ) || (int) $cit['must_pay'] !== 0 ) continue; ?>
                                                    <div class="project-decision-row">
                                                        <div class="project-decision-name"><?php echo esc_html( $cit['desc'] ?? '' ); ?> <span class="mono"><?php echo esc_html( $fmt( (float) ( $cit['cost'] ?? 0 ) ) ); ?> MT</span></div>
                                                        <label class="project-choice"><input type="radio" name="item_assumes[<?php echo (int) $ci_i; ?>]" value="0" <?php checked( empty( $cit['artist_assumes'] ) ); ?>>1MZ assume</label>
                                                        <label class="project-choice"><input type="radio" name="item_assumes[<?php echo (int) $ci_i; ?>]" value="1" <?php checked( ! empty( $cit['artist_assumes'] ) ); ?>>Eu assumo</label>
                                                    </div>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                            <label style="display:block; font-size:11px; font-weight:750; color:var(--muted); letter-spacing:.05em; margin:12px 0 4px;">FOTO (ROSTO + BI + PAPEL)</label>
                                            <input class="inp" type="file" name="kyc_signature_photo" accept="image/*" required>
                                            <label style="display:block; font-size:11px; font-weight:750; color:var(--muted); letter-spacing:.05em; margin:12px 0 4px;">NOME REAL COMPLETO (como no BI — assinatura)</label>
                                            <input class="inp" type="text" name="kyc_real_name" required placeholder="Nome como está no documento">
                                            <button type="submit" class="pill project-btn success" style="margin-top:14px; width:100%; justify-content:center;"><span class="ms">verified_user</span>Aceitar e enviar identidade</button>
                                        </form>

                                        <form method="post" action="<?php echo esc_url( $post_url ); ?>" id="rmbz-vip-rej-<?php echo $pid; ?>" class="project-subform" style="border-color:var(--danger);"
                                              data-vip-confirm="Tens a certeza que queres recusar o contrato? A equipa será notificada com o teu motivo.">
                                            <input type="hidden" name="action" value="onemz_reject_contract">
                                            <input type="hidden" name="project_id" value="<?php echo $pid; ?>">
                                            <?php wp_nonce_field( 'onemz_reject_contract_nonce' ); ?>
                                            <label style="display:block; font-size:11px; font-weight:750; color:var(--muted); letter-spacing:.05em; margin-bottom:4px;">MOTIVO DA RECUSA (vai para a equipa)</label>
                                            <textarea class="inp" name="rejection_reason" rows="3" required placeholder="Explica o que não concordas…"></textarea>
                                            <button type="submit" class="pill project-btn danger" style="margin-top:10px;"><span class="ms">send</span>Enviar recusa</button>
                                        </form>
                                    <?php endif; ?>

                                    <?php if ( $contract_url !== '' ): ?>
                                        <div class="scrim" id="rmbz-vip-ctr-<?php echo $pid; ?>">
                                            <div class="dialog" style="width:min(860px,96vw); height:min(88vh,940px); display:flex; flex-direction:column; padding:18px 20px;">
                                                <div class="project-modal-head">
                                                    <span class="ms project-modal-icon">contract</span>
                                                    <div style="flex:1;"><div style="font-size:15px; font-weight:750;">Contrato Original</div><div style="font-size:11px; color:var(--muted);">Documento oficial — só leitura</div></div>
                                                    <a href="<?php echo esc_url( $contract_url ); ?>" target="_blank" rel="noopener" class="pill project-btn outlined"><span class="ms">download</span>Descarregar</a>
                                                    <button type="button" class="project-icon-btn rmbz-vip-dclose" aria-label="Fechar"><span class="ms" style="font-size:22px;">close</span></button>
                                                </div>
                                                <div style="flex:1; min-height:0; background:var(--elev); border-radius:14px; overflow:hidden;">
                                                    <?php $c_ext = strtolower( (string) pathinfo( (string) parse_url( $contract_url, PHP_URL_PATH ), PATHINFO_EXTENSION ) ); ?>
                                                    <?php if ( in_array( $c_ext, [ 'jpg', 'jpeg', 'png', 'gif', 'webp' ], true ) ): ?>
                                                        <div style="height:100%; overflow:auto; text-align:center; padding:14px;"><img src="<?php echo esc_url( $contract_url ); ?>" alt="Contrato" style="max-width:100%; border-radius:10px;"></div>
                                                    <?php else: ?>
                                                        <object data="<?php echo esc_url( $contract_url ); ?>#toolbar=0" type="application/pdf" style="width:100%; height:100%;">
                                                            <div class="project-doc-empty">
                                                                <span class="ms">description</span>
                                                                <p style="color:var(--text2); font-size:13px; margin:0;">A pré-visualização não está disponível neste navegador.</p>
                                                                <a href="<?php echo esc_url( $contract_url ); ?>" target="_blank" rel="noopener" class="pill project-btn filled"><span class="ms">open_in_new</span>Abrir contrato</a>
                                                            </div>
                                                        </object>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <?php // O guião é um documento operacional permanente: não desaparece depois do KYC. ?>
                                <?php if ( ! empty( $px['script_url'] ) ): ?>
                                    <div class="project-section-card" style="display:flex; align-items:center; gap:12px; flex-wrap:wrap;">
                                        <span class="ms project-section-icon">description</span>
                                        <div style="flex:1; min-width:190px;"><div class="project-section-title">Guião oficial</div><div class="project-section-subtitle">Documento de consulta permanente durante a produção.</div></div>
                                        <a href="<?php echo esc_url( $px['script_url'] ); ?>" target="_blank" rel="noopener" class="pill project-btn filled"><span class="ms">open_in_new</span>Abrir guião</a>
                                    </div>
                                <?php endif; ?>

                                <?php // ── Pitch + guião/roteiro ──
                                if ( ! empty( $px['production_pitch'] ) ): ?>
                                    <div class="project-section-card" style="background:var(--brand-soft);">
                                        <div class="project-section-head"><span class="ms project-section-icon">lightbulb</span><div><div class="project-section-title">Visão criativa</div><div class="project-section-subtitle">Direção proposta pela equipa para o videoclipe.</div></div></div>
                                        <div style="font-size:13px; color:var(--text2); line-height:1.6; white-space:pre-line;"><?php echo esc_html( $px['production_pitch'] ); ?></div>
                                    </div>
                                <?php endif; ?>
                                <?php if ( ! empty( $pr->script_content ) ): ?>
                                    <div class="project-section-card">
                                        <div class="project-section-head"><span class="ms project-section-icon">assignment</span><div><div class="project-section-title">Plano de produção</div><div class="project-section-subtitle">Anotações operacionais da equipa.</div></div></div>
                                        <div style="font-size:12.5px; color:var(--text2); line-height:1.6; max-height:140px; overflow-y:auto; white-space:pre-line;"><?php echo esc_html( $pr->script_content ); ?></div>
                                    </div>
                                <?php endif; ?>

                                <?php // ── Chat com a equipa ──
                                ?>
                                <div class="project-section-card project-live-chat" style="margin-bottom:0;" data-project-id="<?php echo $pid; ?>" data-get-url="<?php echo esc_url( rest_url( '1mz/v1/artist-chat/' . $pid ) ); ?>" data-send-url="<?php echo esc_url( rest_url( '1mz/v1/artist-chat/' . $pid . '/send' ) ); ?>" data-upload-url="<?php echo esc_url( rest_url( '1mz/v1/artist-chat/' . $pid . '/upload' ) ); ?>" data-delete-url="<?php echo esc_url( rest_url( '1mz/v1/artist-chat/' . $pid . '/delete' ) ); ?>">
                                    <button type="button" class="rmbz-vip-toggle" data-target="rmbz-vip-chat-<?php echo $pid; ?>" style="width:100%; border:none; background:none; color:var(--text); font-family:inherit; cursor:pointer; padding:0; display:flex; align-items:center; gap:10px; text-align:left;">
                                        <span class="ms project-section-icon">forum</span><span style="flex:1;"><span class="project-section-title" style="display:block;">Conversa com a equipa</span><span class="project-section-subtitle" style="display:block;">Mensagens e ficheiros do projeto.</span></span><span class="project-chat-live" data-chat-live>Live</span><span class="project-chat-unread" data-chat-unread aria-live="polite" hidden>0</span><span class="ms" style="font-size:20px; color:var(--muted);">expand_more</span>
                                    </button>
                                    <div id="rmbz-vip-chat-<?php echo $pid; ?>" style="display:none; margin-top:12px;">
                                        <div class="project-chat-list" data-chat-list>
                                            <?php if ( ! empty( $pr->artist_feedback ) ): ?>
                                                <?php
                                                $chat_lines = explode( "\n\n", trim( (string) $pr->artist_feedback ) );
                                                $deleted_chat_slots = [];
                                                $deleted_chat_rows = $wpdb->get_results( $wpdb->prepare(
                                                    "SELECT author_type, DATE_FORMAT(created_at, '%%d/%%m/%%Y %%H:%%i') AS minute_label
                                                     FROM {$wpdb->prefix}rmbz_project_chat_messages
                                                     WHERE project_id = %d AND is_deleted = 1",
                                                    $pid
                                                ) );
                                                foreach ( (array) $deleted_chat_rows as $deleted_chat_row ) {
                                                    $deleted_chat_slots[ (string) $deleted_chat_row->author_type . '|' . (string) $deleted_chat_row->minute_label ] = true;
                                                }
                                                $last_confirm_line = null;
                                                foreach ( $chat_lines as $chat_index => $chat_raw_line ) {
                                                    if ( preg_match( '/confirmou as datas de gravação|datas de gravação confirmadas/iu', $chat_raw_line ) ) $last_confirm_line = $chat_index;
                                                }
                                                foreach ( $chat_lines as $chat_index => $msg_line ):
                                                    $msg_line = trim( $msg_line );
                                                    if ( $msg_line === '' ) continue;
                                                    $is_team = ( stripos( $msg_line, 'Admin:' ) !== false || stripos( $msg_line, '1MZ:' ) !== false || stripos( $msg_line, 'Equipa:' ) !== false );
                                                    $msg_date = '';
                                                    if ( preg_match( '/^\[(.*?)\]/', $msg_line, $date_match ) ) {
                                                        $msg_date = (string) $date_match[1];
                                                        $msg_line = substr( $msg_line, strlen( $date_match[0] ) );
                                                    }
                                                    $legacy_author_type = $is_team ? 'admin' : 'artist';
                                                    if ( $msg_date !== '' && isset( $deleted_chat_slots[ $legacy_author_type . '|' . $msg_date ] ) ) continue;
                                                    $is_system_confirm = (bool) preg_match( '/confirmou as datas de gravação|datas de gravação confirmadas/iu', $msg_line );
                                                    $is_system_proposal = (bool) preg_match( '/propôs novas datas de gravação|nova proposta de gravação/iu', $msg_line );
                                                    if ( $is_system_confirm && $last_confirm_line !== $chat_index ) continue;
                                                    $is_system = $is_system_confirm || $is_system_proposal || stripos( $msg_line, 'Sistema:' ) !== false;
                                                    $is_edited = stripos( $msg_line, '(Editado)' ) !== false;
                                                    $msg_line = preg_replace( '/<em[^>]*>\s*\(Editado\)\s*<\/em>/i', '', $msg_line );
                                                    $msg_line = preg_replace( '/<(strong|b)>.*?<\/(strong|b)>:?/i', '', $msg_line );
                                                    $msg_line = preg_replace( '/\b(Artista|Admin|1MZ|Equipa(?:\s+1MZ)?|Sistema):/i', '', $msg_line );
                                                    $msg_line = ltrim( trim( wp_strip_all_tags( $msg_line ) ), ': ' );
                                                    $msg_line = preg_replace( '/^[\p{So}\p{Sk}\x{FE0F}\x{200D}\s]+/u', '', $msg_line );
                                                    $msg_parts = rmbz_vip_chat_extract_attachments( $msg_line );
                                                    $system_title = 'Atualização do projeto';
                                                    $system_detail = $msg_parts['text'];
                                                    $system_icon = 'info';
                                                    if ( $is_system_confirm ) {
                                                        $system_title = 'Datas de gravação confirmadas';
                                                        $system_detail = 'O período definido foi aceite pelo artista.';
                                                        $system_icon = 'event_available';
                                                    } elseif ( $is_system_proposal ) {
                                                        $system_title = 'Nova proposta de datas';
                                                        $system_detail = preg_replace( '/^Propôs novas datas de gravação:\s*/iu', 'Período proposto: ', $system_detail );
                                                        $system_icon = 'edit_calendar';
                                                    }
                                                ?>
                                                    <?php if ( $is_system ): ?>
                                                        <div class="project-chat-event<?php echo $is_system_proposal ? ' proposal' : ''; ?>">
                                                            <span class="ms"><?php echo esc_html( $system_icon ); ?></span>
                                                            <div><div class="project-chat-event-title"><?php echo esc_html( $system_title ); ?></div><div class="project-chat-event-meta"><?php echo esc_html( $system_detail ); ?><?php if ( $msg_date !== '' ): ?> · <?php echo esc_html( $msg_date ); ?><?php endif; ?></div></div>
                                                        </div>
                                                    <?php else: ?>
                                                    <div class="project-chat-message <?php echo $is_team ? 'team' : 'artist'; ?>">
                                                        <div class="project-chat-sender"><?php echo $is_team ? 'Equipa 1MZ' : 'Tu'; ?><?php if ( $msg_date !== '' ): ?> · <span style="font-weight:500; letter-spacing:0; text-transform:none;"><?php echo esc_html( $msg_date ); ?></span><?php endif; ?></div>
                                                        <?php if ( $msg_parts['text'] !== '' ): ?><div class="project-chat-text"><?php echo nl2br( esc_html( $msg_parts['text'] ) ); ?></div><?php endif; ?>
                                                        <?php if ( ! empty( $msg_parts['attachments'] ) ): ?>
                                                            <div style="display:flex; flex-direction:column; gap:7px; margin-top:8px;">
                                                            <?php foreach ( $msg_parts['attachments'] as $attachment ): ?>
                                                                <?php if ( $attachment['is_image'] ): ?>
                                                                    <a href="<?php echo esc_url( $attachment['url'] ); ?>" target="_blank" rel="noopener" style="display:block; max-width:240px; overflow:hidden; border:1px solid var(--border2); border-radius:10px;"><img src="<?php echo esc_url( $attachment['url'] ); ?>" alt="<?php echo esc_attr( $attachment['name'] ); ?>" loading="lazy" style="display:block; width:100%; max-height:190px; object-fit:cover;"></a>
                                                                <?php else: ?>
                                                                    <a href="<?php echo esc_url( $attachment['url'] ); ?>" target="_blank" rel="noopener" class="chip" style="display:inline-flex; align-self:flex-start; text-decoration:none; max-width:240px;"><span class="ms" style="font-size:16px;">attach_file</span><span style="overflow:hidden; text-overflow:ellipsis; white-space:nowrap;"><?php echo esc_html( $attachment['name'] ); ?></span></a>
                                                                <?php endif; ?>
                                                            <?php endforeach; ?>
                                                            </div>
                                                        <?php endif; ?>
                                                        <?php if ( $is_edited ): ?><div style="font-size:9.5px; color:var(--muted); text-align:right; margin-top:5px; font-style:italic;">Editado</div><?php endif; ?>
                                                    </div>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </div>
                                        <form method="post" action="<?php echo esc_url( $post_url ); ?>" class="project-live-chat-form" style="display:flex; gap:10px; flex-wrap:wrap;">
                                            <input type="hidden" name="action" value="onemz_update_feedback">
                                            <input type="hidden" name="project_id" value="<?php echo $pid; ?>">
                                            <?php wp_nonce_field( 'onemz_update_feedback_nonce' ); ?>
                                            <div class="project-chat-upload" data-chat-upload-preview aria-live="polite" hidden>
                                                <span class="ms project-chat-upload-icon" data-chat-upload-icon>draft</span>
                                                <span class="project-chat-upload-copy"><span class="project-chat-upload-name" data-chat-upload-name></span><span class="project-chat-upload-meta" data-chat-upload-meta></span></span>
                                                <button type="button" class="project-chat-upload-remove" data-chat-upload-remove aria-label="Remover anexo"><span class="ms">close</span></button>
                                            </div>
                                            <input type="file" data-chat-file accept="image/jpeg,image/png,image/webp,image/gif,audio/mpeg,audio/mp4,audio/aac,audio/ogg,audio/wav,audio/webm,application/pdf,video/mp4,video/webm,video/quicktime" hidden>
                                            <button type="button" class="project-chat-attach-btn" data-chat-attach aria-label="Anexar ficheiro" title="Anexar imagem, áudio, vídeo ou PDF (máximo 15 MB)" hidden><span class="ms">attach_file</span></button>
                                            <input class="inp" type="text" name="artist_feedback" data-chat-input autocomplete="off" placeholder="Escreve à equipa…" style="flex:1; min-width:0;">
                                            <button type="submit" class="pill project-btn filled" data-chat-send aria-label="Enviar mensagem" disabled><span class="ms">send</span></button>
                                            <div class="project-chat-feedback" data-chat-feedback aria-live="polite"></div>
                                        </form>
                                    </div>
                                </div>

                            <?php endif; ?>
                            <?php endif; // fim do bloqueio de filmagem live ?>
                            </div>
                        </article>
                    <?php $project_accordion_index++; ?>
                    <?php endforeach; ?>
                    </div>

                    <?php // ── Lançamentos concluídos (tab "Meus Lançamentos" do antigo) ──
                    if ( ! empty( $lancamentos ) ): ?>
                        <div class="project-complete-head"><span class="ms">task_alt</span>Projetos concluídos</div>
                        <div class="grid2">
                            <?php foreach ( $lancamentos as $lp ): $lpr = $lp['row']; ?>
                                <div class="card project-complete-card">
                                    <span class="ms" style="width:44px; height:44px; border-radius:14px; background:var(--success-soft); color:var(--success); align-items:center; justify-content:center; font-size:22px;">movie</span>
                                    <div style="flex:1; min-width:160px;">
                                        <div style="font-weight:750; font-size:15px;">«<?php echo esc_html( $lp['titulo'] ); ?>»</div>
                                        <div style="font-size:11.5px; color:var(--muted);"><?php echo ! empty( $lpr->release_date ) ? 'Lançado a ' . esc_html( date_i18n( 'd/m/Y', strtotime( (string) $lpr->release_date ) ) ) : 'Concluído'; ?></div>
                                    </div>
                                    <?php if ( ! empty( $lpr->final_video_url ) ): ?><a href="<?php echo esc_url( $lpr->final_video_url ); ?>" target="_blank" rel="noopener" class="pill project-btn outlined"><span class="ms">download</span>Baixar HD</a><?php endif; ?>
                                    <?php if ( ! empty( $lpr->youtube_url ) ): ?><a href="<?php echo esc_url( $lpr->youtube_url ); ?>" target="_blank" rel="noopener" class="pill project-btn outlined"><?php echo rmbz_vip_social_brand_icon( 'youtube', 17 ); ?>YouTube</a><?php endif; ?>
                                    <?php if ( empty( $lpr->final_video_url ) && empty( $lpr->youtube_url ) ): ?>
                                        <span class="status" style="background:var(--rev-soft); color:var(--rev);"><span class="ms" style="font-size:15px;">schedule</span> Aguardando links da equipa</span>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                    <?php rmbz_vip_render_pager( $project_page, $project_total, $project_per_page, 'proj_page', 'projetos' ); ?>
                <?php endif; ?>
                <?php endif; ?>
            </section>

            <!-- ═══ DISTRIBUIÇÃO ═══ -->
            <section class="sect<?php echo $vip_sect === 'distro' ? ' on' : ''; ?>" data-sect="distro" data-screen-label="Distribuição">
                <?php
                // [1.5.418] OVERVIEW NATIVO (tema do painel). Os fluxos pesados
                // (criar/editar lançamento, detalhe, analytics, splits) são um
                // módulo de 30+ ficheiros com wizard multi-passo — abrem na sua
                // página dedicada em full-screen (dist_url), não embutidos.
                $dist_status_map = [
                    'live'        => [ 'Live',        'success', 'view_release' ],
                    'distribuido' => [ 'Live',        'success', 'view_release' ],
                    'pendente'    => [ 'Em Revisão',  'rev',     'view_release' ],
                    'pending'     => [ 'Em Revisão',  'rev',     'view_release' ],
                    'submitted'   => [ 'Em Revisão',  'rev',     'view_release' ],
                    'approved'    => [ 'Aprovado',    'success', 'view_release' ],
                    'delivered'   => [ 'Em Entrega',  'info',    'view_release' ],
                    'returned'    => [ 'Devolvido',   'danger',  'edit_release' ],
                    'rejected'    => [ 'Rejeitado',   'danger',  'view_release' ],
                    'incomplete'  => [ 'Rascunho',    'muted',   'edit_release' ],
                    'draft'       => [ 'Rascunho',    'muted',   'edit_release' ],
                ];
                $distro_hard_error = function_exists( 'rmbz_distro_artist_access_error' )
                    ? rmbz_distro_artist_access_error( $telemovel, true )
                    : '';
                $distro_route_error = function_exists( 'rmbz_distro_artist_access_error' )
                    ? rmbz_distro_artist_access_error( $telemovel, false )
                    : '';
                ?>
                <?php if ( ! $distro_access || $distro_hard_error !== '' ): ?>
                    <?php rmbz_vip_render_service_gate(
                        'distribution',
                        $distro_gate_reason,
                        $distro_gate_reason === 'restricted' ? $distro_hard_error : ''
                    ); ?>
                <?php elseif ( $distro_route_error !== '' && $vip_dview !== 'somas' ): ?>
                    <div class="card" style="max-width:720px; margin:28px auto; padding:30px; text-align:center; border-color:var(--rev);">
                        <span class="ms" style="width:56px; height:56px; margin:0 auto 14px; border-radius:18px; display:flex; align-items:center; justify-content:center; background:var(--rev-soft); color:var(--rev); font-size:30px;">pending_actions</span>
                        <div style="font-size:19px; font-weight:800;">Conclui primeiro o pedido SOMAS</div>
                        <p style="color:var(--text2); line-height:1.6; margin:8px auto 18px; max-width:520px;"><?php echo esc_html( $distro_route_error ); ?></p>
                        <a class="pill" href="<?php echo esc_url( add_query_arg( [ 'sect' => 'distro', 'dview' => 'somas' ], home_url( '/minha-conta/' ) ) ); ?>" style="display:inline-flex; background:var(--brand); color:var(--on-brand); text-decoration:none;"><span class="ms">verified_user</span> Resolver pedido SOMAS</a>
                    </div>
                <?php else: ?>
                <?php // [1.5.420] Sub-navegação nativa da Distribuição. ?>
                <div class="rmbz-tpx-tabs rvd-tabs" aria-label="Áreas da distribuição">
                    <?php // [1.5.431] Estado "on" das tabs resolvido no servidor (deep-link ?dview=). ?>
                    <?php $distro_tabs = $distro_route_error !== ''
                        ? [ [ 'somas', 'verified_user', 'SOMAS' ] ]
                        : [ [ 'overview', 'grid_view', 'Visão geral' ], [ 'stats', 'monitoring', 'Estatísticas' ], [ 'history', 'history', 'Histórico' ], [ 'profiles', 'verified', 'Perfis nas Lojas' ], [ 'somas', 'verified_user', 'SOMAS' ] ]; ?>
                    <?php foreach ( $distro_tabs as $tb ):
                        $tb_on = $vip_dview === $tb[0] || ( $tb[0] === 'stats' && in_array( $vip_dview, [ 'report', 'release-stats' ], true ) ); ?>
                    <button type="button" class="rvd-tab<?php echo $tb_on ? ' on' : ''; ?>" data-dview="<?php echo esc_attr( $tb[0] ); ?>"><span class="ms"><?php echo esc_html( $tb[1] ); ?></span><?php echo esc_html( $tb[2] ); ?></button>
                    <?php endforeach; ?>
                </div>

                <!-- ─── VISÃO GERAL ─── -->
                <div class="rvd-view" data-dview="overview"<?php echo $vip_dview === 'overview' ? '' : ' hidden'; ?>>
                <div class="distro-summary-grid">
                    <article class="distro-balance-card">
                        <div class="distro-summary-head"><span class="ms distro-summary-icon">payments</span><div class="distro-summary-label">Royalties disponíveis</div></div>
                        <div class="distro-summary-value">$ <?php echo esc_html( number_format( $roy_usd, 2, ',', '.' ) ); ?></div>
                        <div class="distro-summary-meta">≈ <?php echo esc_html( $fmt( $roy_mt ) ); ?> MT ao câmbio atual</div>
                    </article>
                    <article class="distro-summary-card">
                        <div class="distro-summary-head"><span class="ms distro-summary-icon">headphones</span><div class="distro-summary-label">Reproduções</div></div>
                        <div class="distro-summary-value"><?php echo esc_html( number_format( $streams_tot ) ); ?></div>
                        <div class="distro-summary-meta">Streams acumulados no catálogo.</div>
                    </article>
                    <article class="distro-summary-card">
                        <div class="distro-summary-head"><span class="ms distro-summary-icon">album</span><div class="distro-summary-label">Lançamentos</div></div>
                        <div class="distro-summary-value"><?php echo (int) $dist_catalog_total; ?></div>
                        <div class="distro-summary-meta"><?php echo (int) $rel_live; ?> publicados<?php echo $rel_returned > 0 ? ' · ' . (int) $rel_returned . ' devolvido(s)' : ''; ?></div>
                    </article>
                </div>

                <div class="distro-create-banner">
                    <span class="ms distro-create-icon">library_music</span>
                    <div><div class="distro-create-title">A tua música. <span>Os teus royalties.</span></div><div class="distro-create-text">Distribui para as principais lojas e acompanha todo o processo num só lugar.</div></div>
                    <button type="button" class="pill rvd-goview distro-create-action" data-dview="create"><span class="ms">add_circle</span>Novo lançamento</button>
                </div>

                <div class="distro-dsp-grid">
                    <a href="https://artists.spotify.com" target="_blank" rel="noopener" class="distro-dsp-card spotify">
                        <span class="distro-dsp-logo"><?php echo function_exists( 'rmbz_dsp_logo_svg' ) ? rmbz_dsp_logo_svg( 'spotify', 40 ) : '<span class="ms">graphic_eq</span>'; ?></span>
                        <div class="distro-dsp-copy"><div class="distro-dsp-title">Spotify for Artists</div><div class="distro-dsp-text">Reivindicar o perfil de artista</div></div><span class="ms distro-dsp-arrow">arrow_outward</span>
                    </a>
                    <a href="https://artists.apple.com" target="_blank" rel="noopener" class="distro-dsp-card apple">
                        <span class="distro-dsp-logo"><?php echo function_exists( 'rmbz_dsp_logo_svg' ) ? rmbz_dsp_logo_svg( 'apple_music', 40 ) : '<span class="ms">music_note</span>'; ?></span>
                        <div class="distro-dsp-copy"><div class="distro-dsp-title">Apple Music for Artists</div><div class="distro-dsp-text">Consultar estatísticas e perfil</div></div><span class="ms distro-dsp-arrow">arrow_outward</span>
                    </a>
                </div>

                <div class="distro-catalog-head">
                    <span class="ms distro-catalog-icon">library_music</span>
                    <div class="distro-catalog-copy"><div class="distro-catalog-title">Os teus lançamentos</div><div class="distro-catalog-subtitle">Pesquisa, acompanha ou edita o teu catálogo.</div></div>
                    <?php if ( $dist_catalog_total > 0 ): ?><span class="distro-catalog-count"><?php echo (int) $dist_catalog_total; ?> no catálogo</span><?php endif; ?>
                </div>

                <?php if ( $dist_catalog_total > 0 ): ?>
                    <form method="get" action="<?php echo esc_url( home_url( '/minha-conta/' ) ); ?>" class="rvd-catalog-filter distro-filter">
                        <input type="hidden" name="sect" value="distro"><input type="hidden" name="dview" value="overview">
                        <label class="distro-search"><span class="ms">search</span><input class="inp" type="search" name="rel_q" value="<?php echo esc_attr( $dist_search ); ?>" placeholder="Pesquisar por título"></label>
                        <select class="inp" name="rel_type" aria-label="Tipo de lançamento"><option value="">Todos os tipos</option><?php foreach ( [ 'single' => 'Single', 'ep' => 'EP', 'album' => 'Álbum' ] as $filter_key => $filter_label ): ?><option value="<?php echo esc_attr( $filter_key ); ?>" <?php selected( $dist_type_filter, $filter_key ); ?>><?php echo esc_html( $filter_label ); ?></option><?php endforeach; ?></select>
                        <select class="inp" name="rel_status" aria-label="Estado do lançamento"><option value="">Todos os estados</option><?php foreach ( [ 'draft' => 'Rascunho', 'review' => 'Em revisão', 'live' => 'Live', 'returned' => 'Devolvido', 'rejected' => 'Rejeitado' ] as $filter_key => $filter_label ): ?><option value="<?php echo esc_attr( $filter_key ); ?>" <?php selected( $dist_status_filter, $filter_key ); ?>><?php echo esc_html( $filter_label ); ?></option><?php endforeach; ?></select>
                        <button class="pill distro-filter-submit" type="submit"><span class="ms">tune</span>Filtrar</button>
                    </form>
                <?php endif; ?>

                <?php if ( empty( $dist_releases ) ): ?>
                    <div class="distro-empty">
                        <span class="ms">album</span>
                        <?php if ( $dist_catalog_total > 0 ): ?><div class="distro-empty-title">Nenhum lançamento corresponde aos filtros</div><div class="distro-empty-text">Altera a pesquisa ou limpa os filtros para voltares a ver o catálogo.</div><a class="pill home-utility-action outlined" href="<?php echo esc_url( add_query_arg( [ 'sect' => 'distro', 'dview' => 'overview' ], home_url( '/minha-conta/' ) ) ); ?>" style="display:inline-flex;text-decoration:none;">Limpar filtros</a>
                        <?php else: ?><div class="distro-empty-title">Ainda não tens lançamentos</div><div class="distro-empty-text">Distribui a tua música para Spotify, Apple Music, YouTube Music e outras lojas.</div><button type="button" class="pill rvd-goview distro-create-action" data-dview="create"><span class="ms">add_circle</span>Criar primeiro lançamento</button><?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="distro-release-grid">
                        <?php foreach ( $dist_releases as $rel ):
                            $rk = strtolower( (string) $rel->status );
                            [ $r_lbl, $r_tone, $r_act ] = $dist_status_map[ $rk ] ?? [ ucfirst( (string) $rel->status ), 'muted', 'view_release' ];
                            // [1.5.426] Rascunho/devolvido/rejeitado → wizard NATIVO (editar);
                            // live/pendente → estúdio (detalhe).
                            $r_edit = in_array( $rk, [ 'incomplete', 'draft', 'returned' ], true );
                            $r_href = $r_edit
                                ? $dist_url . '?sect=distro&dview=create&rid=' . (int) $rel->id
                                : $dist_url . '?sect=distro&dview=release&rid=' . (int) $rel->id;
                        ?>
                            <a href="<?php echo esc_url( $r_href ); ?>" class="distro-release-link">
                                <article class="distro-release-card">
                                    <div class="distro-release-cover">
                                        <?php if ( $rel->cover_image ): ?>
                                            <img src="<?php echo esc_url( $rel->cover_image ); ?>" alt="Capa de <?php echo esc_attr( $rel->title ?: 'lançamento' ); ?>" loading="lazy">
                                        <?php else: ?>
                                            <div class="distro-release-placeholder"><span class="ms">music_note</span></div>
                                        <?php endif; ?>
                                        <span class="distro-release-status"><span class="distro-release-status-dot" style="background:var(--<?php echo esc_attr( $r_tone === 'muted' ? 'muted' : $r_tone ); ?>);"></span><?php echo esc_html( $r_lbl ); ?></span>
                                    </div>
                                    <div class="distro-release-body">
                                        <div class="distro-release-title"><?php echo esc_html( $rel->title ?: 'Sem título' ); ?></div>
                                        <div class="distro-release-type"><span class="ms">album</span><?php echo esc_html( $rel->release_type ?: 'single' ); ?></div>
                                    </div>
                                </article>
                            </a>
                        <?php endforeach; ?>
                        <button type="button" class="rvd-goview distro-new-release" data-dview="create">
                            <div class="distro-new-release-inner">
                                <span class="ms distro-new-release-icon">add</span>
                                <span class="distro-new-release-label">Novo lançamento</span>
                            </div>
                        </button>
                    </div>
                    <?php rmbz_vip_render_pager( $dist_page, $dist_total, $dist_per_page, 'rel_page', 'distro', [ 'dview' => 'overview', 'rel_q' => $dist_search, 'rel_type' => $dist_type_filter, 'rel_status' => $dist_status_filter ] ); ?>
                <?php endif; ?>

                <div class="distro-quick-grid">
                    <button type="button" class="rvd-goview distro-quick-card" data-dview="stats">
                        <span class="ms distro-quick-icon">monitoring</span>
                        <div class="distro-quick-copy"><div class="distro-quick-title">Estatísticas e relatórios</div><div class="distro-quick-text">Streams e ganhos por faixa, loja e período.</div></div>
                        <span class="ms distro-quick-arrow">arrow_forward</span>
                    </button>
                    <button type="button" class="rvd-goview distro-quick-card" data-dview="profiles">
                        <span class="ms distro-quick-icon">verified</span>
                        <div class="distro-quick-copy"><div class="distro-quick-title">Perfis nas lojas</div><div class="distro-quick-text">Liga os perfis de Spotify, Apple Music e outras plataformas.</div></div>
                        <span class="ms distro-quick-arrow">arrow_forward</span>
                    </button>
                </div>
                </div><!-- /overview -->

                <!-- ─── ESTATÍSTICAS ─── -->
                <div class="rvd-view" data-dview="stats"<?php echo $vip_dview === 'stats' ? '' : ' hidden'; ?>>
                    <div style="display:flex;gap:7px;flex-wrap:wrap;margin-bottom:14px;">
                        <?php foreach ( [ '7d' => '7 dias', '30d' => '30 dias', '90d' => '90 dias', '12m' => '12 meses', 'all' => 'Tudo' ] as $dp_key => $dp_label ): ?>
                            <a class="chip" href="<?php echo esc_url( add_query_arg( [ 'sect' => 'distro', 'dview' => 'stats', 'period' => $dp_key ], home_url( '/minha-conta/' ) ) ); ?>" style="text-decoration:none;<?php echo $dist_period === $dp_key ? 'background:var(--brand);color:var(--on-brand);border-color:var(--brand);' : ''; ?>"><?php echo esc_html( $dp_label ); ?></a>
                        <?php endforeach; ?>
                    </div>
                    <?php
                    $dist_period_streams = array_sum( array_map( static fn( $row ) => (int) $row->s, $dist_daily ) );
                    $dist_period_earnings = array_sum( array_map( static fn( $row ) => (float) $row->e, $dist_daily ) );
                    ?>
                    <div class="grid3">
                        <div style="background:var(--navy); border-radius:26px; padding:24px 28px; color:#fff;">
                            <div style="font-size:11.5px; font-weight:700; letter-spacing:.07em; color:rgba(255,255,255,.7);">GANHOS NO PERÍODO</div>
                            <div class="mono" style="font-size:30px; font-weight:600; margin:8px 0 2px;">$ <?php echo esc_html( number_format( $dist_period_earnings, 2, ',', '.' ) ); ?></div>
                            <div style="font-size:12px; color:rgba(255,255,255,.6);">Dados aprovados dos relatórios</div>
                        </div>
                        <div class="card"><div style="font-size:11.5px; font-weight:700; color:var(--muted); letter-spacing:.07em;">STREAMS NO PERÍODO</div><div class="mono" style="font-size:26px; font-weight:600; margin-top:8px;"><?php echo esc_html( number_format( $dist_period_streams ) ); ?></div></div>
                        <div class="card"><div style="font-size:11.5px; font-weight:700; color:var(--muted); letter-spacing:.07em;">LANÇAMENTOS COM DADOS</div><div class="mono" style="font-size:26px; font-weight:600; margin-top:8px;"><?php echo count( array_filter( $dist_by_release, fn( $r ) => (int) $r->s > 0 ) ); ?></div></div>
                    </div>

                    <?php
                    // Máximo para a barra do gráfico simples de 30 dias.
                    $dist_daily_asc = array_reverse( $dist_daily );
                    $dmax = 1; foreach ( $dist_daily as $dd ) { $dmax = max( $dmax, (int) $dd->s ); }
                    ?>
                    <?php if ( empty( $dist_daily ) ): ?>
                        <div class="card" style="margin-top:20px; text-align:center; padding:40px 24px;">
                            <div style="font-size:40px; opacity:.4;">📊</div>
                            <p style="font-weight:750; margin:8px 0 0;">Ainda sem relatórios</p>
                            <p style="font-size:12.5px; color:var(--muted); margin:4px 0 0; max-width:440px; margin-left:auto; margin-right:auto;">Assim que as lojas reportarem os teus streams (normalmente 1–2 meses após o lançamento ficar live), os números aparecem aqui — por dia, por faixa e por loja.</p>
                        </div>
                    <?php else: ?>
                        <div class="card" style="margin-top:20px;">
                            <div style="font-size:12px; font-weight:750; letter-spacing:.07em; color:var(--brand-ink); margin-bottom:14px;">📈 STREAMS — ÚLTIMOS <?php echo count( $dist_daily_asc ); ?> DIAS</div>
                            <div style="display:flex; align-items:flex-end; gap:4px; height:120px; overflow-x:auto;">
                                <?php foreach ( $dist_daily_asc as $dd ):
                                    $h = max( 3, (int) round( ( (int) $dd->s / $dmax ) * 108 ) ); ?>
                                    <div style="flex:1; min-width:8px; display:flex; flex-direction:column; align-items:center; justify-content:flex-end;" title="<?php echo esc_attr( date_i18n( 'd/m', strtotime( (string) $dd->report_date ) ) . ' · ' . number_format( (int) $dd->s ) . ' streams' ); ?>">
                                        <div style="width:100%; height:<?php echo (int) $h; ?>px; background:linear-gradient(180deg,var(--brand),var(--brand-soft)); border-radius:4px 4px 0 0;"></div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <div style="display:flex; justify-content:space-between; font-size:10px; color:var(--muted); margin-top:6px;">
                                <span><?php echo esc_html( date_i18n( 'd/m', strtotime( (string) $dist_daily_asc[0]->report_date ) ) ); ?></span>
                                <span><?php echo esc_html( date_i18n( 'd/m', strtotime( (string) end( $dist_daily_asc )->report_date ) ) ); ?></span>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if ( ! empty( $dist_by_release ) ): ?>
                        <div style="font-size:12px; font-weight:750; letter-spacing:.07em; color:var(--brand-ink); margin:24px 0 12px;">🏆 POR LANÇAMENTO</div>
                        <div style="display:flex; flex-direction:column; gap:8px;">
                            <?php foreach ( $dist_by_release as $br ): if ( (int) $br->s <= 0 && (float) $br->e <= 0 ) continue; ?>
                                <div class="card" style="display:flex; align-items:center; gap:14px; padding:12px 16px;">
                                    <?php if ( $br->cover_image ): ?><img src="<?php echo esc_url( $br->cover_image ); ?>" style="width:44px; height:44px; border-radius:10px; object-fit:cover;">
                                    <?php else: ?><span class="ms" style="width:44px; height:44px; border-radius:10px; background:var(--elev); color:var(--muted); align-items:center; justify-content:center; font-size:22px;">music_note</span><?php endif; ?>
                                    <div style="flex:1; min-width:0;"><div style="font-weight:700; font-size:13.5px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;"><?php echo esc_html( $br->title ?: 'Sem título' ); ?></div><div style="font-size:11.5px; color:var(--muted);"><?php echo esc_html( number_format( (int) $br->s ) ); ?> streams</div></div>
                                    <div class="mono" style="font-weight:700; color:var(--success); font-size:14px;">$ <?php echo esc_html( number_format( (float) $br->e, 2, ',', '.' ) ); ?></div>
                                    <a class="chip" href="<?php echo esc_url( add_query_arg( [ 'sect' => 'distro', 'dview' => 'release-stats', 'rid' => (int) $br->id ], home_url( '/minha-conta/' ) ) ); ?>" style="text-decoration:none;">Detalhes</a>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                    <?php if ( ! empty( $dist_top_tracks ) ): ?>
                        <div style="font-size:12px;font-weight:750;letter-spacing:.07em;color:var(--brand-ink);margin:24px 0 12px;">TOP FAIXAS</div>
                        <div class="card" style="padding:6px 16px;">
                            <?php foreach ( $dist_top_tracks as $top_i => $top_track ): ?>
                                <div style="display:flex;align-items:center;gap:12px;padding:11px 0;border-bottom:1px solid var(--border);">
                                    <span class="mono" style="width:22px;color:var(--muted);font-weight:700;"><?php echo (int) $top_i + 1; ?></span>
                                    <?php if ( $top_track->cover_image ): ?><img src="<?php echo esc_url( $top_track->cover_image ); ?>" style="width:38px;height:38px;border-radius:9px;object-fit:cover;"><?php endif; ?>
                                    <div style="flex:1;min-width:0;"><div style="font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?php echo esc_html( $top_track->track_title ); ?></div><div style="font-size:10.5px;color:var(--muted);"><?php echo esc_html( $top_track->release_title ); ?></div></div>
                                    <div style="text-align:right;"><b class="mono" style="font-size:12.5px;"><?php echo esc_html( number_format( (int) $top_track->s ) ); ?></b><div style="font-size:10px;color:var(--success);">$ <?php echo esc_html( number_format( (float) $top_track->e, 2 ) ); ?></div></div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                    <?php if ( ! empty( $dist_top_stores ) || ! empty( $dist_top_countries ) ): ?>
                        <div class="grid2" style="margin-top:16px;">
                            <?php foreach ( [ 'Lojas' => $dist_top_stores, 'Países' => $dist_top_countries ] as $break_title => $break_rows ): ?>
                                <div class="card"><div style="font-size:13px;font-weight:800;margin-bottom:9px;">Top <?php echo esc_html( $break_title ); ?></div><?php if ( empty( $break_rows ) ): ?><div style="font-size:12px;color:var(--muted);">Sem dados.</div><?php else: foreach ( $break_rows as $break_row ): ?><div style="display:flex;gap:10px;padding:8px 0;border-bottom:1px solid var(--border);font-size:12px;"><b style="flex:1;"><?php echo esc_html( $break_row->name ?: '—' ); ?></b><span><?php echo esc_html( number_format( (int) $break_row->s ) ); ?></span><span style="color:var(--success);">$<?php echo esc_html( number_format( (float) $break_row->e, 2 ) ); ?></span></div><?php endforeach; endif; ?></div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                    <?php if ( ! empty( $dist_imports ) ): ?>
                        <div style="font-size:12px;font-weight:750;letter-spacing:.07em;color:var(--brand-ink);margin:24px 0 12px;">RELATÓRIOS MENSAIS</div>
                        <div class="grid2">
                            <?php foreach ( $dist_imports as $import ): ?>
                                <a class="card" href="<?php echo esc_url( add_query_arg( [ 'sect' => 'distro', 'dview' => 'report', 'import_id' => (int) $import->id ], home_url( '/minha-conta/' ) ) ); ?>" style="text-decoration:none;color:inherit;display:flex;align-items:center;gap:13px;padding:14px 16px;"><span class="ms" style="width:40px;height:40px;border-radius:12px;background:var(--brand-soft);color:var(--brand-ink);display:flex;align-items:center;justify-content:center;">calendar_month</span><div style="flex:1;"><div style="font-size:13px;font-weight:750;"><?php echo esc_html( function_exists( 'rmbz_analytics_format_period' ) ? rmbz_analytics_format_period( $import->reporting_period ) : $import->reporting_period ); ?></div><div style="font-size:10.5px;color:var(--muted);"><?php echo esc_html( number_format( (int) $import->streams ) ); ?> streams · <?php echo (int) $import->stores_count; ?> loja(s)</div></div><b class="mono" style="color:var(--success);">$ <?php echo esc_html( number_format( (float) $import->earnings_usd, 2 ) ); ?></b><span class="ms" style="color:var(--muted);">chevron_right</span></a>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                    <div style="margin-top:16px;">
                        <a href="<?php echo esc_url( add_query_arg( [ 'distro_action' => 'analytics', 'export' => 'csv', 'period' => $dist_period ], $dist_url ) ); ?>" class="pill" style="border:1px solid var(--border); background:none; color:var(--brand-ink); font-size:12.5px;"><span class="ms" style="font-size:16px;">download</span> Exportar CSV deste período</a>
                    </div>
                </div><!-- /stats -->

                <!-- ─── DETALHE DE RELATÓRIO MENSAL ─── -->
                <div class="rvd-view" data-dview="report"<?php echo $vip_dview === 'report' ? '' : ' hidden'; ?>>
                    <a class="pill" href="<?php echo esc_url( add_query_arg( [ 'sect' => 'distro', 'dview' => 'stats' ], home_url( '/minha-conta/' ) ) ); ?>" style="display:inline-flex;text-decoration:none;border:1px solid var(--border);color:var(--text2);margin-bottom:14px;"><span class="ms">arrow_back</span> Estatísticas</a>
                    <?php if ( ! $rvd_import_detail ): ?>
                        <div class="card" style="text-align:center;padding:38px;">Relatório não encontrado ou sem dados para esta conta.</div>
                    <?php else:
                        $report_header = $rvd_import_detail['header'];
                        $report_daily  = $rvd_import_detail['daily'];
                        $report_max = 1; foreach ( $report_daily as $report_day ) $report_max = max( $report_max, (int) $report_day->streams );
                    ?>
                        <div class="card" style="background:linear-gradient(125deg,var(--navy),#25283d);color:#fff;margin-bottom:14px;">
                            <div style="font-size:12px;color:rgba(255,255,255,.65);">RELATÓRIO MENSAL · 1MZ For Artists</div>
                            <div style="font-size:23px;font-weight:800;margin-top:5px;"><?php echo esc_html( function_exists( 'rmbz_analytics_format_period' ) ? rmbz_analytics_format_period( $report_header->reporting_period ) : $report_header->reporting_period ); ?></div>
                            <div style="display:flex;gap:30px;flex-wrap:wrap;margin-top:18px;"><div><small style="color:rgba(255,255,255,.6);">GANHOS</small><div class="mono" style="font-size:25px;color:#7ee2ad;">$ <?php echo esc_html( number_format( (float) $rvd_import_detail['earnings'], 2 ) ); ?></div></div><div><small style="color:rgba(255,255,255,.6);">STREAMS</small><div class="mono" style="font-size:25px;"><?php echo esc_html( number_format( (int) $rvd_import_detail['streams'] ) ); ?></div></div></div>
                        </div>
                        <?php if ( ! empty( $report_daily ) ): ?><div class="card" style="margin-bottom:14px;"><div style="font-size:13px;font-weight:800;margin-bottom:12px;">Streams por dia</div><div style="display:flex;align-items:flex-end;gap:4px;height:120px;overflow-x:auto;"><?php foreach ( $report_daily as $report_day ): $report_h=max(3,(int)round(((int)$report_day->streams/$report_max)*105)); ?><div title="<?php echo esc_attr( $report_day->day . ' · ' . number_format( (int) $report_day->streams ) ); ?> streams" style="min-width:7px;flex:1;height:<?php echo (int) $report_h; ?>px;background:linear-gradient(180deg,var(--brand),var(--brand-soft));border-radius:4px 4px 0 0;"></div><?php endforeach; ?></div></div><?php endif; ?>
                        <div class="grid3">
                            <?php rmbz_vip_render_stats_breakdown( 'Top músicas', $rvd_import_detail['top_tracks'], 'track_title' ); ?>
                            <?php rmbz_vip_render_stats_breakdown( 'Top lojas', $rvd_import_detail['top_stores'], 'store' ); ?>
                            <?php rmbz_vip_render_stats_breakdown( 'Top países', $rvd_import_detail['top_countries'], 'country_code' ); ?>
                        </div>
                    <?php endif; ?>
                </div><!-- /report -->

                <!-- ─── RELATÓRIO POR LANÇAMENTO ─── -->
                <div class="rvd-view" data-dview="release-stats"<?php echo $vip_dview === 'release-stats' ? '' : ' hidden'; ?>>
                    <a class="pill" href="<?php echo esc_url( add_query_arg( [ 'sect' => 'distro', 'dview' => 'stats' ], home_url( '/minha-conta/' ) ) ); ?>" style="display:inline-flex;text-decoration:none;border:1px solid var(--border);color:var(--text2);margin-bottom:14px;"><span class="ms">arrow_back</span> Estatísticas</a>
                    <?php if ( empty( $rvd_release_stats['release'] ) ): ?>
                        <div class="card" style="text-align:center;padding:38px;">Lançamento não encontrado.</div>
                    <?php else: $release_report = $rvd_release_stats['release']; ?>
                        <div class="card" style="display:flex;align-items:center;gap:16px;margin-bottom:14px;">
                            <?php if ( $release_report->cover_image ): ?><img src="<?php echo esc_url( $release_report->cover_image ); ?>" style="width:72px;height:72px;border-radius:15px;object-fit:cover;"><?php else: ?><span class="ms" style="width:72px;height:72px;border-radius:15px;background:var(--elev);display:flex;align-items:center;justify-content:center;font-size:30px;">album</span><?php endif; ?>
                            <div style="flex:1;"><div style="font-size:11px;color:var(--muted);font-weight:750;">RELATÓRIO DO LANÇAMENTO</div><div style="font-size:20px;font-weight:800;"><?php echo esc_html( $release_report->title ); ?></div></div>
                            <?php if ( ! empty( $rvd_release_stats['has_data'] ) ): ?><div style="text-align:right;"><div class="mono" style="font-size:21px;color:var(--success);">$ <?php echo esc_html( number_format( (float) $rvd_release_stats['earnings'], 2 ) ); ?></div><div style="font-size:11px;color:var(--muted);"><?php echo esc_html( number_format( (int) $rvd_release_stats['streams'] ) ); ?> streams</div></div><?php endif; ?>
                        </div>
                        <?php if ( empty( $rvd_release_stats['has_data'] ) ): ?><div class="card" style="text-align:center;padding:34px;color:var(--muted);">As lojas ainda não enviaram dados deste lançamento.</div><?php else: ?><div class="grid3"><?php rmbz_vip_render_stats_breakdown( 'Faixas', $rvd_release_stats['tracks'], 'track_title' ); ?><?php rmbz_vip_render_stats_breakdown( 'Lojas', $rvd_release_stats['top_stores'], 'store' ); ?><?php rmbz_vip_render_stats_breakdown( 'Países', $rvd_release_stats['top_countries'], 'country_code' ); ?></div><?php endif; ?>
                    <?php endif; ?>
                </div><!-- /release-stats -->

                <!-- ─── HISTÓRICO NATIVO ─── -->
                <div class="rvd-view" data-dview="history"<?php echo $vip_dview === 'history' ? '' : ' hidden'; ?>>
                    <div class="card" style="margin-bottom:14px;">
                        <div style="display:flex; align-items:center; gap:12px; flex-wrap:wrap;">
                            <span class="ms" style="width:42px;height:42px;border-radius:14px;background:var(--brand-soft);color:var(--brand-ink);display:flex;align-items:center;justify-content:center;">history</span>
                            <div style="flex:1;min-width:180px;"><div style="font-size:16px;font-weight:800;">Histórico de atividade</div><div style="font-size:12px;color:var(--muted);">Lançamentos, pagamentos, splits e alterações da conta numa só linha do tempo.</div></div>
                        </div>
                        <div style="display:flex;gap:7px;flex-wrap:wrap;margin-top:14px;">
                            <?php foreach ( [ 'all' => 'Tudo', 'releases' => 'Lançamentos', 'payments' => 'Pagamentos', 'splits' => 'Splits', 'account' => 'Conta' ] as $hf_key => $hf_label ): ?>
                                <a class="chip" href="<?php echo esc_url( add_query_arg( [ 'sect' => 'distro', 'dview' => 'history', 'hfilter' => $hf_key ], home_url( '/minha-conta/' ) ) ); ?>" style="text-decoration:none;<?php echo $rvd_history_filter === $hf_key ? 'background:var(--brand);color:var(--on-brand);border-color:var(--brand);' : ''; ?>"><?php echo esc_html( $hf_label ); ?></a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php if ( empty( $rvd_history_items ) ): ?>
                        <div class="card" style="text-align:center;padding:38px 22px;"><span class="ms" style="font-size:38px;color:var(--muted);">inbox</span><div style="font-weight:750;margin-top:8px;">Ainda não há atividade neste filtro.</div></div>
                    <?php else: ?>
                        <div class="card" style="padding:8px 18px;">
                            <?php foreach ( $rvd_history_items as $history_item ):
                                $history_sev = (string) ( $history_item['severity'] ?? 'info' );
                                $history_tone = [ 'success' => 'success', 'warning' => 'rev', 'error' => 'danger', 'danger' => 'danger', 'info' => 'brand' ][ $history_sev ] ?? 'brand';
                                $history_when = ! empty( $history_item['created_at'] ) ? date_i18n( 'd/m/Y · H:i', strtotime( (string) $history_item['created_at'] ) ) : '';
                            ?>
                                <div style="display:flex;gap:13px;padding:14px 0;border-bottom:1px solid var(--border);">
                                    <span style="width:11px;height:11px;border-radius:50%;background:var(--<?php echo esc_attr( $history_tone ); ?>);margin-top:5px;flex-shrink:0;"></span>
                                    <div style="flex:1;min-width:0;"><div style="font-size:13px;font-weight:750;"><?php echo esc_html( $history_item['heading'] ?? 'Atividade' ); ?></div><?php if ( ! empty( $history_item['sub'] ) ): ?><div style="font-size:12px;color:var(--text2);margin-top:2px;line-height:1.45;"><?php echo esc_html( $history_item['sub'] ); ?></div><?php endif; ?><div style="font-size:10.5px;color:var(--muted);margin-top:5px;"><?php echo esc_html( $history_when ); ?></div></div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div><!-- /history -->

                <!-- ─── PERFIS NAS LOJAS ─── -->
                <div class="rvd-view" data-dview="profiles"<?php echo $vip_dview === 'profiles' ? '' : ' hidden'; ?>>
                    <?php
                    $dist_miss_ess = 0;
                    foreach ( $dist_profiles_cat as $slug => $meta ) { if ( ! empty( $meta['essential'] ) && empty( $dist_profiles_saved[ $slug ] ) ) $dist_miss_ess++; }
                    ?>
                    <div class="card" style="margin-bottom:16px;">
                        <div style="font-weight:750; font-size:15px;">Porque é importante?</div>
                        <p style="font-size:13px; color:var(--text2); line-height:1.6; margin:6px 0 10px;">Quando há vários artistas com o mesmo nome nas lojas, sem o teu perfil exato os royalties podem ir para outra pessoa. Cola aqui os links diretos do <b>teu</b> perfil em cada loja.</p>
                        <?php if ( $dist_miss_ess > 0 ): ?>
                            <div style="border-radius:12px; padding:10px 14px; background:var(--rev-soft); color:var(--rev); font-size:12.5px; font-weight:650;">⚠ Tens <?php echo (int) $dist_miss_ess; ?> perfil(is) essencial(is) por configurar.</div>
                        <?php else: ?>
                            <div style="border-radius:12px; padding:10px 14px; background:var(--success-soft); color:var(--success); font-size:12.5px; font-weight:650;">✓ Todos os perfis essenciais estão configurados.</div>
                        <?php endif; ?>
                    </div>
                    <div id="rvd-profiles" data-nonce="<?php echo esc_attr( wp_create_nonce( 'rmbz_distro_nonce' ) ); ?>" style="display:grid; grid-template-columns:repeat(auto-fill,minmax(280px,1fr)); gap:14px;">
                        <?php foreach ( $dist_profiles_cat as $slug => $meta ):
                            $cur = $dist_profiles_saved[ $slug ] ?? null;
                            $cur_url = $cur ? (string) ( $cur->url ?? '' ) : '';
                        ?>
                            <div class="card rvd-prof" data-dsp="<?php echo esc_attr( $slug ); ?>" style="border-color:<?php echo $cur_url !== '' ? 'var(--success)' : 'var(--border)'; ?>;">
                                <div style="display:flex; align-items:center; gap:10px; margin-bottom:10px;">
                                    <?php // [1.5.421] Logótipo REAL (SVG) da loja; fallback ao emoji. ?>
                                    <span style="width:36px; height:36px; border-radius:10px; overflow:hidden; display:flex; align-items:center; justify-content:center; <?php echo function_exists( 'rmbz_dsp_logo_svg' ) ? '' : 'background:' . esc_attr( $meta['color'] ) . '22; font-size:18px;'; ?>"><?php
                                        echo function_exists( 'rmbz_dsp_logo_svg' ) ? rmbz_dsp_logo_svg( $slug, 36 ) : $meta['icon'];
                                    ?></span>
                                    <div style="flex:1;"><div style="font-weight:750; font-size:14px;"><?php echo esc_html( $meta['name'] ); ?></div><?php if ( ! empty( $meta['essential'] ) ): ?><div style="font-size:10.5px; color:var(--rev); font-weight:700;">ESSENCIAL</div><?php endif; ?></div>
                                    <span class="rvd-prof-ok ms" style="color:var(--success); font-size:20px; <?php echo $cur_url === '' ? 'display:none;' : ''; ?>">check_circle</span>
                                </div>
                                <input class="inp rvd-prof-url" type="url" value="<?php echo esc_attr( $cur_url ); ?>" placeholder="<?php echo esc_attr( $meta['example'] ?? 'https://…' ); ?>" style="font-size:12.5px;">
                                <?php if ( ! empty( $meta['hint'] ) ): ?><p style="font-size:11px; color:var(--muted); margin:6px 0 0;"><?php echo esc_html( $meta['hint'] ); ?></p><?php endif; ?>
                                <div style="display:flex; gap:8px; margin-top:10px;">
                                    <button type="button" class="pill rvd-prof-save" style="background:var(--brand); color:var(--on-brand); font-size:12px; padding:9px 18px;">Guardar</button>
                                    <?php if ( $cur_url !== '' ): ?><a href="<?php echo esc_url( $cur_url ); ?>" target="_blank" rel="noopener" class="pill" style="border:1px solid var(--border); background:none; color:var(--brand-ink); font-size:12px; padding:9px 14px;">Abrir ↗</a><?php endif; ?>
                                    <button type="button" class="pill rvd-prof-clear" style="border:1px solid var(--border); background:none; color:var(--muted); font-size:12px; padding:9px 14px; <?php echo $cur_url === '' ? 'display:none;' : ''; ?>">Limpar</button>
                                </div>
                                <div class="rvd-prof-msg" style="font-size:11.5px; font-weight:650; margin-top:8px; display:none;"></div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div><!-- /profiles -->

                <!-- ─── SOMAS / LICENCIAMENTO ─── -->
                <div class="rvd-view" data-dview="somas"<?php echo $vip_dview === 'somas' ? '' : ' hidden'; ?>>
                    <div class="card" style="margin-bottom:16px; background:linear-gradient(120deg,var(--brand-soft),var(--surface));">
                        <div style="display:flex; align-items:flex-start; gap:14px;">
                            <span class="ms" style="width:42px; height:42px; border-radius:13px; background:var(--brand); color:var(--on-brand); display:flex; align-items:center; justify-content:center; font-size:23px;">verified_user</span>
                            <div>
                                <div style="font-weight:800; font-size:16px;">Registo e licenciamento SOMAS</div>
                                <p style="font-size:12.5px; color:var(--text2); line-height:1.55; margin:5px 0 0;">Faz o registo, acompanha a análise e consulta o teu número SOMAS sem sair da conta.</p>
                            </div>
                        </div>
                    </div>
                    <div class="rvd-somas-native">
                        <?php if ( $vip_sect === 'distro' && function_exists( 'rmbz_licensing_render_somas_form' ) ): ?>
                            <?php rmbz_licensing_render_somas_form( $telemovel ); ?>
                        <?php elseif ( $vip_sect === 'distro' ): ?>
                            <div class="card" style="text-align:center; padding:30px; color:var(--muted);">O serviço SOMAS está temporariamente indisponível.</div>
                        <?php endif; ?>
                    </div>
                </div><!-- /somas -->

                <!-- ─── DETALHE DO RELEASE (nativo) ─── -->
                <div class="rvd-view" data-dview="release"<?php echo $vip_dview === 'release' ? '' : ' hidden'; ?>>
                    <?php if ( $rvd_detail ):
                        $dr = $rvd_detail['row'];
                        $drk = strtolower( (string) $dr->status );
                        [ $d_lbl, $d_tone ] = ( $dist_status_map[ $drk ] ?? [ ucfirst( (string) $dr->status ), 'muted', '' ] );
                        $d_live = in_array( $drk, [ 'live', 'distribuido' ], true );
                        $d_can_edit = in_array( $drk, [ 'incomplete', 'draft', 'returned' ], true );
                        $d_lock_reason = [ 'approved' => 'Já aprovado — em entrega aos DSPs.', 'delivered' => 'Em entrega — a caminho das lojas.', 'live' => 'Nas lojas — para corrigir, pede takedown primeiro.', 'distribuido' => 'Nas lojas — para corrigir, pede takedown primeiro.', 'takedown_requested' => 'Takedown em análise.', 'taken_down' => 'Removido das lojas.', 'rejected' => 'Rejeitado.' ][ $drk ] ?? '';
                    ?>
                        <button type="button" class="pill rvd-goview release-detail-back" data-dview="overview"><span class="ms">arrow_back</span>Voltar ao catálogo</button>
                        <section class="release-hero">
                            <div class="release-hero-cover">
                            <?php if ( $dr->cover_image ): ?>
                                <img src="<?php echo esc_url( $dr->cover_image ); ?>" alt="Capa de <?php echo esc_attr( $dr->title ?: 'lançamento' ); ?>">
                            <?php else: ?>
                                <span class="ms">music_note</span>
                            <?php endif; ?>
                            </div>
                            <div class="release-hero-content">
                                <div class="release-hero-top"><div class="release-hero-heading">
                                    <span class="release-status" style="background:var(--<?php echo esc_attr( $d_tone === 'muted' ? 'muted' : $d_tone ); ?>-soft); color:var(--<?php echo esc_attr( $d_tone === 'muted' ? 'muted' : $d_tone ); ?>);"><?php echo esc_html( $d_lbl ); ?></span>
                                    <div class="release-hero-title"><?php echo esc_html( $dr->title ?: 'Sem título' ); ?></div>
                                    <div class="release-hero-artist"><?php echo esc_html( $nome ); ?></div>
                                </div></div>
                                <div class="release-meta">
                                    <span class="release-meta-chip"><span class="ms">album</span><?php echo esc_html( ucfirst( (string) ( $dr->release_type ?: 'single' ) ) ); ?></span>
                                    <?php if ( $dr->primary_genre ): ?><span class="release-meta-chip"><span class="ms">genres</span><?php echo esc_html( $dr->primary_genre ); ?></span><?php endif; ?>
                                    <?php if ( $dr->release_date ): ?><span class="release-meta-chip"><span class="ms">calendar_today</span><?php echo esc_html( date_i18n( 'd/m/Y', strtotime( (string) $dr->release_date ) ) ); ?></span><?php endif; ?>
                                    <span class="release-meta-chip"><span class="ms">queue_music</span><?php echo count( $rvd_detail['tracks'] ); ?> <?php echo count( $rvd_detail['tracks'] ) === 1 ? 'faixa' : 'faixas'; ?></span>
                                </div>
                                <?php if ( $d_live ): ?>
                                    <div class="release-hero-metrics">
                                        <div class="release-hero-metric"><div class="release-hero-metric-label">Streams</div><div class="release-hero-metric-value"><?php echo esc_html( number_format( $rvd_detail['streams'] ) ); ?></div></div>
                                        <div class="release-hero-metric success"><div class="release-hero-metric-label">Ganhos</div><div class="release-hero-metric-value">$ <?php echo esc_html( number_format( $rvd_detail['earn'], 2, ',', '.' ) ); ?></div></div>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="release-actions">
                            <?php if ( $d_live ): ?>
                                <button type="button" class="pill rvd-goview release-action primary" data-dview="stats"><span class="ms">monitoring</span>Relatório de ganhos</button>
                                <button type="button" class="pill release-action tonal" id="rvd-stores-open"><span class="ms">store</span>Gerir lojas</button>
                                <button type="button" class="pill release-action tonal" id="rvd-splits-open"><span class="ms">groups</span>Configurar splits</button>
                                <button type="button" class="pill release-action danger" data-dialog="rvd-td-scrim"><span class="ms">block</span>Pedir retirada</button>
                            <?php elseif ( $d_can_edit ): ?>
                                <a href="<?php echo esc_url( $dist_url . '?sect=distro&dview=create&rid=' . (int) $dr->id ); ?>" class="pill release-action primary"><span class="ms">edit</span>Editar lançamento</a>
                            <?php elseif ( $d_lock_reason !== '' ): ?>
                                <span class="pill release-action locked"><span class="ms">lock</span>Edição bloqueada · <?php echo esc_html( $d_lock_reason ); ?></span>
                            <?php endif; ?>
                            </div>
                        </section>
                        <?php if ( isset( $_GET['store_ok'] ) ): ?>
                            <div class="release-feedback success"><span class="ms">check_circle</span>Pedido de alteração enviado para análise.</div>
                        <?php elseif ( ! empty( $_GET['store_err'] ) ): ?>
                            <div class="release-feedback danger"><span class="ms">error</span><?php echo esc_html( sanitize_text_field( wp_unslash( $_GET['store_err'] ) ) ); ?></div>
                        <?php endif; ?>

                        <div id="rvd-license-box" class="release-license-box" data-release-id="<?php echo (int) $dr->id; ?>"></div>

                        <?php // ═══ RELEASE TRACKER (stepper 5 fases, igual ao estúdio) ═══
                        $d_ph = (int) $rvd_detail['phase'];
                        if ( $d_ph !== 0 ):
                            $d_steps = [
                                [ 'Submetido', 'Pedido recebido', 'upload_file' ],
                                [ 'Em revisão', 'Equipa 1MZ', 'rate_review' ],
                                [ 'Aprovado', 'Pronto para DSPs', 'verified' ],
                                [ 'Entregue', 'Enviado às lojas', 'outbox' ],
                                [ 'Ao vivo', 'Disponível', 'public' ],
                            ];
                            $d_state = $d_ph === -1 ? [ 'Lançamento rejeitado', 'danger', 'cancel' ] : ( $d_ph === -2 ? [ 'Removido das lojas', 'danger', 'delete' ] : ( $drk === 'returned' ? [ 'Devolvido para correção', 'rev', 'edit_note' ] : ( $d_ph >= 5 ? [ 'Ao vivo nas lojas', 'success', 'public' ] : ( $d_ph === 4 ? [ 'Entregue aos DSPs', 'info', 'outbox' ] : ( $d_ph === 3 ? [ 'Aprovado', 'success', 'verified' ] : [ 'Em revisão · Etapa 2 de 5', 'rev', 'rate_review' ] ) ) ) ) );
                            $d_ph_eff = max( 1, min( 5, $d_ph > 0 ? $d_ph : 1 ) );
                        ?>
                        <section class="release-tracker" aria-label="Progresso do lançamento">
                            <div class="release-tracker-head">
                                <span class="ms release-tracker-icon">route</span>
                                <div class="release-tracker-copy"><div class="release-tracker-kicker">Progresso da distribuição</div><div class="release-tracker-title"><?php echo esc_html( $dr->title ?: 'Sem título' ); ?></div></div>
                                <span class="release-tracker-state" style="background:var(--<?php echo esc_attr( $d_state[1] ); ?>-soft); color:var(--<?php echo esc_attr( $d_state[1] ); ?>);"><span class="ms"><?php echo esc_html( $d_state[2] ); ?></span><?php echo esc_html( $d_state[0] ); ?></span>
                            </div>
                            <?php if ( $d_ph > 0 ): ?>
                            <div class="release-tracker-steps" style="--release-progress:<?php echo (int) round( ( $d_ph_eff - 1 ) / 4 * 100 ); ?>%;">
                                <div class="release-tracker-rail"><span></span></div>
                                <?php foreach ( $d_steps as $si => $stp ): $sn = $si + 1;
                                    $s_done = $sn < $d_ph_eff || $d_ph_eff === 5; $s_cur = $sn === $d_ph_eff && $d_ph_eff < 5; ?>
                                    <div class="release-tracker-step<?php echo $s_done ? ' done' : ( $s_cur ? ' current' : '' ); ?>">
                                        <span class="ms release-tracker-dot"><?php echo $s_done ? 'check' : esc_html( $stp[2] ); ?></span>
                                        <span class="release-tracker-step-title"><?php echo esc_html( $stp[0] ); ?></span>
                                        <span class="release-tracker-step-sub"><?php echo esc_html( $stp[1] ); ?></span>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>

                            <?php // ── Ouvir nas lojas (só quando live) ──
                            if ( $d_ph >= 5 ):
                                $d_listen_stores = [ 'spotify' => 'Spotify', 'apple_music' => 'Apple Music', 'youtube' => 'YouTube Music', 'amazon' => 'Amazon Music', 'tidal' => 'Tidal', 'deezer' => 'Deezer', 'boomplay' => 'Boomplay', 'audiomack' => 'Audiomack' ];
                                $d_logo_slug = [ 'youtube' => 'youtube_music', 'amazon' => 'amazon_music' ];
                                $d_exact_n = 0; foreach ( $rvd_detail['listen'] as $lk ) { if ( ! empty( $lk['is_exact'] ) ) $d_exact_n++; }
                            ?>
                            <div class="release-listen">
                                <div class="release-listen-head"><span class="ms">headphones</span>Ouvir nas lojas<span class="release-listen-note"><?php echo $d_exact_n === 0 ? 'Links de pesquisa até confirmação' : 'Links confirmados'; ?></span></div>
                                <div class="release-store-chips">
                                    <?php foreach ( $d_listen_stores as $lsk => $lsn ):
                                        $lnk = $rvd_detail['listen'][ $lsk ] ?? null;
                                        $l_url = $lnk ? (string) ( $lnk['url'] ?? '' ) : '';
                                        $l_exact = $lnk && ! empty( $lnk['is_exact'] );
                                        $l_logo = $d_logo_slug[ $lsk ] ?? $lsk; ?>
                                        <?php if ( $l_url !== '' ): ?>
                                        <a href="<?php echo esc_url( $l_url ); ?>" target="_blank" rel="noopener" title="<?php echo $l_exact ? '' : 'Link de pesquisa — o link exato ainda não foi confirmado pela equipa'; ?>" class="release-store-chip">
                                            <?php if ( function_exists( 'rmbz_dsp_logo_svg' ) && rmbz_dsp_logo_svg( $l_logo, 17 ) !== '' ): ?><span style="width:17px; height:17px; display:inline-flex;"><?php echo rmbz_dsp_logo_svg( $l_logo, 17 ); ?></span><?php endif; ?>
                                            <?php echo esc_html( $lsn ); ?><?php if ( ! $l_exact ): ?><span class="ms">search</span><?php endif; ?>
                                        </a>
                                        <?php else: ?>
                                        <span title="Em breve" class="release-store-chip pending"><?php echo esc_html( $lsn ); ?></span>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endif; ?>

                            <?php // ── Histórico (timeline, mais recente primeiro) ──
                            if ( ! empty( $rvd_detail['history'] ) ):
                                $d_ev_map = [
                                    'pendente' => [ 'upload_file', 'Submetido para distribuição', 'O lançamento entrou na fila de aprovação.', 'rev' ],
                                    'pending' => [ 'upload_file', 'Submetido para distribuição', 'O lançamento entrou na fila de aprovação.', 'rev' ],
                                    'submitted' => [ 'upload_file', 'Submetido para distribuição', 'O lançamento entrou na fila de aprovação.', 'rev' ],
                                    'returned' => [ 'edit_note', 'Devolvido para correção', 'A equipa identificou pontos a corrigir antes da aprovação.', 'rev' ],
                                    'approved' => [ 'verified', 'Aprovado pela equipa 1MZ', 'Análise completa. O lançamento vai ser enviado aos DSPs.', 'success' ],
                                    'delivered' => [ 'outbox', 'Entregue aos DSPs', 'Ficheiros enviados para Spotify, Apple Music e outros.', 'info' ],
                                    'live' => [ 'public', 'Ao vivo nas lojas', 'A tua música já pode ser ouvida pelos fãs.', 'success' ],
                                    'distribuido' => [ 'public', 'Ao vivo nas lojas', 'A tua música já pode ser ouvida pelos fãs.', 'success' ],
                                    'rejected' => [ 'cancel', 'Rejeitado', 'O lançamento não pôde ser distribuído.', 'danger' ],
                                    'takedown_requested' => [ 'delete', 'Retirada solicitada', 'Pedido de remoção em processamento.', 'danger' ],
                                    'taken_down' => [ 'delete', 'Removido das lojas', 'O lançamento já não está disponível.', 'danger' ],
                                ];
                            ?>
                            <details class="release-history">
                                <summary><span class="ms release-history-summary-icon">history</span><span class="release-history-summary-copy"><span class="release-history-title">Histórico do lançamento</span><span class="release-history-subtitle"><?php echo count( $rvd_detail['history'] ); ?> <?php echo count( $rvd_detail['history'] ) === 1 ? 'atualização registada' : 'atualizações registadas'; ?></span></span><span class="ms release-history-chevron">expand_more</span></summary>
                                <div class="release-timeline">
                                    <?php foreach ( $rvd_detail['history'] as $hi => $hv ):
                                        $hk = strtolower( (string) $hv->to_status );
                                        $he = $d_ev_map[ $hk ] ?? [ 'info', ucfirst( str_replace( '_', ' ', $hk ) ), '', 'muted' ];
                                    ?>
                                    <div class="release-event" style="--event-color:var(--<?php echo esc_attr( $he[3] ); ?>);">
                                        <span class="ms release-event-icon"><?php echo esc_html( $he[0] ); ?></span>
                                        <div class="release-event-copy"><div class="release-event-title"><?php echo esc_html( $he[1] ); ?></div><?php if ( $he[2] !== '' ): ?><div class="release-event-text"><?php echo esc_html( $he[2] ); ?></div><?php endif; ?></div>
                                        <time class="release-event-time"><?php echo esc_html( date_i18n( 'd/m/Y H:i', strtotime( (string) $hv->created_at ) ) ); ?></time>
                                        <?php if ( ! empty( $hv->reason_text ) ): ?><div class="release-event-reason"><?php echo ! empty( $hv->reason_code ) ? '[' . esc_html( $hv->reason_code ) . '] ' : ''; ?><?php echo esc_html( $hv->reason_text ); ?></div><?php endif; ?>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </details>
                            <?php endif; ?>
                        </section>
                        <?php endif; ?>

                        <?php // ═══ LINKS DA LOJA + PERFIS DE ARTISTAS (2 colunas) ═══ ?>
                        <div class="release-info-grid">
                            <section class="release-info-card">
                                <div class="release-section-head">
                                    <span class="ms release-section-icon" aria-hidden="true">link</span>
                                    <div class="release-section-copy">
                                        <div class="release-section-title">Links do lançamento</div>
                                        <div class="release-section-subtitle">Identificadores e páginas oficiais nas lojas.</div>
                                    </div>
                                </div>
                                <div class="release-link-list">
                                    <?php foreach ( $rvd_detail['links'] as $lbl => $lv ): [ $l_val, $l_is_uri ] = $lv; ?>
                                    <div class="release-link-row">
                                        <div class="release-link-label"><?php echo esc_html( strtoupper( $lbl ) ); ?></div>
                                        <?php if ( $l_val === '' ): ?>
                                            <span class="release-link-value is-empty">Disponível depois da distribuição</span>
                                        <?php elseif ( $l_is_uri ): ?>
                                            <span class="release-link-value mono"><?php echo esc_html( $l_val ); ?></span>
                                        <?php else: ?>
                                            <a href="<?php echo esc_url( $l_val ); ?>" target="_blank" rel="noopener" class="release-link-value mono"><?php echo esc_html( $l_val ); ?><span class="ms" aria-hidden="true">open_in_new</span></a>
                                        <?php endif; ?>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </section>
                            <?php
                            $d_prof_n = 0;
                            foreach ( (array) $dist_profiles_saved as $pv ) { if ( $pv && (string) ( $pv->url ?? '' ) !== '' ) $d_prof_n++; }
                            ?>
                            <section class="release-info-card<?php echo $d_prof_n === 0 ? ' attention' : ''; ?>">
                                <div class="release-section-head">
                                    <span class="ms release-section-icon" aria-hidden="true">person_pin</span>
                                    <div class="release-section-copy">
                                        <div class="release-section-title">Perfis de artista</div>
                                        <div class="release-section-subtitle">Associação correta do artista em cada plataforma.</div>
                                    </div>
                                </div>
                                <?php if ( $d_prof_n === 0 ): ?>
                                    <div class="release-profile-state">
                                        <span class="ms" aria-hidden="true">warning</span>
                                        <div>
                                            <strong>Perfis ainda não configurados</strong>
                                            <span>Associa os teus perfis para evitar créditos atribuídos ao artista errado.</span>
                                        </div>
                                    </div>
                                    <button type="button" class="release-profile-action rvd-goview" data-dview="profiles"><span class="ms" aria-hidden="true">settings</span>Configurar perfis</button>
                                <?php else: ?>
                                    <div class="release-profile-state success">
                                        <span class="ms" aria-hidden="true">verified</span>
                                        <div>
                                            <strong><?php echo (int) $d_prof_n; ?> perfil(is) associado(s)</strong>
                                            <span>Os royalties serão encaminhados para os perfis corretos.</span>
                                        </div>
                                    </div>
                                    <button type="button" class="release-profile-action outlined rvd-goview" data-dview="profiles"><span class="ms" aria-hidden="true">edit</span>Gerir perfis</button>
                                <?php endif; ?>
                            </section>
                        </div>

                        <?php // ═══ DETALHES DO LANÇAMENTO (grid, igual ao estúdio) ═══ ?>
                        <section class="release-content-section">
                            <div class="release-section-head">
                                <span class="ms release-section-icon" aria-hidden="true">dataset</span>
                                <div class="release-section-copy">
                                    <div class="release-section-title">Dados do lançamento</div>
                                    <div class="release-section-subtitle">Informação editorial enviada para distribuição.</div>
                                </div>
                            </div>
                            <div class="release-data-grid">
                                <?php foreach ( [
                                    [ 'DATA ORIGINAL', $rvd_detail['date_orig'] ? date_i18n( 'd/m/Y', strtotime( (string) $rvd_detail['date_orig'] ) ) : '' ],
                                    [ 'NOME DA GRAVADORA', (string) ( $dr->label_name ?? '' ) ],
                                    [ 'IDIOMA', (string) ( $dr->language ?? '' ) ],
                                    [ 'GÉNERO PRIMÁRIO', (string) ( $dr->primary_genre ?? '' ) ],
                                    [ 'SUBGÉNERO', (string) ( $dr->secondary_genre ?? '' ) ],
                                    [ 'TERRITÓRIOS', $rvd_detail['terr_txt'] ],
                                    [ 'LOCAL DE GRAVAÇÃO', (string) ( $dr->recording_location ?? '' ) ],
                                ] as $dcell ): ?>
                                <div class="release-data-cell">
                                    <div class="release-data-label"><?php echo esc_html( $dcell[0] ); ?></div>
                                    <div class="release-data-value<?php echo $dcell[1] === '' ? ' is-empty' : ''; ?>"><?php echo $dcell[1] !== '' ? esc_html( $dcell[1] ) : 'Não informado'; ?></div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </section>

                        <?php // Faixas ?>
                        <section class="release-content-section">
                            <div class="release-section-head">
                                <span class="ms release-section-icon" aria-hidden="true">queue_music</span>
                                <div class="release-section-copy">
                                    <div class="release-section-title">Faixas</div>
                                    <div class="release-section-subtitle"><?php echo count( $rvd_detail['tracks'] ); ?> faixa(s) incluída(s) neste lançamento.</div>
                                </div>
                            </div>
                            <div class="release-track-list">
                            <?php foreach ( $rvd_detail['tracks'] as $ti => $trk ): ?>
                                <article class="release-track">
                                    <span class="release-track-number"><?php echo (int) ( $ti + 1 ); ?></span>
                                    <div class="release-track-copy">
                                        <div class="release-track-title"><?php echo esc_html( $trk['title'] ?: 'Sem título' ); ?><?php if ( $trk['explicit'] ): ?><span class="release-track-explicit" title="Conteúdo explícito">E</span><?php endif; ?></div>
                                        <?php if ( $trk['isrc'] ): ?><div class="release-track-isrc mono">ISRC <?php echo esc_html( $trk['isrc'] ); ?></div><?php endif; ?>
                                    </div>
                                    <?php if ( $trk['dur'] ): ?><span class="release-track-duration mono"><?php echo esc_html( $trk['dur'] ); ?></span><?php endif; ?>
                                </article>
                            <?php endforeach; ?>
                            </div>
                        </section>

                        <?php // Lojas escolhidas na distribuição ?>
                        <?php if ( ! empty( $rvd_detail['dsps'] ) ): ?>
                            <section class="release-content-section">
                                <div class="release-section-head">
                                    <span class="ms release-section-icon" aria-hidden="true">storefront</span>
                                    <div class="release-section-copy">
                                        <div class="release-section-title">Distribuição nas lojas</div>
                                        <div class="release-section-subtitle">Plataformas selecionadas para este lançamento.</div>
                                    </div>
                                </div>
                                <div class="release-dsp-list">
                                <?php foreach ( $rvd_detail['dsps'] as $ds => $dname ): ?>
                                    <span class="release-dsp-chip">
                                        <?php if ( function_exists( 'rmbz_dsp_logo_svg' ) && rmbz_dsp_logo_svg( $ds, 18 ) !== '' ): ?><span class="release-dsp-logo"><?php echo rmbz_dsp_logo_svg( $ds, 18 ); ?></span><?php endif; ?>
                                        <?php echo esc_html( $dname ); ?>
                                    </span>
                                <?php endforeach; ?>
                                </div>
                                <div class="release-territories"><span class="ms" aria-hidden="true">public</span><span><strong>Territórios</strong><?php echo esc_html( $rvd_detail['terr_txt'] ); ?></span></div>
                            </section>
                        <?php endif; ?>

                        <?php // ═══ SERVIÇOS EXCLUSIVOS (estados reais do estúdio) ═══ ?>
                        <?php if ( ! empty( $rvd_detail['excl'] ) ): ?>
                            <section class="release-content-section">
                                <div class="release-section-head">
                                    <span class="ms release-section-icon" aria-hidden="true">workspace_premium</span>
                                    <div class="release-section-copy">
                                        <div class="release-section-title">Serviços exclusivos</div>
                                        <div class="release-section-subtitle">Estado dos serviços adicionais deste lançamento.</div>
                                    </div>
                                </div>
                                <div class="release-services">
                                <?php foreach ( $rvd_detail['excl'] as $ex ):
                                    $ex_badge = [
                                        'requested' => [ 'Pedido em análise', 'rev', 'hourglass_top' ],
                                        'approved'  => [ 'Monetização ativa', 'success', 'verified' ],
                                        'rejected'  => [ 'Pedido não aprovado', 'danger', 'cancel' ],
                                        'conflict'  => [ 'Ação necessária', 'danger', 'warning' ],
                                    ][ $ex['status'] ] ?? [ ucfirst( $ex['status'] ), 'muted', 'info' ];
                                ?>
                                <article class="release-service-card">
                                    <div class="release-service-head">
                                        <span class="release-service-logo"><?php echo $ex['ico']; // SVG real ?></span>
                                        <div class="release-service-copy">
                                            <div class="release-service-name"><?php echo esc_html( $ex['name'] ); ?></div>
                                            <span class="release-service-status" style="background:var(--<?php echo esc_attr( $ex_badge[1] ); ?>-soft); color:var(--<?php echo esc_attr( $ex_badge[1] ); ?>);"><span class="ms" aria-hidden="true"><?php echo esc_html( $ex_badge[2] ); ?></span><?php echo esc_html( $ex_badge[0] ); ?></span>
                                        </div>
                                    </div>
                                    <?php if ( $ex['status'] === 'requested' ): ?>
                                        <p class="release-service-body">O teu pedido está a ser revisto pela nossa equipa. Normalmente respondemos em 1–3 dias úteis.</p>
                                    <?php elseif ( $ex['status'] === 'approved' ): ?>
                                        <p class="release-service-body"><?php echo esc_html( $ex['desc_on'] ); ?></p>
                                        <?php if ( $ex['note'] !== '' ): ?><div class="release-service-note"><span class="ms" aria-hidden="true">comment</span><span><strong>Nota da equipa</strong><br><?php echo esc_html( $ex['note'] ); ?></span></div><?php endif; ?>
                                        <?php if ( $ex['key'] === 'yt_content_id' && $rvd_detail['cid'] ): $d_cid_n = count( $rvd_detail['cid']['history'] ); ?>
                                            <?php // [1.5.437] Fluxo REAL do módulo (rmbz_contentid_submit), nativo. ?>
                                            <div style="border-top:1px solid var(--border); margin-top:12px; padding-top:12px;">
                                                <div style="display:flex; align-items:center; gap:12px; flex-wrap:wrap;">
                                                    <button type="button" class="pill" id="rvd-cid-open" style="background:#FF0000; color:#fff; font-size:12px; border:0; font-family:inherit; cursor:pointer;"><span class="ms" aria-hidden="true">remove_circle_outline</span>Pedir remoção de claim</button>
                                                    <?php if ( $d_cid_n > 0 ): ?>
                                                        <button type="button" id="rvd-cid-htoggle" style="border:0; background:none; color:var(--muted); font-size:12px; text-decoration:underline; cursor:pointer; font-family:inherit;">Ver histórico (<?php echo (int) $d_cid_n; ?>) ▾</button>
                                                    <?php endif; ?>
                                                </div>
                                                <?php if ( $d_cid_n > 0 ): ?>
                                                <div id="rvd-cid-history" hidden style="display:flex; flex-direction:column; gap:6px; margin-top:10px;">
                                                    <?php foreach ( $rvd_detail['cid']['history'] as $cr ):
                                                        $cr_tone = $cr->status === 'aprovado' ? 'success' : ( $cr->status === 'rejeitado' ? 'danger' : 'rev' );
                                                        $cr_pill = $cr->status === 'pendente' ? 'Em análise' : ( $cr->status === 'aprovado' ? 'Aprovado' : 'Rejeitado' );
                                                    ?>
                                                    <div style="display:flex; align-items:center; gap:10px; border:1px solid var(--border); border-left:3px solid var(--<?php echo esc_attr( $cr_tone ); ?>); border-radius:10px; background:var(--elev); padding:8px 12px;">
                                                        <div style="flex:1; min-width:0;">
                                                            <a href="<?php echo esc_url( $cr->video_url ); ?>" target="_blank" rel="noopener" style="font-size:12px; word-break:break-all;"><?php echo esc_html( wp_trim_words( (string) $cr->video_url, 8, '...' ) ); ?></a>
                                                            <div style="font-size:11px; color:var(--muted);">há <?php echo esc_html( human_time_diff( strtotime( (string) $cr->created_at ), time() ) ); ?><?php if ( ! empty( $cr->admin_response ) ): ?> · <em>"<?php echo esc_html( wp_trim_words( (string) $cr->admin_response, 10, '...' ) ); ?>"</em><?php endif; ?></div>
                                                        </div>
                                                        <span class="status" style="background:var(--<?php echo esc_attr( $cr_tone ); ?>-soft); color:var(--<?php echo esc_attr( $cr_tone ); ?>);"><?php echo esc_html( $cr_pill ); ?></span>
                                                    </div>
                                                    <?php endforeach; ?>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        <?php elseif ( $ex['key'] === 'yt_content_id' ): ?>
                                            <span class="status" style="margin-top:12px; background:var(--rev-soft); color:var(--rev);">Gestão disponível após a ativação ser confirmada</span>
                                        <?php endif; ?>
                                    <?php elseif ( $ex['status'] === 'rejected' ): ?>
                                        <p class="release-service-body">O teu pedido para este serviço não foi aprovado.</p>
                                        <?php if ( $ex['note'] !== '' ): ?><div class="release-service-note" style="background:var(--danger-soft);color:var(--danger);"><span class="ms" aria-hidden="true">error</span><span><strong>Motivo</strong><br><?php echo esc_html( $ex['note'] ); ?></span></div><?php endif; ?>
                                    <?php elseif ( $ex['status'] === 'conflict' ): ?>
                                        <p class="release-service-body">Foi detetado que esta música pode já estar registada por outro distribuidor ou titular. Enquanto o conflito não for resolvido, a monetização não pode ser ativada.</p>
                                        <div style="font-size:12px; background:var(--danger-soft); border-radius:10px; padding:10px 14px; margin-top:8px; color:var(--text2);">
                                            <?php if ( $ex['note'] !== '' ): ?><div><b>Descrição:</b> <?php echo esc_html( $ex['note'] ); ?></div><?php endif; ?>
                                            <?php if ( $ex['c_src'] !== '' ): ?><div style="margin-top:4px;"><b>Distribuidor / titular suspeito:</b> <?php echo esc_html( $ex['c_src'] ); ?></div><?php endif; ?>
                                            <?php if ( $ex['c_url'] !== '' ): ?><div style="margin-top:4px;"><b>Evidência:</b> <a href="<?php echo esc_url( $ex['c_url'] ); ?>" target="_blank" rel="noopener" style="word-break:break-all;"><?php echo esc_html( $ex['c_url'] ); ?></a></div><?php endif; ?>
                                        </div>
                                        <div style="font-size:12px; color:var(--text2); margin-top:8px;">O que fazer? Contacta a equipa 1MZ com provas de titularidade (contratos, ficheiros originais) para resolvermos o conflito.</div>
                                    <?php endif; ?>
                                </article>
                                <?php endforeach; ?>
                                </div>
                            </section>
                        <?php endif; ?>
                        <?php // [1.5.437] Modal NATIVO "Pedir remoção de claim" —
                              // mesmo contrato do módulo: rmbz_contentid_submit
                              // (_nonce rmbz_cid_submit, release_id, video_url,
                              // reason, tracks JSON) + check_pending no input. ?>
                        <?php if ( $rvd_detail['cid'] ): $d_cid_multi = count( $rvd_detail['cid']['tracks'] ) > 1; ?>
                        <div class="scrim" id="rvd-cid-scrim" data-nonce="<?php echo esc_attr( $rvd_detail['cid']['nonce'] ); ?>" data-rid="<?php echo (int) $dr->id; ?>">
                            <div class="dialog" style="width:min(560px,96vw); max-height:92vh; display:flex; flex-direction:column;">
                                <div style="display:flex; align-items:center; gap:10px; margin-bottom:12px;">
                                    <div style="flex:1; display:flex; align-items:center; gap:8px; font-size:15.5px; font-weight:750;"><span class="ms" aria-hidden="true">smart_display</span>Pedir remoção de claim Content ID</div>
                                    <button type="button" class="rvd-cid-x" style="border:none; background:none; color:var(--muted); cursor:pointer; display:flex;"><span class="ms" style="font-size:22px;">close</span></button>
                                </div>
                                <div style="flex:1; overflow-y:auto; min-height:0;">
                                    <label class="rvu-lbl">URL do vídeo YouTube *</label>
                                    <input type="url" class="inp" id="rvd-cid-url" placeholder="https://www.youtube.com/watch?v=..." autocomplete="off" style="font-size:13px;">
                                    <div style="font-size:11px; color:var(--muted); margin-top:4px;">Aceita formatos: youtube.com/watch?v=…, youtu.be/…, youtube.com/shorts/…</div>
                                    <div id="rvd-cid-warn" hidden style="border-radius:10px; padding:8px 12px; margin-top:8px; background:var(--rev-soft); color:var(--rev); font-size:12px;">⚠ Já existe um pedido pendente para este vídeo. Podes submeter mesmo assim mas será marcado como duplicado.</div>
                                    <?php if ( $d_cid_multi ): ?>
                                        <label class="rvu-lbl" style="margin-top:14px;">Faixas afectadas *</label>
                                        <div style="font-size:11px; color:var(--muted); margin-bottom:6px;">Marca pelo menos uma. Se for o álbum inteiro, marca "Todas".</div>
                                        <div style="border:1px solid var(--border); border-radius:12px; background:var(--elev); padding:8px; max-height:200px; overflow-y:auto; display:flex; flex-direction:column; gap:2px;">
                                            <label style="display:flex; gap:8px; align-items:center; font-size:12.5px; cursor:pointer; padding:6px 8px; border-bottom:1px solid var(--border);"><input type="checkbox" id="rvd-cid-all"> <b>Todas as faixas</b></label>
                                            <?php foreach ( $rvd_detail['cid']['tracks'] as $ct ): ?>
                                                <label style="display:flex; gap:8px; align-items:center; font-size:12.5px; cursor:pointer; padding:6px 8px;"><input type="checkbox" class="rvd-cid-cb" data-track-id="<?php echo (int) $ct['id']; ?>"> #<?php echo (int) $ct['num']; ?> — <?php echo esc_html( $ct['title'] ?: 'Faixa ' . (int) $ct['num'] ); ?></label>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php else: ?>
                                        <input type="hidden" id="rvd-cid-single" value="<?php echo (int) ( $rvd_detail['cid']['tracks'][0]['id'] ?? 0 ); ?>">
                                    <?php endif; ?>
                                    <label class="rvu-lbl" style="margin-top:14px;">Motivo <span style="font-weight:400; color:var(--muted);">(opcional, ajuda a equipa a entender)</span></label>
                                    <textarea class="inp" id="rvd-cid-reason" rows="4" placeholder="Ex: este vídeo é meu (canal X). O meu próprio áudio está a bloquear. Por favor remover claim." style="font-size:13px; resize:vertical;"></textarea>
                                    <div id="rvd-cid-fb" style="font-size:12px; color:var(--danger); min-height:16px; margin-top:8px;"></div>
                                </div>
                                <div style="display:flex; gap:10px; margin-top:12px;">
                                    <button type="button" class="pill rvd-cid-x" style="border:1px solid var(--border); background:none; color:var(--text2);">Cancelar</button>
                                    <button type="button" class="pill" id="rvd-cid-send" style="flex:1; justify-content:center; background:#FF0000; color:#fff;">📨 Enviar pedido</button>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if ( $d_live ): ?>
                        <div class="scrim" id="rvd-td-scrim" data-rid="<?php echo (int) $dr->id; ?>">
                            <div class="dialog" style="width:min(560px,96vw); max-height:92vh; display:flex; flex-direction:column;">
                                <div style="display:flex; align-items:center; gap:10px; margin-bottom:12px;">
                                    <div style="flex:1;">
                                        <div style="font-size:15.5px; font-weight:800;">Retirar das lojas</div>
                                        <div style="font-size:12px; color:var(--muted); margin-top:2px;"><?php echo esc_html( $dr->title ?: 'Lançamento' ); ?></div>
                                    </div>
                                    <button type="button" class="rmbz-vip-dclose" aria-label="Fechar" style="border:none; background:none; color:var(--muted); cursor:pointer; display:flex;"><span class="ms" style="font-size:22px;">close</span></button>
                                </div>
                                <div style="overflow-y:auto; min-height:0;">
                                    <div id="rvd-td-check" style="border-radius:12px; padding:11px 13px; background:var(--elev); color:var(--text2); font-size:12.5px; line-height:1.5; margin-bottom:13px;">A verificar se este lançamento pode ser retirado…</div>
                                    <label class="rvu-lbl" for="rvd-td-code">Motivo *</label>
                                    <select class="inp" id="rvd-td-code" style="font-size:13px;">
                                        <option value="">Seleciona um motivo</option>
                                        <option value="rights">Direitos de autor ou licença expirada</option>
                                        <option value="metadata_error">Erro na faixa ou nos metadados</option>
                                        <option value="relaunch">Vou relançar uma nova versão</option>
                                        <option value="collaborator">Conflito com colaborador</option>
                                        <option value="other">Outro motivo</option>
                                    </select>
                                    <label class="rvu-lbl" for="rvd-td-reason" style="margin-top:14px;">Detalhes <span style="font-weight:400; color:var(--muted);">(obrigatório para “Outro”)</span></label>
                                    <textarea class="inp" id="rvd-td-reason" rows="4" maxlength="1000" placeholder="Explica o que aconteceu para a equipa analisar o pedido." style="font-size:13px; resize:vertical;"></textarea>
                                    <div style="border-radius:12px; padding:11px 13px; background:var(--danger-soft); color:var(--danger); font-size:12px; line-height:1.5; margin-top:13px;">A retirada é analisada pela equipa e pode afetar links, playlists, estatísticas e valores de colaboradores. Esta ação não é imediata.</div>
                                    <div id="rvd-td-fb" role="status" aria-live="polite" style="font-size:12px; min-height:18px; margin-top:10px;"></div>
                                </div>
                                <div style="display:flex; gap:10px; margin-top:12px;">
                                    <button type="button" class="pill rmbz-vip-dclose" style="border:1px solid var(--border); background:none; color:var(--text2);">Cancelar</button>
                                    <button type="button" class="pill" id="rvd-td-send" disabled style="flex:1; justify-content:center; background:var(--danger); color:#fff;">Enviar pedido</button>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if ( function_exists( 'rmbz_splits_frontend_render_modal' ) ): ?>
                            <?php rmbz_splits_frontend_render_modal( $dr ); ?>
                        <?php endif; ?>
                        <?php if ( $d_live && function_exists( 'rmbz_store_render_modal' ) ): ?>
                            <?php rmbz_store_render_modal( (int) $dr->id, $telemovel ); ?>
                        <?php endif; ?>
                    <?php else: ?>
                        <div class="card" style="text-align:center; padding:40px;"><div style="font-size:40px; opacity:.4;">🔍</div><p style="font-weight:700; margin:8px 0 0;">Lançamento não encontrado.</p><button type="button" class="pill rvd-goview" data-dview="overview" style="margin-top:12px; background:var(--brand); color:var(--on-brand);">Voltar</button></div>
                    <?php endif; ?>
                </div><!-- /release -->

                <!-- ─── CRIAR LANÇAMENTO (wizard nativo) ─── -->
                <div class="rvd-view" data-dview="create"<?php echo $vip_dview === 'create' ? '' : ' hidden'; ?>
                     data-nonce="<?php echo esc_attr( $rvd_nonce_distro ); ?>"
                     data-unonce="<?php echo esc_attr( $rvd_nonce_upload ); ?>"
                     <?php if ( $rvw_edit ): ?>data-edit="<?php echo esc_attr( wp_json_encode( $rvw_edit ) ); ?>"<?php endif; ?>>
                    <div style="display:flex; align-items:center; gap:12px; margin-bottom:16px;">
                        <button type="button" class="pill rvd-goview" data-dview="overview" style="border:1px solid var(--border); background:none; color:var(--text2); font-size:12.5px;"><span class="ms" style="font-size:17px;">arrow_back</span> Voltar</button>
                        <div style="flex:1; font-family:'Bricolage Grotesque',sans-serif; font-size:20px; font-weight:700;"><?php echo $rvw_edit ? 'Editar lançamento' : 'Novo lançamento'; ?></div>
                        <?php if ( $rvw_edit && in_array( $rvw_edit['status'], [ 'incomplete', 'draft' ], true ) ): ?>
                            <form method="get" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" data-vip-confirm="Apagar definitivamente este rascunho e os ficheiros associados?">
                                <input type="hidden" name="action" value="onemz_delete_release">
                                <input type="hidden" name="release_id" value="<?php echo (int) $rvw_edit['id']; ?>">
                                <input type="hidden" name="redirect" value="vip">
                                <input type="hidden" name="_wpnonce" value="<?php echo esc_attr( wp_create_nonce( 'rmbz_delete_release_nonce' ) ); ?>">
                                <button type="submit" class="pill" style="border:1px solid var(--danger); background:var(--danger-soft); color:var(--danger); font-size:12px;"><span class="ms" style="font-size:17px;">delete</span> Apagar rascunho</button>
                            </form>
                        <?php endif; ?>
                    </div>

                    <?php if ( $rvw_edit_release && (string) $rvw_edit_release->status === 'returned' && function_exists( 'rmbz_render_return_panel_for_artist' ) ): ?>
                        <?php rmbz_render_return_panel_for_artist( $rvw_edit_release ); ?>
                    <?php endif; ?>

                    <?php // Stepper ?>
                    <div style="display:flex; gap:6px; margin-bottom:20px;">
                        <?php foreach ( [ '1 Detalhes','2 Lojas','3 Faixas','4 Capa' ] as $si => $slbl ): ?>
                            <div class="rvw-step" data-step="<?php echo $si + 1; ?>" style="flex:1; text-align:center; padding:10px 6px; border-radius:12px; font-size:12px; font-weight:700; background:<?php echo $si === 0 ? 'var(--brand-soft)' : 'var(--elev)'; ?>; color:<?php echo $si === 0 ? 'var(--brand-ink)' : 'var(--muted)'; ?>;"><?php echo esc_html( $slbl ); ?></div>
                        <?php endforeach; ?>
                    </div>

                    <input type="hidden" id="rvw-release-id" value="0">
                    <div id="rvw-msg" style="display:none; border-radius:12px; padding:11px 15px; font-size:12.5px; font-weight:650; margin-bottom:14px;"></div>

                    <!-- PASSO 1 — DETALHES -->
                    <div class="rvw-panel" data-step="1">
                        <div class="card">
                            <div><label class="rvu-lbl">Título do lançamento *</label><input class="inp" type="text" id="rvw-title" maxlength="150" placeholder="Nome do single, EP ou álbum"></div>
                            <div style="margin-top:12px;"><label class="rvu-lbl">Artista principal</label><input class="inp" type="text" value="<?php echo esc_attr( $nome ); ?>" readonly style="opacity:.7;"></div>
                            <div class="grid2" style="margin-top:12px;">
                                <div><label class="rvu-lbl">Idioma *</label><select class="inp" id="rvw-language"><option value="Portuguese">Português</option><option value="English">Inglês</option><option value="Spanish">Espanhol</option></select></div>
                                <div><label class="rvu-lbl">Género *</label><select class="inp" id="rvw-genre"><option value="">— Selecione —</option><?php foreach ( $rvd_genres as $g ) echo '<option value="' . esc_attr( $g ) . '">' . esc_html( $g ) . '</option>'; ?></select></div>
                            </div>
                            <label class="rvu-lbl" style="margin-top:14px;">Tipo de lançamento *</label>
                            <div style="display:grid; grid-template-columns:repeat(3,1fr); gap:10px;">
                                <?php foreach ( [ [ 'single','🎵','Single','1–3 faixas' ], [ 'ep','💿','EP','4–6 faixas' ], [ 'album','📀','Álbum','7+ faixas' ] ] as $ti => $t ): ?>
                                    <label class="rvw-type" data-type="<?php echo esc_attr( $t[0] ); ?>" style="text-align:center; border:2px solid <?php echo $ti === 0 ? 'var(--brand)' : 'var(--border)'; ?>; background:<?php echo $ti === 0 ? 'var(--brand-soft)' : 'var(--elev)'; ?>; border-radius:14px; padding:14px 8px; cursor:pointer;">
                                        <input type="radio" name="rvw_type" value="<?php echo esc_attr( $t[0] ); ?>" <?php checked( $ti, 0 ); ?> style="display:none;">
                                        <span style="font-size:24px;"><?php echo $t[1]; ?></span>
                                        <div style="font-weight:700; font-size:13.5px; margin-top:4px;"><?php echo esc_html( $t[2] ); ?></div>
                                        <div style="font-size:11px; color:var(--muted);"><?php echo esc_html( $t[3] ); ?></div>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                            <div style="margin-top:14px;">
                                <label class="rvu-lbl">Data de lançamento *</label>
                                <?php
                                // [1.5.424] Date-picker INTELIGENTE do módulo (sugestão 1MZ,
                                // calendário, catálogo antigo). Rende os hidden release_date
                                // (Y-m-d) + is_legacy que o wizard lê no submit.
                                if ( function_exists( 'rmbz_render_date_picker' ) ) {
                                    rmbz_render_date_picker( [
                                        'name'           => 'release_date',
                                        'value'          => '',
                                        'min_date'       => date_i18n( 'Y-m-d', current_time( 'timestamp' ) + 7 * DAY_IN_SECONDS ),
                                        'suggested_days' => 14,
                                        'required'       => true,
                                        'placeholder'    => 'Escolher data…',
                                        'hint'           => 'Mínimo 7 dias a partir de hoje. Recomendamos pelo menos 2 semanas.',
                                        'allow_legacy'   => true,
                                        'legacy_field'   => 'is_legacy',
                                        'legacy_value'   => '',
                                    ] );
                                } else {
                                    echo '<input class="inp" type="date" name="release_date" min="' . esc_attr( date_i18n( 'Y-m-d', current_time( 'timestamp' ) + 7 * DAY_IN_SECONDS ) ) . '">';
                                    echo '<input type="hidden" name="is_legacy" value="">';
                                }
                                ?>
                            </div>
                            <details style="margin-top:12px;"><summary style="cursor:pointer; font-size:12.5px; color:var(--brand-ink); font-weight:650;">Opções avançadas</summary>
                                <div style="margin-top:10px;"><label class="rvu-lbl">Editora (label)</label><input class="inp" type="text" id="rvw-label" placeholder="Nome da editora (opcional)"></div>
                                <div style="margin-top:10px;"><label class="rvu-lbl">Local de gravação</label><input class="inp" type="text" id="rvw-recloc" placeholder="Ex.: Maputo (opcional)"></div>
                                <div style="margin-top:10px;"><label class="rvu-lbl">UPC / EAN</label><input class="inp" type="text" id="rvw-upc" inputmode="numeric" maxlength="13" placeholder="12 ou 13 dígitos (opcional)"></div>
                            </details>
                            <button type="button" class="pill" id="rvw-next-1" style="margin-top:18px; width:100%; justify-content:center; background:var(--brand); color:var(--on-brand); padding:14px;">Guardar e continuar</button>
                        </div>
                    </div>

                    <!-- PASSO 2 — LOJAS + TERRITÓRIOS + EXCLUSIVOS -->
                    <div class="rvw-panel" data-step="2" hidden>
                        <?php // ── Territórios ── ?>
                        <div class="card" style="margin-bottom:16px;">
                            <div style="font-weight:750; font-size:15px;">🌍 Territórios</div>
                            <p style="font-size:12.5px; color:var(--muted); margin:2px 0 12px;">Onde tens direitos para lançar a obra?</p>
                            <input type="hidden" id="rvw-terr-mode" value="worldwide">
                            <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:10px;">
                                <?php foreach ( [ [ 'worldwide','🌐','Todo o mundo','Recomendado' ], [ 'worldwide_except','🚫','Excluir','Mundo exceto alguns' ], [ 'selected','📍','Escolher países','Apenas os marcados' ] ] as $tmi => $tm ): ?>
                                    <button type="button" class="rvw-terr" data-mode="<?php echo esc_attr( $tm[0] ); ?>" style="text-align:left; border:2px solid <?php echo $tmi === 0 ? 'var(--brand)' : 'var(--border)'; ?>; background:<?php echo $tmi === 0 ? 'var(--brand-soft)' : 'var(--elev)'; ?>; border-radius:14px; padding:12px 14px; cursor:pointer; font-family:inherit;">
                                        <div style="font-weight:700; font-size:13.5px;"><?php echo $tm[1]; ?> <?php echo esc_html( $tm[2] ); ?></div>
                                        <div style="font-size:11px; color:var(--muted); margin-top:2px;"><?php echo esc_html( $tm[3] ); ?></div>
                                    </button>
                                <?php endforeach; ?>
                            </div>
                            <div id="rvw-terr-countries" style="display:none; margin-top:12px; max-height:260px; overflow-y:auto; border:1px solid var(--border); border-radius:14px; padding:12px;">
                                <div id="rvw-terr-hint" style="font-size:11.5px; color:var(--muted); margin-bottom:8px;"></div>
                                <?php foreach ( $rvd_regions as $rkey => $reg ): ?>
                                    <div style="margin-bottom:10px;">
                                        <label style="display:flex; gap:8px; align-items:center; font-size:12.5px; font-weight:700; cursor:pointer; margin-bottom:6px;"><input type="checkbox" class="rvw-region-all" data-region="<?php echo esc_attr( $rkey ); ?>"> <?php echo esc_html( $reg['label'] ?? $rkey ); ?></label>
                                        <div style="display:grid; grid-template-columns:repeat(auto-fill,minmax(150px,1fr)); gap:4px; padding-left:22px;">
                                            <?php foreach ( (array) ( $reg['countries'] ?? [] ) as $cc => $cname ): ?>
                                                <label style="display:flex; gap:6px; align-items:center; font-size:11.5px; cursor:pointer;"><input type="checkbox" class="rvw-terr-cc" data-region="<?php echo esc_attr( $rkey ); ?>" value="<?php echo esc_attr( $cc ); ?>"> <?php echo esc_html( $cname ); ?></label>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <?php // ── Lojas ── ?>
                        <div class="card" style="margin-bottom:16px;">
                            <div style="display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap; margin-bottom:4px;">
                                <div style="font-weight:750; font-size:15px;">📚 Lojas e plataformas</div>
                                <div style="display:flex; gap:6px;">
                                    <button type="button" class="chip rvw-dsp-all" data-set="all" style="background:var(--brand-soft); color:var(--brand-ink);">Todas</button>
                                    <button type="button" class="chip rvw-dsp-all" data-set="none">Nenhuma</button>
                                    <button type="button" class="chip rvw-dsp-all" data-set="essential">Só essenciais</button>
                                </div>
                            </div>
                            <div id="rvw-dsp-count" style="font-size:11.5px; color:var(--muted); margin-bottom:10px;"></div>
                            <?php foreach ( [ 1, 2, 3 ] as $tier ): if ( empty( $rvd_dsp_by_tier[ $tier ] ) ) continue; ?>
                                <div style="font-size:11px; font-weight:800; letter-spacing:.5px; text-transform:uppercase; color:var(--brand-ink); margin:<?php echo $tier === 1 ? '4' : '14'; ?>px 0 8px;"><?php echo esc_html( $rvd_tier_labels[ $tier ] ); ?></div>
                                <div style="display:grid; grid-template-columns:repeat(auto-fill,minmax(170px,1fr)); gap:8px;">
                                    <?php foreach ( $rvd_dsp_by_tier[ $tier ] as $slug => $name ): ?>
                                        <label class="rvw-dsp" style="display:flex; align-items:center; gap:9px; border:1px solid var(--border); background:var(--elev); border-radius:12px; padding:9px 11px; cursor:pointer;">
                                            <input type="checkbox" class="rvw-dsp-cb" data-tier="<?php echo (int) $tier; ?>" value="<?php echo esc_attr( $slug ); ?>" checked style="width:17px; height:17px; accent-color:var(--brand);">
                                            <?php if ( $tier === 1 && function_exists( 'rmbz_dsp_logo_svg' ) ): ?><span style="width:24px; height:24px; border-radius:6px; overflow:hidden; display:flex; align-items:center; justify-content:center;"><?php echo rmbz_dsp_logo_svg( $slug, 24 ); ?></span><?php endif; ?>
                                            <span style="font-size:12px; font-weight:600;"><?php echo esc_html( $name ); ?></span>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <?php // ── Serviços exclusivos ── ?>
                        <?php if ( ! empty( $rvd_exclusives ) ): ?>
                        <div class="card" style="margin-bottom:16px;">
                            <div style="font-weight:750; font-size:15px;">⚠️ Serviços exclusivos <span style="color:var(--muted); font-weight:400; font-size:12.5px;">(opcional)</span></div>
                            <p style="font-size:12px; color:var(--muted); margin:2px 0 12px;">Exigem <b>direitos exclusivos</b>. A equipa 1MZ revê e aprova cada pedido. Só ativa se controlas 100% dos direitos da gravação.</p>
                            <?php foreach ( $rvd_exclusives as $ekey => $esvc ): $efield = $rvd_excl_field[ $ekey ] ?? ''; if ( ! $efield ) continue; ?>
                                <div class="rvw-excl-row" style="display:flex; gap:12px; align-items:flex-start; border:1px solid var(--border); border-radius:14px; padding:12px 14px; margin-bottom:8px;">
                                    <input type="checkbox" class="rvw-excl" data-field="<?php echo esc_attr( $efield ); ?>"
                                           data-name="<?php echo esc_attr( $esvc['name'] ?? $ekey ); ?>"
                                           data-notice="<?php echo esc_attr( $esvc['notice'] ?? '' ); ?>"
                                           style="width:18px; height:18px; margin-top:2px; accent-color:var(--brand);">
                                    <div style="flex:1;">
                                        <div style="font-weight:700; font-size:13px;"><?php echo esc_html( $esvc['name'] ?? $ekey ); ?> <span class="rvw-excl-state" style="font-size:11px; font-weight:600; color:var(--muted);">— não solicitado</span></div>
                                        <div style="font-size:12px; color:var(--muted); margin-top:2px;"><?php echo esc_html( $esvc['short'] ?? '' ); ?></div>
                                        <button type="button" class="chip rvw-excl-read" style="margin-top:8px;">📄 Ler aviso e aceitar</button>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>

                        <div style="display:flex; gap:10px;">
                            <button type="button" class="pill rvw-back" data-to="1" style="border:1px solid var(--border); background:none; color:var(--text2);">Voltar</button>
                            <button type="button" class="pill" id="rvw-next-2" style="flex:1; justify-content:center; background:var(--brand); color:var(--on-brand);">Guardar e continuar</button>
                        </div>
                    </div>

                    <!-- PASSO 3 — FAIXAS -->
                    <div class="rvw-panel" data-step="3" hidden>
                        <div class="card">
                            <div style="font-weight:750; font-size:15px; margin-bottom:4px;">Faixas</div>
                            <p style="font-size:12.5px; color:var(--muted); margin:0 0 12px;">Carrega o áudio de cada faixa. Preenche o título e o compositor — e abre <b>✏️ Detalhes</b> para créditos, letra, splits e mais.</p>
                            <div class="rvu-audio" id="rvw-audio-dz" style="margin-bottom:14px;">
                                <div class="rvu-audio-idle"><span style="font-size:38px; display:block;">🎵</span><div style="font-weight:700; margin-top:6px;">Clique para carregar uma faixa</div><div style="font-size:11.5px; color:var(--muted);">WAV (16-bit/44.1kHz+) · FLAC · MP3 (320 kbps) · mín. 30s · máx. 200 MB</div></div>
                                <input type="file" class="rvw-audio-input" accept=".mp3,.wav,.flac,audio/*" style="display:none;">
                                <div class="rvu-audio-prog" style="display:none;"><div style="font-size:12.5px; color:var(--text2); margin-bottom:8px;">A enviar… 🚀</div><div style="background:var(--elev); border-radius:20px; height:12px; overflow:hidden;"><div class="rvw-audio-bar" style="height:100%; width:0%; background:linear-gradient(90deg,var(--brand),#ffe270);"></div></div><div class="rvw-audio-pct" style="color:var(--brand-ink); font-size:13px; font-weight:700; margin-top:8px;">0%</div></div>
                            </div>
                            <div id="rvw-tracks" style="display:flex; flex-direction:column; gap:10px;"></div>
                            <div style="display:flex; gap:10px; margin-top:18px;">
                                <button type="button" class="pill rvw-back" data-to="2" style="border:1px solid var(--border); background:none; color:var(--text2);">Voltar</button>
                                <button type="button" class="pill" id="rvw-next-3" style="flex:1; justify-content:center; background:var(--brand); color:var(--on-brand);">Continuar</button>
                            </div>
                        </div>
                    </div>

                    <!-- PASSO 4 — CAPA + FINALIZAR -->
                    <div class="rvw-panel" data-step="4" hidden>
                        <div class="card">
                            <div style="font-weight:750; font-size:15px; margin-bottom:4px;">Capa do lançamento</div>
                            <p style="font-size:12.5px; color:var(--muted); margin:0 0 12px;">JPG ou PNG · quadrada (1:1) · mínimo 1400×1400 px · 100 KB a 10 MB.<br>💡 Recomendado: 3000×3000 px, sRGB, sem logos de outras plataformas.</p>
                            <div class="rvu-drop" id="rvw-cover-dz" style="min-height:160px;"><span style="font-size:30px;">🖼️</span><span style="font-size:12.5px; color:var(--text2);">Carregar capa</span><input type="file" id="rvw-cover-input" accept="image/jpeg,image/png" style="display:none;"></div>
                            <div id="rvw-cover-prev" class="rvu-prev" style="display:none;"></div>

                            <div id="rvw-license-box" data-release-id="" style="margin-top:16px;"></div>

                            <div style="display:flex; gap:10px; margin-top:18px;">
                                <button type="button" class="pill rvw-back" data-to="3" style="border:1px solid var(--border); background:none; color:var(--text2);">Voltar</button>
                                <button type="button" class="pill" id="rvw-finalize" disabled style="flex:1; justify-content:center; background:var(--success); color:#fff;">🚀 Finalizar e enviar para as lojas</button>
                            </div>
                        </div>
                    </div>
                    <?php // [1.5.424] Modal partilhado do date-picker inteligente. ?>
                    <?php if ( function_exists( 'rmbz_render_date_picker_modal' ) ) rmbz_render_date_picker_modal(); ?>

                    <?php // [1.5.427] Modal do AVISO dos serviços exclusivos (10s p/ aceitar). ?>
                    <div class="scrim" id="rvw-excl-scrim">
                        <div class="dialog" style="width:min(640px,96vw); max-height:90vh; display:flex; flex-direction:column;">
                            <div style="display:flex; align-items:center; gap:10px; margin-bottom:10px;">
                                <span style="font-size:20px;">⚠️</span>
                                <div style="flex:1; font-size:15px; font-weight:750;" id="rvw-excl-title">Serviço exclusivo</div>
                                <button type="button" class="rvw-excl-x" style="border:none; background:none; color:var(--muted); cursor:pointer; display:flex;"><span class="ms" style="font-size:22px;">close</span></button>
                            </div>
                            <div id="rvw-excl-notice" style="flex:1; overflow-y:auto; background:var(--elev); border:1px solid var(--border); border-radius:14px; padding:14px 16px; font-size:12.5px; color:var(--text2); line-height:1.6; white-space:pre-line; max-height:52vh;"></div>
                            <div style="display:flex; gap:10px; margin-top:14px; align-items:center;">
                                <button type="button" class="pill rvw-excl-x" style="border:1px solid var(--border); background:none; color:var(--text2);">Cancelar</button>
                                <button type="button" class="pill" id="rvw-excl-accept" disabled style="flex:1; justify-content:center; background:var(--success); color:#fff; opacity:.5;">Aguarda <span id="rvw-excl-cd">10</span>s…</button>
                            </div>
                        </div>
                    </div>
                    <?php // [1.5.434] Modal DETALHES DA FAIXA — mapeia o editor
                          // completo do módulo antigo (4 tabs) no tema nativo.
                          // Carrega via rmbz_track_editor_load e grava via
                          // rmbz_track_editor_save (payload COMPLETO). ?>
                    <div class="scrim" id="rvt-scrim">
                        <div class="dialog" style="width:min(760px,96vw); max-height:92vh; display:flex; flex-direction:column;">
                            <div style="display:flex; align-items:center; gap:10px; margin-bottom:12px;">
                                <div style="flex:1; font-size:16px; font-weight:750;">Detalhes da faixa</div>
                                <button type="button" class="rvt-x" style="border:none; background:none; color:var(--muted); cursor:pointer; display:flex;"><span class="ms" style="font-size:22px;">close</span></button>
                            </div>
                            <div style="display:flex; gap:6px; flex-wrap:wrap; margin-bottom:14px;">
                                <?php foreach ( [ 'basic' => '1 · Básico', 'credits' => '2 · Créditos', 'splits' => '3 · Splits', 'advanced' => '4 · Avançado' ] as $tk => $tl ): ?>
                                <button type="button" class="rvt-tab<?php echo $tk === 'basic' ? ' on' : ''; ?>" data-t="<?php echo esc_attr( $tk ); ?>" style="border:0; background:<?php echo $tk === 'basic' ? 'var(--brand-soft)' : 'transparent'; ?>; color:<?php echo $tk === 'basic' ? 'var(--brand-ink)' : 'var(--text2)'; ?>; font-family:inherit; font-size:12.5px; font-weight:700; padding:8px 14px; border-radius:100px; cursor:pointer;"><?php echo esc_html( $tl ); ?></button>
                                <?php endforeach; ?>
                            </div>
                            <div style="flex:1; overflow-y:auto; min-height:0;">
                                <!-- TAB BÁSICO -->
                                <div class="rvt-pane" data-t="basic">
                                    <label class="rvu-lbl">Título da faixa *</label>
                                    <input class="inp" id="rvt-title" style="font-size:13px;">
                                    <div class="grid2" style="margin-top:12px;">
                                        <div>
                                            <label class="rvu-lbl">Idioma</label>
                                            <select class="inp" id="rvt-lang" style="font-size:13px;">
                                                <?php foreach ( $rvt_langs as $lv => $ll ): ?><option value="<?php echo esc_attr( $lv ); ?>"><?php echo esc_html( $ll ); ?></option><?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="rvu-lbl">Duração</label>
                                            <div style="border:1px solid var(--border); border-radius:12px; padding:10px 14px; background:var(--elev);"><span class="mono" id="rvt-dur" style="font-size:16px; font-weight:700; color:var(--brand-ink);">--:--</span><div style="font-size:10.5px; color:var(--muted); margin-top:2px;">Capturada automaticamente do ficheiro</div></div>
                                        </div>
                                    </div>
                                    <div class="grid2" style="margin-top:12px;">
                                        <div>
                                            <label class="rvu-lbl">ISRC (opcional)</label>
                                            <input class="inp" id="rvt-isrc" maxlength="12" placeholder="Ex: MZ0AB2400001" style="font-size:13px;">
                                            <div style="font-size:11px; color:var(--muted); margin-top:4px;">Deixa vazio para a 1MZ gerar.</div>
                                        </div>
                                        <div>
                                            <label class="rvu-lbl">Estado</label>
                                            <label style="display:flex; gap:8px; align-items:center; font-size:12.5px; cursor:pointer; margin-top:6px;"><input type="checkbox" id="rvt-exp"> Letra explícita</label>
                                            <label style="display:flex; gap:8px; align-items:center; font-size:12.5px; cursor:pointer; margin-top:8px;"><input type="checkbox" id="rvt-inst"> É instrumental (sem letra)</label>
                                        </div>
                                    </div>
                                </div>
                                <!-- TAB CRÉDITOS -->
                                <div class="rvt-pane" data-t="credits" hidden>
                                    <label class="rvu-lbl">Compositores (songwriters) *</label>
                                    <div style="font-size:11.5px; color:var(--muted); margin-bottom:8px;">Quem escreveu a música e a letra. Obrigatório pelas editoras (mesmo que seja só o artista principal).</div>
                                    <div id="rvt-sw-list" style="display:flex; flex-direction:column; gap:8px;"></div>
                                    <button type="button" class="chip" id="rvt-sw-add" style="margin-top:8px;">＋ Adicionar compositor</button>
                                    <label class="rvu-lbl" style="margin-top:16px;">Colaboradores / artistas</label>
                                    <div style="font-size:11.5px; color:var(--muted); margin-bottom:8px;">Adiciona quem participou: featuring, produtores, mistura, etc. O artista principal é adicionado automaticamente.</div>
                                    <div id="rvt-collab-list" style="display:flex; flex-direction:column; gap:8px;"></div>
                                    <button type="button" class="chip" id="rvt-collab-add" style="margin-top:8px;">＋ Adicionar colaborador</button>
                                    <label style="display:flex; gap:8px; align-items:center; font-size:12.5px; cursor:pointer; margin-top:16px;"><input type="checkbox" id="rvt-haslyrics"> Esta faixa tem letra</label>
                                    <div id="rvt-lyrics-wrap" hidden style="margin-top:8px;">
                                        <textarea class="inp" id="rvt-lyrics" rows="5" placeholder="Cola aqui a letra da música…" style="font-size:13px; resize:vertical;"></textarea>
                                        <div style="font-size:11px; color:var(--muted); margin-top:4px;">Usada em Apple Music, Musixmatch e outras plataformas de letras.</div>
                                    </div>
                                    <label style="display:flex; gap:8px; align-items:center; font-size:12.5px; cursor:pointer; margin-top:14px;"><input type="checkbox" id="rvt-prev"> Já foi lançada antes (noutra distribuidora)</label>
                                    <div id="rvt-prev-wrap" hidden style="margin-top:8px;">
                                        <input class="inp" id="rvt-origisrc" maxlength="12" placeholder="ISRC original — Ex: USUM71900001" style="font-size:13px;">
                                    </div>
                                    <label style="display:flex; gap:8px; align-items:center; font-size:12.5px; cursor:pointer; margin-top:14px;"><input type="checkbox" id="rvt-iscover"> É uma versão cover</label>
                                    <div id="rvt-cover-wrap" hidden style="margin-top:8px;" class="grid2">
                                        <input class="inp" id="rvt-covertitle" placeholder="Título original — Ex: Umbrella" style="font-size:13px;">
                                        <input class="inp" id="rvt-covercomposer" placeholder="Compositor original — Ex: The-Dream" style="font-size:13px;">
                                    </div>
                                </div>
                                <!-- TAB SPLITS -->
                                <div class="rvt-pane" data-t="splits" hidden>
                                    <label class="rvu-lbl">Divisão de royalties (splits)</label>
                                    <div style="font-size:11.5px; color:var(--muted); margin-bottom:8px;">Sem splits, 100% fica para ti. Com splits, o total tem de somar <b>100%</b>.</div>
                                    <div id="rvt-splits-list" style="display:flex; flex-direction:column; gap:8px;"></div>
                                    <div style="display:flex; align-items:center; gap:10px; margin-top:10px;">
                                        <button type="button" class="chip" id="rvt-split-add">＋ Adicionar split</button>
                                        <div id="rvt-splits-total" style="font-size:12px; font-weight:700; color:var(--muted);"></div>
                                    </div>
                                    <div style="font-size:11.5px; color:var(--muted); line-height:1.55; margin-top:12px; background:var(--elev); border-radius:12px; padding:10px 14px;">💡 Se um colaborador tem conta 1MZ (pelo telemóvel), receberá um convite para aceitar o split. Caso contrário, a percentagem fica registada no lançamento e pode ser paga manualmente.</div>
                                </div>
                                <!-- TAB AVANÇADO -->
                                <div class="rvt-pane" data-t="advanced" hidden>
                                    <label class="rvu-lbl">Começar preview em (segundos)</label>
                                    <input class="inp" type="number" id="rvt-preview" min="0" step="1" placeholder="0 = início" style="font-size:13px; max-width:220px;">
                                    <div style="font-size:11px; color:var(--muted); margin-top:4px;">O trecho que toca nas prévias de TikTok/Instagram e nas lojas.</div>
                                    <label class="rvu-lbl" style="margin-top:16px;">Moods e tags (até 5)</label>
                                    <div id="rvt-moods" style="display:flex; gap:6px; flex-wrap:wrap;">
                                        <?php foreach ( $rvt_moods as $mk => $ml ): ?>
                                        <button type="button" class="chip rvt-mood" data-mood="<?php echo esc_attr( $mk ); ?>"><?php echo esc_html( $ml ); ?></button>
                                        <?php endforeach; ?>
                                    </div>
                                    <div style="border:1px dashed var(--border2); border-radius:12px; padding:10px 14px; margin-top:16px; font-size:12px; color:var(--muted);">🎧 Dolby Atmos / Áudio imersivo — em breve.</div>
                                </div>
                            </div>
                            <div style="display:flex; gap:10px; margin-top:14px;">
                                <button type="button" class="pill rvt-x" style="border:1px solid var(--border); background:none; color:var(--text2);">Cancelar</button>
                                <button type="button" class="pill" id="rvt-save" style="flex:1; justify-content:center; background:var(--brand); color:var(--on-brand);">Guardar detalhes</button>
                            </div>
                        </div>
                    </div>
                </div><!-- /create -->
                <?php endif; ?>
            </section>

            <!-- ═══ ENVIOS ═══ -->
            <section class="sect<?php echo $vip_sect === 'envios' ? ' on' : ''; ?>" data-sect="envios" data-screen-label="Envios">
                <?php if ( ! $envios_access ): ?>
                    <?php rmbz_vip_render_service_gate( 'submissions', $envios_gate_reason ); ?>
                <?php else: ?>
                <?php // [1.5.416] FORMULÁRIO DE ENVIO — refeito NATIVO no tema VIP
                      // (M3), mantendo TODOS os name/action/nonces do antigo:
                      // rmbz_handle_frontend_upload + rmbz_async_audio_upload +
                      // rmbz_feat_check_account. Nada de include feio. ?>
                <?php
                $rvu_types = [
                    [ 'audio_site',   $perm_site,   'library_music', 'Enviar para o Site', 'Publicar música',       $motivo_site ],
                    [ 'video_social', $perm_social, 'share',         'Redes Sociais',      'Divulgar vídeo',        $motivo_social ],
                    [ 'win_video',    $perm_video,  'movie',         'Ganhar Videoclipe',   'Candidatar à produção', $motivo_video ],
                ];
                $rvu_any = ( $perm_site || $perm_social || $perm_video );
                ?>
                <div class="card rvu-page-head" style="margin-bottom:16px;">
                    <div class="rvu-page-head-icon"><span class="ms">upload</span></div>
                    <div style="flex:1; min-width:220px;">
                        <div style="font-family:'Bricolage Grotesque',sans-serif; font-size:19px; font-weight:800;">Os teus envios</div>
                        <div style="font-size:12.5px; color:var(--muted); margin-top:3px;">Acompanha publicações no site e campanhas nas redes sem misturar com o formulário.</div>
                    </div>
                    <div style="display:flex; align-items:center; gap:10px; flex-wrap:wrap;">
                        <span class="status" style="background:var(--elev); color:var(--text2);"><?php echo (int) $submission_counts['all']; ?> no total</span>
                        <button type="button" class="pill" <?php echo ! empty( $pendente_tipo ) ? 'disabled' : 'data-dialog="rmbz-vip-new-submission"'; ?> style="background:var(--brand); color:var(--on-brand); opacity:<?php echo ! empty( $pendente_tipo ) ? '.45' : '1'; ?>; cursor:<?php echo ! empty( $pendente_tipo ) ? 'not-allowed' : 'pointer'; ?>;"><span class="ms" style="font-size:19px;">add</span> Novo envio</button>
                    </div>
                </div>
                <?php if ( ! empty( $pendente_tipo ) ): ?>
                    <div class="card" style="border-color:var(--rev); margin-bottom:16px; display:flex; gap:14px; align-items:center; flex-wrap:wrap;">
                        <span style="font-size:24px;">⏳</span>
                        <div style="flex:1; min-width:220px;">
                            <div style="font-weight:750; font-size:14px; color:var(--rev);">Aguarda a validação</div>
                            <div style="font-size:12.5px; color:var(--text2); margin-top:3px;">Já tens um envio em análise (<b><?php echo esc_html( $pendente_tipo ); ?></b>). Para evitar duplicações, espera que a equipa aprove ou rejeite antes de enviar outra obra.</div>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="scrim" id="rmbz-vip-new-submission" data-screen-label="Novo envio">
                <div id="rvu-wrap" class="dialog" style="width:min(860px,96vw); max-height:92vh; padding:24px 28px;">
                    <div style="display:flex; align-items:center; gap:12px; margin-bottom:16px;">
                        <span class="ms" style="width:44px; height:44px; border-radius:14px; background:var(--brand-soft); color:var(--brand-ink); align-items:center; justify-content:center; font-size:23px;">upload</span>
                        <div style="flex:1;"><h2 style="font-family:'Bricolage Grotesque',sans-serif; font-size:20px; margin:0;">Criar novo envio</h2><div style="font-size:11.5px; color:var(--muted); margin-top:2px;">Escolhe primeiro o serviço que pretendes usar.</div></div>
                        <button type="button" class="rmbz-vip-dclose" aria-label="Fechar" style="border:0; background:none; color:var(--muted); cursor:pointer;"><span class="ms">close</span></button>
                    </div>
                    <div style="font-size:11px; font-weight:750; letter-spacing:.08em; color:var(--muted); margin-bottom:10px;">ESCOLHE O TIPO DE ENVIO</div>
                    <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:12px;">
                        <?php foreach ( $rvu_types as $rt ):
                            [ $rk, $ralw, $ric, $rtitle, $rsub, $rreason ] = $rt; ?>
                            <?php if ( $ralw ): ?>
                                <button type="button" class="rvu-type" data-type="<?php echo esc_attr( $rk ); ?>"
                                        style="text-align:center; border:1.5px solid var(--border); background:var(--elev); border-radius:20px; padding:20px 14px; cursor:pointer; font-family:inherit; transition:transform .12s, border-color .12s, background .12s;">
                                    <span class="ms" style="font-size:32px; color:var(--brand-ink);"><?php echo esc_html( $ric ); ?></span>
                                    <div style="font-weight:750; font-size:14px; margin-top:8px; color:var(--text);"><?php echo esc_html( $rtitle ); ?></div>
                                    <div style="font-size:11.5px; color:var(--muted); margin-top:2px;"><?php echo esc_html( $rsub ); ?></div>
                                </button>
                            <?php else: ?>
                                <div style="text-align:center; border:1.5px solid var(--border); background:var(--surface); border-radius:20px; padding:20px 14px; opacity:.55;" title="Acesso restrito">
                                    <span class="ms" style="font-size:32px; color:var(--muted);">lock</span>
                                    <div style="font-weight:750; font-size:14px; margin-top:8px; color:var(--muted);"><?php echo esc_html( $rtitle ); ?></div>
                                    <div style="font-size:11px; color:var(--danger); margin-top:2px;"><?php echo esc_html( $rreason ); ?></div>
                                </div>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>

                    <?php if ( ! $rvu_any ): ?>
                        <div style="margin-top:16px; border-radius:14px; padding:12px 16px; background:var(--danger-soft); color:var(--danger); font-size:12.5px; font-weight:650;">O teu plano VIP atual não permite enviar obras por esta página. Consulta o teu perfil para ver as permissões.</div>
                    <?php else: ?>
                        <form id="rvu-form" action="<?php echo esc_url( $post_url ); ?>" method="post" enctype="multipart/form-data" style="margin-top:6px;">
                            <input type="hidden" name="action" value="rmbz_handle_frontend_upload">
                            <input type="hidden" name="_wpnonce" value="<?php echo esc_attr( $up_nonce_form ); ?>">
                            <input type="hidden" id="rvu-audio-nonce" value="<?php echo esc_attr( $up_nonce_audio ); ?>">
                            <input type="hidden" name="submission_type" id="rvu-type-in" value="">

                            <?php /* ═══ SITE ═══ */ ?>
                            <div class="rvu-sec" data-sec="audio_site" style="display:none;">
                                <div style="font-size:12px; font-weight:750; color:var(--brand-ink); letter-spacing:.05em; margin:18px 0 12px;">1 · INFORMAÇÕES BÁSICAS (SITE)</div>
                                <label style="display:flex; gap:10px; align-items:center; background:var(--brand-soft); border:1px solid var(--brand); border-radius:14px; padding:12px 14px; cursor:pointer; font-size:13.5px; font-weight:700; color:var(--brand-ink);">
                                    <input type="checkbox" name="is_album" id="rvu-album" value="yes" style="width:20px; height:20px;"> 💿 Isto é um Álbum ou EP? (múltiplas faixas)
                                </label>
                                <div style="margin-top:14px;"><label class="rvu-lbl">Artista Principal *</label><input class="inp rvu-f-site" type="text" name="artist_name" placeholder="Nome artístico"></div>
                                <div style="margin-top:12px;"><label class="rvu-lbl" id="rvu-title-lbl">Título da Música *</label><input class="inp rvu-f-site" type="text" name="music_title" placeholder="Nome da obra"></div>
                                <div style="margin-top:12px;"><label class="rvu-lbl">Género Musical *</label>
                                    <select class="inp rvu-f-site" name="music_genre"><option value="">Selecione…</option><?php foreach ( [ 'Hip-Hop','Trap','R&B','Pandza','Kizomba','Afro House','Amapiano','Marrabenta','Gospel','Outro' ] as $g ) echo '<option value="' . esc_attr( $g ) . '">' . esc_html( $g ) . '</option>'; ?></select>
                                </div>
                                <div style="margin-top:12px;"><label class="rvu-lbl">Tem Participação (Feat)?</label>
                                    <div class="rvu-yn"><label><input type="radio" name="has_feat" value="no" checked data-box="rvu-feat-site" data-show="0">Não</label><label><input type="radio" name="has_feat" value="yes" data-box="rvu-feat-site" data-show="1">Sim</label></div>
                                </div>
                                <div id="rvu-feat-site" style="display:none; margin-top:10px;"><label class="rvu-lbl">Nome(s) da(s) participação(ões)</label><input class="inp" type="text" name="feat_name" placeholder="Ex: Artista A, Artista B"></div>
                                <div style="margin-top:12px;"><label class="rvu-lbl">Data ideal de publicação *</label><input class="inp rvu-f-site" type="date" name="release_date" style="color-scheme:dark;"></div>

                                <div style="font-size:12px; font-weight:750; color:var(--brand-ink); letter-spacing:.05em; margin:20px 0 12px;">2 · FICHEIROS & LINKS</div>
                                <label class="rvu-lbl">Capa do Áudio (imagem quadrada) *</label>
                                <div class="rvu-drop" data-target="rvu-cover"><span style="font-size:26px;">🖼️</span><span style="font-size:12.5px; color:var(--text2);">Carregar capa (JPG/PNG)</span><input type="file" name="cover_image" id="rvu-cover" accept="image/*" style="display:none;"></div>
                                <div class="rvu-prev" id="rvu-cover-prev" style="display:none;"></div>

                                <div id="rvu-single-audio" style="margin-top:14px;">
                                    <label class="rvu-lbl" style="color:var(--brand-ink);">Upload do Áudio (MP3 ou WAV) *</label>
                                    <?php echo rmbz_vip_audio_dropzone( 'site' ); ?>
                                </div>
                                <div id="rvu-album-audio" style="display:none; margin-top:14px; background:var(--elev); border:1px solid var(--border); border-radius:16px; padding:16px;">
                                    <label class="rvu-lbl" style="color:var(--brand-ink);">Faixas do Álbum / EP *</label>
                                    <p style="font-size:12px; color:var(--muted); margin:4px 0 12px;">Título de cada música + o ficheiro MP3 correspondente.</p>
                                    <div id="rvu-tracks">
                                        <div class="rvu-track" style="display:flex; gap:8px; margin-bottom:8px; align-items:center;"><span style="font-weight:700; color:var(--muted); width:18px;">1.</span><input class="inp" type="text" name="album_track_titles[]" placeholder="Título da faixa" style="flex:1;"><input type="file" name="album_track_files[]" accept=".mp3,.wav" style="max-width:160px; font-size:12px; color:var(--text2);"></div>
                                    </div>
                                    <button type="button" class="chip" id="rvu-add-track" style="margin-top:6px;">+ Adicionar faixa</button>
                                </div>

                                <div style="margin-top:14px;"><label class="rvu-lbl">Tem Videoclipe?</label>
                                    <div class="rvu-yn"><label><input type="radio" name="has_video" value="no" checked data-box="rvu-video-site" data-show="0">Não</label><label><input type="radio" name="has_video" value="yes" data-box="rvu-video-site" data-show="1">Sim</label></div>
                                </div>
                                <div id="rvu-video-site" style="display:none; margin-top:10px;"><label class="rvu-lbl">Link do YouTube</label><input class="inp" type="url" name="youtube_link" placeholder="https://youtube.com/watch?v=…"></div>
                                <div style="margin-top:12px;"><label class="rvu-lbl">Disponível nas Plataformas Digitais?</label>
                                    <div class="rvu-yn"><label><input type="radio" name="on_platforms" value="no" checked data-box="rvu-plat" data-show="0">Não</label><label><input type="radio" name="on_platforms" value="yes" data-box="rvu-plat" data-show="1">Sim</label></div>
                                </div>
                                <div id="rvu-plat" style="display:none; margin-top:10px;"><label class="rvu-lbl">Link do Spotify</label><input class="inp" type="url" name="spotify_link" placeholder="Link Spotify"><label class="rvu-lbl" style="margin-top:10px;">Link do Apple Music</label><input class="inp" type="url" name="apple_music_link" placeholder="Link Apple Music"></div>

                                <div style="font-size:12px; font-weight:750; color:var(--brand-ink); letter-spacing:.05em; margin:20px 0 12px;">3 · DETALHES FINAIS</div>
                                <div><label class="rvu-lbl">Redes Sociais Oficiais *</label><input class="inp rvu-f-site" type="url" name="social_link" placeholder="Link do Instagram ou TikTok"></div>
                                <div style="margin-top:12px;"><label class="rvu-lbl">Descrição da Música *</label><textarea class="inp rvu-f-site" name="submission_concept" rows="4" placeholder="Conta um pouco sobre a música, mensagem, produção…"></textarea></div>
                                <label class="rvu-chk"><input type="checkbox" name="declaration_check_site" class="rvu-req-site"><span><b>Declaração de Autoria:</b> declaro que possuo os direitos desta obra.</span></label>
                                <label class="rvu-chk"><input type="checkbox" name="terms_check_site" class="rvu-req-site"><span><b>Termos e Condições:</b> aceito os termos de publicação da 1MusicMoz.</span></label>
                                <button type="submit" class="pill" style="margin-top:18px; width:100%; justify-content:center; background:var(--brand); color:var(--on-brand); font-size:15px; padding:15px;">PUBLICAR 🎵</button>
                            </div>

                            <?php /* ═══ REDES SOCIAIS ═══ */ ?>
                            <div class="rvu-sec" data-sec="video_social" style="display:none;">
                                <div style="font-size:12px; font-weight:750; color:var(--brand-ink); letter-spacing:.05em; margin:18px 0 12px;">1 · DETALHES DA OBRA (VÍDEO)</div>
                                <div><label class="rvu-lbl">Artista Principal *</label><input class="inp rvu-f-social" type="text" name="video_artist_name" placeholder="Nome artístico"></div>
                                <div style="margin-top:12px;"><label class="rvu-lbl">Título do Vídeo / Música *</label><input class="inp rvu-f-social" type="text" name="video_title" placeholder="Nome da obra"></div>
                                <div style="margin-top:12px;"><label class="rvu-lbl">Canais de Divulgação *</label>
                                    <div style="display:flex; gap:10px; flex-wrap:wrap;">
                                        <label class="chip" style="cursor:pointer;"><input type="checkbox" name="dist_channels[]" value="Facebook" checked style="margin-right:6px;">🔵 Facebook</label>
                                        <label class="chip" style="cursor:pointer;"><input type="checkbox" name="dist_channels[]" value="YouTube" checked style="margin-right:6px;">🔴 YouTube</label>
                                    </div>
                                </div>
                                <div style="margin-top:12px;"><label class="rvu-lbl">Link da Obra (download do vídeo HD/4K) *</label><input class="inp rvu-f-social" type="url" name="video_link_url" placeholder="Drive, Dropbox, WeTransfer…"><p style="font-size:11px; color:var(--muted); margin:4px 0 0;">Cola o link para baixarmos o original com qualidade máxima.</p></div>
                                <div style="margin-top:12px;"><label class="rvu-lbl">Capa do Vídeo (thumbnail) *</label>
                                    <div class="rvu-drop" data-target="rvu-vthumb"><span style="font-size:26px;">🖼️</span><span style="font-size:12.5px; color:var(--text2);">Carregar thumbnail (JPG/PNG)</span><input type="file" name="video_thumbnail" id="rvu-vthumb" accept="image/*" style="display:none;"></div>
                                    <div class="rvu-prev" id="rvu-vthumb-prev" style="display:none;"></div>
                                </div>
                                <div style="margin-top:12px;"><label class="rvu-lbl">Género Musical *</label>
                                    <select class="inp rvu-f-social" name="video_genre"><option value="">Selecione…</option><?php foreach ( [ 'Hip-Hop','Trap','Pandza','Kizomba','Afro House','Amapiano','Marrabenta','Gospel','Outro' ] as $g ) echo '<option value="' . esc_attr( $g ) . '">' . esc_html( $g ) . '</option>'; ?></select>
                                </div>
                                <div style="margin-top:12px;"><label class="rvu-lbl">Tem Participação (Feat)?</label>
                                    <div class="rvu-yn"><label><input type="radio" name="video_has_feat" value="no" checked data-box="rvu-feat-social" data-show="0">Não</label><label><input type="radio" name="video_has_feat" value="yes" data-box="rvu-feat-social" data-show="1">Sim</label></div>
                                </div>
                                <div id="rvu-feat-social" style="display:none; margin-top:10px;"><label class="rvu-lbl">Nome(s) da(s) participação(ões)</label><input class="inp" type="text" name="video_feat_name" placeholder="Ex: Artista A, Artista B"></div>
                                <div style="margin-top:12px;"><label class="rvu-lbl">Data ideal de publicação *</label><input class="inp rvu-f-social" type="date" name="video_release_date" style="color-scheme:dark;"></div>
                                <div style="font-size:12px; font-weight:750; color:var(--brand-ink); letter-spacing:.05em; margin:20px 0 12px;">2 · CONTEÚDO DO POST</div>
                                <div><label class="rvu-lbl">Legenda do Post / Descrição *</label><textarea class="inp rvu-f-social" name="social_caption" rows="5" placeholder="Escreve o texto que será publicado nas redes…"></textarea></div>
                                <label class="rvu-chk"><input type="checkbox" name="declaration_check_social" class="rvu-req-social"><span><b>Declaração de Autoria:</b> confirmo que sou o detentor dos direitos deste vídeo.</span></label>
                                <label class="rvu-chk"><input type="checkbox" name="terms_check_social" class="rvu-req-social"><span><b>Termos e Condições:</b> aceito os termos de divulgação.</span></label>
                                <button type="submit" class="pill" style="margin-top:18px; width:100%; justify-content:center; background:var(--brand); color:var(--on-brand); font-size:15px; padding:15px;">ENVIAR VÍDEO 🎬</button>
                            </div>

                            <?php /* ═══ GANHAR VÍDEO ═══ */ ?>
                            <div class="rvu-sec" data-sec="win_video" style="display:none;">
                                <div style="font-size:12px; font-weight:750; color:var(--brand-ink); letter-spacing:.05em; margin:18px 0 12px;">1 · DADOS DA CANDIDATURA</div>
                                <div style="display:flex; gap:12px; align-items:flex-start; background:var(--rev-soft); border:1px solid var(--rev); border-radius:14px; padding:12px 14px; margin-bottom:14px;">
                                    <span style="font-size:20px;">⚠️</span>
                                    <div style="font-size:12.5px; color:var(--text2);"><b style="color:var(--rev); display:block;">Regra Principal</b>A música enviada <b>não pode</b> ter videoclipe oficial existente.</div>
                                </div>
                                <div><label class="rvu-lbl">Nome do Artista *</label><input class="inp rvu-f-proj" type="text" name="project_artist" placeholder="Seu nome artístico"></div>
                                <div style="margin-top:12px;"><label class="rvu-lbl">Título da Música *</label><input class="inp rvu-f-proj" type="text" name="project_title" placeholder="Nome da música"></div>
                                <div style="margin-top:12px;"><label class="rvu-lbl">Nome do Produtor *</label><input class="inp rvu-f-proj" type="text" name="music_producer" placeholder="Quem produziu o beat/captação"></div>

                                <label style="display:flex; gap:8px; align-items:center; margin-top:14px; cursor:pointer; font-size:13.5px; font-weight:700;">
                                    <input type="checkbox" name="feat_enabled" value="1" id="rvu-feat-enabled"> 🎤 A música tem participação (feat)?
                                </label>
                                <div id="rvu-feat-proj" style="display:none; margin-top:10px; background:var(--brand-soft); border:1px solid var(--brand); border-radius:14px; padding:14px;">
                                    <label class="rvu-lbl">Nome do participante</label>
                                    <input class="inp" type="text" name="feat_name" placeholder="Nome artístico do feat">
                                    <label style="display:flex; gap:8px; align-items:center; margin-top:10px; cursor:pointer; font-size:13px;">
                                        <input type="checkbox" id="rvu-feat-has" name="feat_has_account" value="1"> O participante tem conta 1MZ For Artists?
                                    </label>
                                    <div id="rvu-feat-tel-wrap" style="display:none; margin-top:8px;">
                                        <input class="inp" type="tel" id="rvu-feat-tel" name="feat_tel" placeholder="Número da conta dele" autocomplete="off">
                                        <div id="rvu-feat-status" style="font-size:12px; font-weight:700; margin-top:6px; display:none;"></div>
                                        <p style="font-size:11px; color:var(--muted); margin:8px 0 0;">⚠️ O participante recebe um convite e tem de <b>aceitar</b>. Se recusar, o projeto é cancelado.</p>
                                    </div>
                                    <p style="font-size:11px; color:var(--muted); margin:8px 0 0;">Sem conta 1MZ fica só para registo — não altera pagamentos, contrato nem produção.</p>
                                </div>

                                <div style="margin-top:12px;"><label class="rvu-lbl">Link Opcional (SoundCloud/Drive)</label><input class="inp" type="url" name="project_link_opt" placeholder="https://…"></div>
                                <div style="margin-top:14px;"><label class="rvu-lbl" style="color:var(--brand-ink);">MP3 da Música (Demo) *</label><?php echo rmbz_vip_audio_dropzone( 'project' ); ?></div>

                                <div style="font-size:12px; font-weight:750; color:var(--brand-ink); letter-spacing:.05em; margin:20px 0 12px;">2 · ESCOLHE O CENÁRIO</div>
                                <div style="display:grid; grid-template-columns:repeat(3,1fr); gap:10px;">
                                    <?php foreach ( [ [ 'basic','🎬','Básico','Produção Simples' ], [ 'professional','🎥','Profissional','Produção Média' ], [ 'cinema','⭐️','Cinema','Alto Nível' ] ] as $ci => $sc ): ?>
                                        <label class="rvu-scen" data-scen="<?php echo esc_attr( $sc[0] ); ?>" style="text-align:center; border:2px solid var(--border); background:var(--elev); border-radius:16px; padding:14px 8px; cursor:pointer;">
                                            <input type="radio" name="video_scenario" value="<?php echo esc_attr( $sc[0] ); ?>" <?php checked( $ci, 0 ); ?> style="display:none;">
                                            <span style="font-size:26px;"><?php echo $sc[1]; ?></span>
                                            <div style="font-weight:700; font-size:13.5px; margin-top:4px;"><?php echo esc_html( $sc[2] ); ?></div>
                                            <div style="font-size:11px; color:var(--muted);"><?php echo esc_html( $sc[3] ); ?></div>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                                <div id="rvu-scen-info" style="margin-top:12px; background:var(--elev); border:1px solid var(--border); border-radius:14px; padding:14px;"></div>

                                <div style="font-size:12px; font-weight:750; color:var(--brand-ink); letter-spacing:.05em; margin:20px 0 12px;">3 · O TEU CONCEITO</div>
                                <div><label class="rvu-lbl">Ideia do Videoclipe *</label><textarea class="inp rvu-f-proj" name="project_pitch" rows="5" placeholder="Descreve o conceito visual, estilo, ambiente…"></textarea></div>
                                <div style="font-size:12px; font-weight:750; color:var(--brand-ink); letter-spacing:.05em; margin:20px 0 12px;">4 · CONFIRMAÇÕES OBRIGATÓRIAS</div>
                                <label class="rvu-chk"><input type="checkbox" name="decl_auth_project" class="rvu-req-proj"><span>Sou o autor legítimo desta música.</span></label>
                                <label class="rvu-chk"><input type="checkbox" name="decl_novideo_project" class="rvu-req-proj"><span>Confirmo que esta música <b>NÃO</b> possui videoclipe oficial.</span></label>
                                <label class="rvu-chk"><input type="checkbox" name="decl_terms_project" class="rvu-req-proj"><span>Aceito que a candidatura será avaliada pela equipa 1MZ.</span></label>
                                <button type="submit" class="pill" style="margin-top:18px; width:100%; justify-content:center; background:var(--brand); color:var(--on-brand); font-size:15px; padding:15px;">ENVIAR CANDIDATURA 🏆</button>
                            </div>
                        </form>
                    <?php endif; ?>
                </div>
                </div>

                <div class="rvu-list-toolbar">
                    <div><div style="font-size:15px; font-weight:800;">Submissões</div><div style="font-size:11.5px; color:var(--muted); margin-top:2px;">Organizadas por destino e estado.</div></div>
                    <nav class="rvu-kind-filter" aria-label="Filtrar envios">
                        <?php
                        $submission_filter_options = [ 'all' => [ 'apps', 'Todos' ] ];
                        if ( $perm_site ) $submission_filter_options['site'] = [ 'language', 'Site' ];
                        if ( $perm_social ) $submission_filter_options['social'] = [ 'share', 'Redes sociais' ];
                        foreach ( $submission_filter_options as $kind_key => $kind_meta ):
                            $kind_active = $submission_kind === $kind_key;
                            $kind_url = add_query_arg( [ 'sect' => 'envios', 'sub_kind' => $kind_key ], home_url( '/minha-conta/' ) );
                        ?>
                            <a href="<?php echo esc_url( $kind_url ); ?>" class="rvu-kind<?php echo $kind_active ? ' on' : ''; ?>" aria-current="<?php echo $kind_active ? 'page' : 'false'; ?>"><span class="ms"><?php echo esc_html( $kind_meta[0] ); ?></span><?php echo esc_html( $kind_meta[1] ); ?><span class="mono"><?php echo (int) $submission_counts[ $kind_key ]; ?></span></a>
                        <?php endforeach; ?>
                    </nav>
                </div>
                <?php if ( empty( $submissions ) ): ?>
                    <div class="card" style="text-align:center; padding:36px 28px;">
                        <span class="ms" style="width:56px; height:56px; border-radius:18px; background:var(--elev); color:var(--muted); align-items:center; justify-content:center; font-size:28px;">inbox</span>
                        <p style="font-weight:750; margin:12px 0 0;"><?php echo $submission_kind === 'all' ? 'Ainda não tens envios' : 'Sem envios nesta categoria'; ?></p>
                        <p style="font-size:12.5px; color:var(--muted); margin:4px auto 0; max-width:460px;">As submissões aparecem aqui com o estado, destino, data e orientações da equipa.</p>
                    </div>
                <?php else: ?>
                    <div style="display:flex; flex-direction:column; gap:12px;">
                    <?php
                    $sub_status_map = [
                        'pendente'      => [ 'Pendente', 'rev' ], 'aprovado' => [ 'Aprovado', 'success' ],
                        'em_publicacao' => [ 'Em publicação', 'info' ], 'finalizado' => [ 'Publicado', 'success' ],
                        'correcao'      => [ 'Precisa de correção', 'danger' ], 'rejeitado' => [ 'Rejeitado', 'danger' ],
                    ];
                    foreach ( $submissions as $sub ):
                        $sx = ! empty( $sub->extra_data ) ? json_decode( (string) $sub->extra_data, true ) : [];
                        if ( ! is_array( $sx ) ) $sx = [];
                        $s_st = (string) ( $sub->review_status ?? 'pendente' );
                        [ $s_lbl, $s_tone ] = $sub_status_map[ $s_st ] ?? [ ucfirst( $s_st ), 'muted' ];
                        $s_type = (string) ( $sub->scenario_type ?? '' );
                        $s_is_social = ( $s_type === 'Redes Sociais' );
                        $s_cover = $s_is_social
                            ? (string) ( $sx['thumbnail_url'] ?? ( $sx['cover_image'] ?? '' ) )
                            : (string) ( $sx['cover_image'] ?? ( $sx['thumbnail_url'] ?? '' ) );
                        // Publicação agendada (esconde links até chegar a hora)
                        $sched_ts = ! empty( $sx['scheduled_publish_at'] ) ? strtotime( (string) $sx['scheduled_publish_at'] . ' UTC' ) : 0;
                        $sched_future = $sched_ts > 0 && $sched_ts > time();
                        $sched_done = $sched_ts > 0 && $sched_ts <= time();
                        $show_links = ( $s_st === 'finalizado' || $sched_done ) && ! $sched_future;
                        $s_dialog = 'rmbz-vip-submission-' . (int) $sub->id;
                        $s_status_messages = [
                            'pendente' => 'A equipa está a rever o teu envio.',
                            'aprovado' => 'O envio foi aprovado e entrou na fila de publicação.',
                            'em_publicacao' => 'A publicação está a ser preparada.',
                            'finalizado' => 'A publicação foi concluída.',
                            'correcao' => 'É preciso corrigir os pontos indicados pela equipa.',
                            'rejeitado' => 'O envio não foi aprovado. Consulta o motivo abaixo.',
                        ];
                    ?>
                        <div class="card rvu-sub-card">
                            <div class="rvu-sub-cover">
                                <?php if ( $s_cover !== '' ): ?>
                                    <img src="<?php echo esc_url( $s_cover ); ?>" alt="" loading="lazy">
                                <?php else: ?>
                                    <span class="ms"><?php echo $s_is_social ? 'share' : 'music_note'; ?></span>
                                <?php endif; ?>
                                <span class="ms rvu-sub-destination"><?php echo $s_is_social ? 'share' : 'language'; ?></span>
                            </div>
                            <div class="rvu-sub-main">
                                <div class="rvu-sub-kind"><span class="ms"><?php echo $s_is_social ? 'share' : 'language'; ?></span><?php echo esc_html( $s_is_social ? 'REDES SOCIAIS' : 'PUBLICAÇÃO NO SITE' ); ?></div>
                                <div style="font-weight:800; font-size:15px; margin-top:5px;"><?php echo esc_html( $sub->music_title ?: '(sem título)' ); ?></div>
                                <div style="font-size:11.5px; color:var(--muted); margin-top:4px; display:flex; gap:10px; flex-wrap:wrap;"><span><?php echo ! empty( $sub->submission_date ) ? esc_html( date_i18n( 'd/m/Y · H:i', strtotime( (string) $sub->submission_date ) ) ) : 'Data não informada'; ?></span><?php if ( ! empty( $sub->music_genre ) ): ?><span>· <?php echo esc_html( $sub->music_genre ); ?></span><?php endif; ?></div>
                                <?php if ( $sched_future ): ?>
                                    <div style="font-size:11.5px; color:var(--rev); font-weight:650; margin-top:3px;">🗓️ Publicação agendada — falta <b class="mono rmbz-vip-cd" data-until="<?php echo (int) $sched_ts; ?>">—</b></div>
                                <?php endif; ?>
                            </div>
                            <div class="rvu-sub-actions">
                                <span class="status" style="background:var(--<?php echo esc_attr( $s_tone ); ?>-soft); color:var(--<?php echo esc_attr( $s_tone ); ?>);"><?php echo esc_html( $s_lbl ); ?></span>
                                <button type="button" class="chip" data-dialog="<?php echo esc_attr( $s_dialog ); ?>" style="padding:8px 13px;"><span class="ms" style="font-size:16px;">visibility</span> Detalhes</button>
                            </div>
                            <?php if ( $show_links ): ?>
                                <?php foreach ( [ 'published_url' => [ 'Site', 'language', '' ], 'youtube_url' => [ 'YouTube', '', 'youtube' ], 'facebook_url' => [ 'Facebook', '', 'facebook' ] ] as $lk => $link_meta ):
                                    if ( ! empty( $sx[ $lk ] ) ): ?><a href="<?php echo esc_url( $sx[ $lk ] ); ?>" target="_blank" rel="noopener" class="chip" style="text-decoration:none;"><?php if ( $link_meta[2] !== '' ) { echo rmbz_vip_social_brand_icon( $link_meta[2], 17 ); } else { ?><span class="ms" style="font-size:16px;"><?php echo esc_html( $link_meta[1] ); ?></span><?php } ?><?php echo esc_html( $link_meta[0] ); ?></a><?php endif;
                                endforeach; ?>
                            <?php endif; ?>
                            <?php if ( in_array( $s_st, [ 'correcao', 'rejeitado' ], true ) && ! empty( $sub->rejection_reason ) ): ?>
                                <button type="button" class="chip rmbz-vip-toggle" data-target="rmbz-vip-subrz-<?php echo (int) $sub->id; ?>">📄 Ver motivo</button>
                            <?php endif; ?>
                            <?php if ( $s_st === 'correcao' ): ?>
                                <button type="button" class="chip rmbz-vip-toggle" data-target="rmbz-vip-subfix-<?php echo (int) $sub->id; ?>" style="border-color:var(--brand); color:var(--brand-ink);">🛠️ Corrigir</button>
                            <?php endif; ?>
                            <?php if ( ! empty( $sub->rejection_reason ) ): ?>
                                <div id="rmbz-vip-subrz-<?php echo (int) $sub->id; ?>" style="display:none; flex-basis:100%; background:var(--danger-soft); border-radius:12px; padding:10px 14px; font-size:12.5px; color:var(--text2);"><b style="color:var(--danger);">Motivo:</b> <?php echo esc_html( $sub->rejection_reason ); ?></div>
                            <?php endif; ?>
                            <?php if ( $s_st === 'correcao' ): ?>
                                <form method="post" action="<?php echo esc_url( $post_url ); ?>" enctype="multipart/form-data" id="rmbz-vip-subfix-<?php echo (int) $sub->id; ?>" style="display:none; flex-basis:100%; background:var(--elev); border-radius:14px; padding:14px;">
                                    <input type="hidden" name="action" value="rmbz_process_correction">
                                    <input type="hidden" name="sub_id" value="<?php echo (int) $sub->id; ?>">
                                    <?php wp_nonce_field( 'rmbz_correction_nonce' ); ?>
                                    <div style="display:flex; gap:12px; flex-wrap:wrap;">
                                        <?php if ( ! empty( $sx['needs_audio_fix'] ) ): ?><label style="flex:1; min-width:180px; font-size:11px; font-weight:750; color:var(--muted);">NOVO ÁUDIO<input class="inp" type="file" name="new_audio" accept="audio/*" style="margin-top:4px;"></label><?php endif; ?>
                                        <?php if ( ! empty( $sx['needs_cover_fix'] ) ): ?><label style="flex:1; min-width:180px; font-size:11px; font-weight:750; color:var(--muted);">NOVA CAPA<input class="inp" type="file" name="new_cover" accept="image/*" style="margin-top:4px;"></label><?php endif; ?>
                                        <?php if ( ! empty( $sx['needs_link_fix'] ) ): ?><label style="flex:1; min-width:180px; font-size:11px; font-weight:750; color:var(--muted);">NOVO LINK<input class="inp" type="url" name="new_link" placeholder="https://…" style="margin-top:4px;"></label><?php endif; ?>
                                    </div>
                                    <button type="submit" class="pill" style="margin-top:12px; background:var(--brand); color:var(--on-brand); font-size:12.5px;">Enviar correção</button>
                                </form>
                            <?php endif; ?>
                        </div>
                        <div class="scrim" id="<?php echo esc_attr( $s_dialog ); ?>">
                            <div class="dialog" style="width:min(620px,96vw); max-height:88vh; overflow:auto;">
                                <div style="display:flex; align-items:center; gap:13px; margin-bottom:16px;">
                                    <?php if ( $s_cover !== '' ): ?><img src="<?php echo esc_url( $s_cover ); ?>" alt="" style="width:54px; height:54px; border-radius:14px; object-fit:cover;">
                                    <?php else: ?><span class="ms" style="width:54px; height:54px; border-radius:14px; background:var(--brand-soft); color:var(--brand-ink); align-items:center; justify-content:center; font-size:25px;">music_note</span><?php endif; ?>
                                    <div style="flex:1; min-width:0;"><div style="font-size:18px; font-weight:800; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;"><?php echo esc_html( $sub->music_title ?: '(sem título)' ); ?></div><div style="font-size:11.5px; color:var(--muted);">Envio #<?php echo (int) $sub->id; ?></div></div>
                                    <button type="button" class="rmbz-vip-dclose" aria-label="Fechar" style="border:0; background:none; color:var(--muted); cursor:pointer;"><span class="ms">close</span></button>
                                </div>
                                <div style="background:var(--<?php echo esc_attr( $s_tone ); ?>-soft); color:var(--<?php echo esc_attr( $s_tone ); ?>); border-radius:14px; padding:12px 14px; font-size:12.5px; font-weight:650; margin-bottom:14px;">
                                    <?php echo esc_html( $s_status_messages[ $s_st ] ?? $s_lbl ); ?>
                                </div>
                                <div class="rmbz-vip-detail-grid" style="display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px;">
                                    <?php foreach ( [
                                        [ 'Estado', $s_lbl ],
                                        [ 'Tipo', $s_is_social ? 'Redes Sociais' : 'Publicação no Site' ],
                                        [ 'Género', (string) ( $sub->music_genre ?: 'Não informado' ) ],
                                        [ 'Enviado em', ! empty( $sub->submission_date ) ? date_i18n( 'd/m/Y H:i', strtotime( (string) $sub->submission_date ) ) : '—' ],
                                    ] as $detail ): ?>
                                        <div style="background:var(--elev); border-radius:12px; padding:11px 13px;"><div style="font-size:10.5px; color:var(--muted); font-weight:750; letter-spacing:.04em;"><?php echo esc_html( $detail[0] ); ?></div><div style="font-size:12.5px; font-weight:650; margin-top:3px; word-break:break-word;"><?php echo esc_html( $detail[1] ); ?></div></div>
                                    <?php endforeach; ?>
                                </div>
                                <?php if ( ! empty( $sub->rejection_reason ) ): ?>
                                    <div style="margin-top:12px; background:var(--danger-soft); border:1px solid var(--danger); border-radius:14px; padding:12px 14px; font-size:12.5px; color:var(--text2);"><b style="color:var(--danger);">Orientação da equipa:</b><br><?php echo nl2br( esc_html( $sub->rejection_reason ) ); ?></div>
                                <?php endif; ?>
                                <div style="display:flex; gap:8px; flex-wrap:wrap; margin-top:14px;">
                                    <?php if ( ! empty( $sub->music_file_url ) ): ?><a class="pill" href="<?php echo esc_url( $sub->music_file_url ); ?>" target="_blank" rel="noopener" style="border:1px solid var(--border); background:none; color:var(--brand-ink); text-decoration:none; font-size:12px;"><span class="ms" style="font-size:16px;">headphones</span> Ouvir ficheiro enviado</a><?php endif; ?>
                                    <?php foreach ( [ 'published_url' => [ 'Abrir no Site', 'language', '' ], 'youtube_url' => [ 'Abrir no YouTube', '', 'youtube' ], 'facebook_url' => [ 'Abrir no Facebook', '', 'facebook' ], 'video_link_url' => [ 'Abrir vídeo enviado', 'movie', '' ], 'social_link' => [ 'Abrir link original', 'link', '' ] ] as $key => $link_meta ): ?>
                                        <?php if ( ! empty( $sx[ $key ] ) ): ?><a class="pill" href="<?php echo esc_url( $sx[ $key ] ); ?>" target="_blank" rel="noopener" style="border:1px solid var(--border); background:none; color:var(--brand-ink); text-decoration:none; font-size:12px;"><?php if ( $link_meta[2] !== '' ) { echo rmbz_vip_social_brand_icon( $link_meta[2], 18 ); } else { ?><span class="ms" style="font-size:16px;"><?php echo esc_html( $link_meta[1] ); ?></span><?php } ?><?php echo esc_html( $link_meta[0] ); ?></a><?php endif; ?>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    </div>
                    <?php rmbz_vip_render_pager( $submission_page, $submission_total, $submission_per_page, 'sub_page', 'envios', [ 'sub_kind' => $submission_kind ] ); ?>
                <?php endif; ?>
                <?php endif; ?>
            </section>

            <!-- ═══ FINANÇAS ═══ -->
            <section class="sect<?php echo $vip_sect === 'financas' ? ' on' : ''; ?>" data-sect="financas" data-screen-label="Finanças">
                <div class="finance-hero">
                    <div class="finance-hero-main">
                        <div class="finance-hero-head"><span class="ms">account_balance_wallet</span><span>Saldo atual da carteira</span><span class="finance-hero-state"><span class="ms">verified</span>Atualizado</span></div>
                        <div class="finance-hero-value"><?php echo esc_html( $fmt( $saldo_total ) ); ?><small>MT</small></div>
                        <div class="finance-balance-facts">
                            <span class="finance-balance-fact"><span class="ms">payments</span>Retirável <b><?php echo esc_html( $fmt( $retiravel ) ); ?> MT</b></span>
                            <?php if ( $promocional > 0 ): ?><span class="finance-balance-fact"><span class="ms">redeem</span>Promocional <b><?php echo esc_html( $fmt( $promocional ) ); ?> MT</b></span><?php endif; ?>
                        </div>
                        <div class="finance-hero-actions">
                            <button type="button" class="pill finance-action primary" data-wallet-action="deposit"><span class="ms">add_circle</span>Depositar</button>
                            <button type="button" class="pill finance-action secondary" data-wallet-action="withdraw"><span class="ms">payments</span>Levantar</button>
                        </div>
                    </div>
                    <div class="finance-hero-metrics">
                        <div class="finance-metric credit"><div class="finance-metric-label">Entradas acumuladas</div><div class="finance-metric-value">+<?php echo esc_html( $fmt( $tx_credit_total ) ); ?> MT</div></div>
                        <div class="finance-metric debit"><div class="finance-metric-label">Saídas acumuladas</div><div class="finance-metric-value">−<?php echo esc_html( $fmt( $tx_debit_total ) ); ?> MT</div></div>
                        <div class="finance-metric wide"><span class="ms finance-metric-icon">pending_actions</span><div><div class="finance-metric-label">Pedidos em análise</div><div class="finance-metric-value"><?php echo (int) ( $dep_pending_total + $wd_pending_total ); ?> pendente(s)</div></div><span class="finance-metric-pending"><?php echo (int) $tx_total_all; ?> movimentos</span></div>
                    </div>
                </div>

                <?php
                $finance_tabs = [
                    'overview'    => [ 'dashboard', 'Visão geral', 0 ],
                    'deposits'    => [ 'add_card', 'Depósitos', $dep_total ],
                    'withdrawals' => [ 'payments', 'Levantamentos', $wd_total ],
                    'statement'   => [ 'receipt_long', 'Extrato', $tx_total_all ],
                ];
                ?>
                <nav aria-label="Opções financeiras" class="finance-tabs">
                    <?php foreach ( $finance_tabs as $fkey => $ftab ):
                        $factive = $finance_view === $fkey;
                        $furl = add_query_arg( [ 'sect' => 'financas', 'fview' => $fkey ], home_url( '/minha-conta/' ) );
                    ?>
                        <a href="<?php echo esc_url( $furl ); ?>" class="finance-tab<?php echo $factive ? ' active' : ''; ?>" aria-current="<?php echo $factive ? 'page' : 'false'; ?>">
                            <span class="ms"><?php echo esc_html( $ftab[0] ); ?></span>
                            <?php echo esc_html( $ftab[1] ); ?>
                            <?php if ( (int) $ftab[2] > 0 ): ?><span class="finance-tab-count"><?php echo (int) $ftab[2]; ?></span><?php endif; ?>
                        </a>
                    <?php endforeach; ?>
                </nav>

                <?php if ( in_array( $finance_view, [ 'overview', 'deposits', 'withdrawals' ], true ) ): ?>
                <div class="finance-panels<?php echo $finance_view === 'overview' ? '' : ' single'; ?>">
                    <?php if ( in_array( $finance_view, [ 'overview', 'deposits' ], true ) ): ?>
                    <div class="card finance-panel">
                        <div class="finance-panel-head"><span class="ms finance-panel-icon">add_card</span><div class="finance-panel-copy"><div class="finance-panel-title">Pedidos de depósito</div><div class="finance-panel-subtitle">Entradas submetidas para validação.</div></div><span class="finance-panel-count"><?php echo (int) $dep_total; ?> pedido(s)</span></div>
                        <?php if ( empty( $depositos ) ): ?><div class="finance-empty"><span class="ms">account_balance_wallet</span><div><strong>Ainda não fizeste depósitos</strong><small>Usa o botão Depositar para adicionar saldo à carteira.</small></div></div><?php else: ?>
                            <div class="finance-request-list">
                            <?php foreach ( $depositos as $dp ):
                                $dp_st = (string) ( $dp->status ?? '' );
                                $dp_tone = $dp_st === 'aprovado' ? 'success' : ( $dp_st === 'rejeitado' ? 'danger' : 'rev' );
                                $dp_dialog = 'rmbz-vip-deposit-' . (int) $dp->id;
                                $dp_transaction_id = trim( (string) ( $dp->transaction_id ?? '' ) );
                                $dp_has_image = ! empty( $dp->proof_image );
                            ?>
                                <div class="finance-request">
                                    <span class="ms finance-request-icon" style="background:var(--<?php echo esc_attr( $dp_tone ); ?>-soft); color:var(--<?php echo esc_attr( $dp_tone ); ?>);">south_west</span>
                                    <div class="finance-request-copy"><div class="mono finance-request-value"><?php echo esc_html( $fmt( (float) ( $dp->amount ?? 0 ) ) ); ?> MT</div><div class="finance-request-meta"><span class="ms">account_balance</span><span><?php echo esc_html( $dp->payment_method ?? 'Método não informado' ); ?></span><span>·</span><span><?php echo ! empty( $dp->request_date ) ? esc_html( date_i18n( 'd/m/Y H:i', strtotime( (string) $dp->request_date ) ) ) : 'Sem data'; ?></span></div></div>
                                    <span class="finance-request-status" style="background:var(--<?php echo esc_attr( $dp_tone ); ?>-soft); color:var(--<?php echo esc_attr( $dp_tone ); ?>);"><?php echo esc_html( ucfirst( $dp_st ) ); ?></span>
                                    <button type="button" class="pill finance-request-detail" data-dialog="<?php echo esc_attr( $dp_dialog ); ?>">Detalhes</button>
                                </div>
                                <div class="scrim" id="<?php echo esc_attr( $dp_dialog ); ?>">
                                    <div class="dialog" style="width:min(520px,96vw);">
                                        <div style="display:flex; align-items:center; gap:12px; margin-bottom:16px;">
                                            <span class="ms" style="width:42px; height:42px; border-radius:14px; align-items:center; justify-content:center; background:var(--<?php echo esc_attr( $dp_tone ); ?>-soft); color:var(--<?php echo esc_attr( $dp_tone ); ?>);">account_balance_wallet</span>
                                            <div style="flex:1;"><div style="font-size:17px; font-weight:800;">Depósito de <?php echo esc_html( $fmt( (float) $dp->amount ) ); ?> MT</div><div style="font-size:11.5px; color:var(--muted);">Pedido #<?php echo (int) $dp->id; ?></div></div>
                                            <button type="button" class="rmbz-vip-dclose" style="border:0; background:none; color:var(--muted); cursor:pointer;"><span class="ms">close</span></button>
                                        </div>
                                        <div class="rmbz-vip-detail-grid" style="display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px;">
                                            <?php foreach ( [
                                                [ 'Estado', ucfirst( $dp_st ) ],
                                                [ 'Método', (string) ( $dp->payment_method ?: '—' ) ],
                                                [ 'ID da transação', $dp_transaction_id !== '' ? $dp_transaction_id : 'Não informado' ],
                                                [ 'Remetente', (string) ( $dp->sender_phone ?: 'Não informado' ) ],
                                                [ 'Pedido', ! empty( $dp->request_date ) ? date_i18n( 'd/m/Y H:i', strtotime( (string) $dp->request_date ) ) : '—' ],
                                                [ 'Processado', ! empty( $dp->processed_date ) ? date_i18n( 'd/m/Y H:i', strtotime( (string) $dp->processed_date ) ) : 'Ainda não' ],
                                                [ 'Origem', ( $dp->source_platform ?? '' ) === 'app' ? 'App Android' : ( ( $dp->source_platform ?? '' ) === 'site' ? 'Site' : 'Não informada' ) ],
                                                [ 'Tipo', ! empty( $dp->is_first_deposit ) ? 'Abertura de conta' : 'Reforço de saldo' ],
                                            ] as $dp_info ): ?>
                                                <div style="background:var(--elev); border-radius:12px; padding:10px 12px;"><div style="font-size:10px; color:var(--muted); font-weight:750; letter-spacing:.06em; text-transform:uppercase;"><?php echo esc_html( $dp_info[0] ); ?></div><div style="font-size:12.5px; color:var(--text2); font-weight:650; margin-top:3px; word-break:break-word;"><?php echo esc_html( $dp_info[1] ); ?></div></div>
                                            <?php endforeach; ?>
                                        </div>
                                        <?php if ( $dp_transaction_id !== '' ): ?>
                                            <div class="deposit-proof-id-note">
                                                <span class="ms" aria-hidden="true">tag</span>
                                                <div><strong>Comprovativo enviado por ID da transação</strong><span><?php echo $dp_has_image ? 'O artista também anexou uma imagem do comprovativo.' : 'Não foi anexada imagem; a validação foi submetida através deste código.'; ?></span></div>
                                            </div>
                                        <?php endif; ?>
                                        <?php if ( $dp_st === 'rejeitado' ): ?>
                                            <div style="margin-top:12px; background:var(--danger-soft); border:1px solid var(--danger); border-radius:14px; padding:12px 14px; font-size:12.5px; color:var(--text2);"><b style="color:var(--danger);">Motivo da rejeição:</b><br><?php echo esc_html( trim( (string) ( $dp->admin_notes ?? '' ) ) ?: 'Motivo não informado.' ); ?></div>
                                        <?php endif; ?>
                                        <?php if ( $dp_has_image ): ?>
                                            <button type="button" class="deposit-proof-trigger" data-proof-src="<?php echo esc_url( $dp->proof_image ); ?>" data-proof-title="Comprovativo do depósito #<?php echo (int) $dp->id; ?>" aria-haspopup="dialog" aria-controls="rmbz-vip-proof-viewer">
                                                <img src="<?php echo esc_url( $dp->proof_image ); ?>" alt="Comprovativo do depósito #<?php echo (int) $dp->id; ?>" loading="lazy">
                                                <span class="deposit-proof-trigger-label"><span class="ms" aria-hidden="true">fullscreen</span>Abrir comprovativo</span>
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                            </div>
                            <?php rmbz_vip_render_pager( $dep_page, $dep_total, $finance_per_page, 'dep_page', 'financas', [ 'fview' => 'deposits' ] ); ?>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                    <?php if ( in_array( $finance_view, [ 'overview', 'withdrawals' ], true ) ): ?>
                    <div class="card finance-panel">
                        <div class="finance-panel-head"><span class="ms finance-panel-icon">payments</span><div class="finance-panel-copy"><div class="finance-panel-title">Pedidos de levantamento</div><div class="finance-panel-subtitle">Saídas da carteira e dos royalties.</div></div><span class="finance-panel-count"><?php echo (int) $wd_total; ?> pedido(s)</span></div>
                        <?php if ( empty( $levantamentos ) ): ?><div class="finance-empty"><span class="ms">payments</span><div><strong>Ainda não fizeste levantamentos</strong><small>Quando houver saldo retirável, podes enviar o pedido aqui.</small></div></div><?php else: ?>
                            <div class="finance-request-list">
                            <?php foreach ( $levantamentos as $lw ):
                                $lw_st = (string) ( $lw->status ?? '' );
                                $lw_tone = in_array( $lw_st, [ 'aprovado', 'pago', 'concluido' ], true ) ? 'success' : ( $lw_st === 'rejeitado' ? 'danger' : 'rev' );
                                $lw_dialog = 'rmbz-vip-withdrawal-' . (int) $lw->id;
                                $lw_source_label = ( (string) ( $lw->source ?? 'wallet' ) === 'royalties' ) ? 'Royalties' : 'Carteira';
                            ?>
                                <div class="finance-request">
                                    <span class="ms finance-request-icon" style="background:var(--<?php echo esc_attr( $lw_tone ); ?>-soft); color:var(--<?php echo esc_attr( $lw_tone ); ?>);">north_east</span>
                                    <div class="finance-request-copy"><div class="mono finance-request-value"><?php echo esc_html( $fmt( (float) ( $lw->amount ?? 0 ) ) ); ?> MT</div><div class="finance-request-meta"><span class="ms"><?php echo $lw_source_label === 'Royalties' ? 'music_note' : 'account_balance_wallet'; ?></span><span><?php echo esc_html( $lw_source_label ); ?></span><span>·</span><span><?php echo esc_html( $lw->payment_method ?? 'Método não informado' ); ?></span><span>·</span><span><?php echo esc_html( $lw->payment_details ?? '' ); ?></span></div></div>
                                    <span class="finance-request-status" style="background:var(--<?php echo esc_attr( $lw_tone ); ?>-soft); color:var(--<?php echo esc_attr( $lw_tone ); ?>);"><?php echo esc_html( ucfirst( $lw_st ) ); ?></span>
                                    <button type="button" class="pill finance-request-detail" data-dialog="<?php echo esc_attr( $lw_dialog ); ?>">Detalhes</button>
                                </div>
                                <div class="scrim" id="<?php echo esc_attr( $lw_dialog ); ?>">
                                    <div class="dialog" style="width:min(520px,96vw);">
                                        <div style="display:flex; align-items:center; gap:12px; margin-bottom:16px;">
                                            <span class="ms" style="width:42px; height:42px; border-radius:14px; align-items:center; justify-content:center; background:var(--<?php echo esc_attr( $lw_tone ); ?>-soft); color:var(--<?php echo esc_attr( $lw_tone ); ?>);">payments</span>
                                            <div style="flex:1;"><div style="font-size:17px; font-weight:800;">Levantamento de <?php echo esc_html( $fmt( (float) $lw->amount ) ); ?> MT</div><div style="font-size:11.5px; color:var(--muted);">Pedido #<?php echo (int) $lw->id; ?></div></div>
                                            <button type="button" class="rmbz-vip-dclose" aria-label="Fechar" style="border:0; background:none; color:var(--muted); cursor:pointer;"><span class="ms">close</span></button>
                                        </div>
                                        <div class="rmbz-vip-detail-grid" style="display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px;">
                                            <?php foreach ( [
                                                [ 'Estado', ucfirst( $lw_st ) ],
                                                [ 'Origem do saldo', (string) ( $lw->source ?? 'wallet' ) === 'royalties' ? 'Royalties' : 'Carteira' ],
                                                [ 'Método', (string) ( $lw->payment_method ?: '—' ) ],
                                                [ 'Destino', (string) ( $lw->payment_details ?: '—' ) ],
                                                [ 'Pedido', ! empty( $lw->request_date ) ? date_i18n( 'd/m/Y H:i', strtotime( (string) $lw->request_date ) ) : '—' ],
                                                [ 'Processado', ! empty( $lw->processed_date ) ? date_i18n( 'd/m/Y H:i', strtotime( (string) $lw->processed_date ) ) : 'Ainda não' ],
                                            ] as $detail ): ?>
                                                <div style="background:var(--elev); border-radius:12px; padding:11px 13px;"><div style="font-size:10.5px; color:var(--muted); font-weight:750; letter-spacing:.04em;"><?php echo esc_html( $detail[0] ); ?></div><div style="font-size:12.5px; font-weight:650; margin-top:3px; word-break:break-word;"><?php echo esc_html( $detail[1] ); ?></div></div>
                                            <?php endforeach; ?>
                                        </div>
                                        <?php if ( $lw_st === 'rejeitado' ): ?>
                                            <div style="margin-top:12px; background:var(--danger-soft); border:1px solid var(--danger); border-radius:14px; padding:12px 14px; font-size:12.5px; color:var(--text2);"><b style="color:var(--danger);">Motivo da rejeição:</b><br><?php echo nl2br( esc_html( trim( (string) ( $lw->admin_notes ?? '' ) ) ?: 'Motivo não informado.' ) ); ?></div>
                                        <?php elseif ( $lw_st === 'pendente' ): ?>
                                            <div style="margin-top:12px; background:var(--rev-soft); border-radius:14px; padding:12px 14px; font-size:12.5px; color:var(--rev);">A equipa financeira ainda está a validar este pedido.</div>
                                        <?php elseif ( ! empty( $lw->admin_notes ) ): ?>
                                            <div style="margin-top:12px; background:var(--elev); border-radius:14px; padding:12px 14px; font-size:12.5px; color:var(--text2);"><b>Observação:</b><br><?php echo nl2br( esc_html( $lw->admin_notes ) ); ?></div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                            </div>
                            <?php rmbz_vip_render_pager( $wd_page, $wd_total, $finance_per_page, 'wd_page', 'financas', [ 'fview' => 'withdrawals' ] ); ?>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                <?php if ( in_array( $finance_view, [ 'overview', 'statement' ], true ) ): ?>
                <div class="card finance-statement" style="margin-top:<?php echo $finance_view === 'overview' ? '13px' : '0'; ?>;">
                    <div class="finance-statement-head">
                        <div class="finance-statement-heading">
                            <span class="ms finance-statement-icon">receipt_long</span>
                            <div><div class="finance-statement-title">Extrato da carteira</div><div class="finance-statement-subtitle"><?php echo $finance_view === 'statement' && ( $tx_search !== '' || $tx_flow !== 'all' ) ? esc_html( sprintf( '%d resultado(s) de %d movimentos', $tx_total, $tx_total_all ) ) : esc_html( sprintf( '%d movimento(s) registado(s)', $tx_total_all ) ); ?></div></div>
                        </div>
                        <?php if ( $finance_view === 'overview' ): ?>
                            <a class="pill finance-statement-open" href="<?php echo esc_url( add_query_arg( [ 'sect' => 'financas', 'fview' => 'statement' ], home_url( '/minha-conta/' ) ) ); ?>"><span class="ms">open_in_full</span> Abrir extrato completo</a>
                        <?php endif; ?>
                    </div>

                    <?php if ( $finance_view === 'statement' ): ?>
                    <form method="get" action="<?php echo esc_url( home_url( '/minha-conta/' ) ); ?>" class="finance-filter">
                        <input type="hidden" name="sect" value="financas">
                        <input type="hidden" name="fview" value="statement">
                        <label style="flex:1 1 260px; min-width:0;"><span class="finance-filter-label">Pesquisar movimento</span><span class="finance-filter-search"><span class="ms">search</span><input type="search" name="tx_q" value="<?php echo esc_attr( $tx_search ); ?>" placeholder="Descrição ou tipo..."></span></label>
                        <label style="flex:0 1 190px;"><span class="finance-filter-label">Tipo</span><select name="tx_flow" class="inp finance-filter-action"><option value="all"<?php selected( $tx_flow, 'all' ); ?>>Todos</option><option value="credit"<?php selected( $tx_flow, 'credit' ); ?>>Entradas</option><option value="debit"<?php selected( $tx_flow, 'debit' ); ?>>Saídas</option><option value="locked"<?php selected( $tx_flow, 'locked' ); ?>>Bloqueados</option></select></label>
                        <button type="submit" class="pill finance-filter-action" style="border:0; background:var(--brand); color:var(--on-brand);"><span class="ms">filter_alt</span> Aplicar</button>
                        <?php if ( $tx_search !== '' || $tx_flow !== 'all' ): ?><a class="pill finance-filter-action" href="<?php echo esc_url( add_query_arg( [ 'sect' => 'financas', 'fview' => 'statement' ], home_url( '/minha-conta/' ) ) ); ?>" style="border:1px solid var(--border); background:var(--surface); color:var(--text2);">Limpar</a><?php endif; ?>
                    </form>
                    <?php endif; ?>

                    <?php
                    $statement_rows = $finance_view === 'overview' ? array_slice( $transacoes, 0, 5 ) : $transacoes;
                    $tx_type_labels = [
                        'deposit' => 'Depósito', 'deposit_credit' => 'Depósito', 'withdrawal' => 'Levantamento',
                        'withdrawal_refund' => 'Reembolso', 'subscription_payment' => 'Subscrição VIP',
                        'project_payment' => 'Pagamento de projeto', 'distro_payout' => 'Royalties',
                        'referral_bonus' => 'Bónus de convite', 'coupon' => 'Cupão', 'refund' => 'Reembolso',
                        'music_boost_payment' => 'Impulsionamento de música', 'music_boost_refund' => 'Reembolso de campanha',
                    ];
                    ?>
                    <?php if ( empty( $statement_rows ) ): ?>
                        <div class="finance-empty" style="margin:18px;"><span class="ms">receipt_long</span><div><strong><?php echo ( $tx_search !== '' || $tx_flow !== 'all' ) ? 'Nenhum movimento encontrado' : 'Ainda não há movimentos'; ?></strong><small><?php echo ( $tx_search !== '' || $tx_flow !== 'all' ) ? 'Experimenta alterar a pesquisa ou o filtro.' : 'As entradas e saídas da carteira aparecerão aqui.'; ?></small></div></div>
                    <?php else: ?>
                        <div class="finance-transactions">
                        <?php foreach ( $statement_rows as $tx ):
                            $tx_val      = (float) ( $tx->amount ?? 0 );
                            $tx_credit   = $tx_val >= 0;
                            $tx_locked   = isset( $tx->is_unlocked ) && (int) $tx->is_unlocked === 0;
                            $tx_type_key = sanitize_key( (string) ( $tx->type ?? '' ) );
                            $tx_type_lbl = $tx_type_labels[ $tx_type_key ] ?? ucwords( str_replace( '_', ' ', $tx_type_key ?: 'movimento' ) );
                            $tx_details  = trim( (string) ( $tx->details ?? '' ) );
                            $tx_date     = ! empty( $tx->transaction_date ) ? date_i18n( 'd/m/Y · H:i', strtotime( (string) $tx->transaction_date ) ) : 'Data não informada';
                        ?>
                            <div class="finance-transaction">
                                <span class="ms finance-transaction-icon" style="background:<?php echo $tx_locked ? 'var(--rev-soft)' : ( $tx_credit ? 'var(--success-soft)' : 'var(--danger-soft)' ); ?>; color:<?php echo $tx_locked ? 'var(--rev)' : ( $tx_credit ? 'var(--success)' : 'var(--danger)' ); ?>;"><?php echo $tx_locked ? 'lock_clock' : ( $tx_credit ? 'south_west' : 'north_east' ); ?></span>
                                <div class="finance-transaction-copy"><div class="finance-transaction-title"><?php echo esc_html( $tx_details !== '' ? $tx_details : $tx_type_lbl ); ?></div><div class="finance-transaction-meta"><span><?php echo esc_html( $tx_type_lbl ); ?></span><span>·</span><span><?php echo esc_html( $tx_date ); ?></span><?php if ( $tx_locked ): ?><span class="finance-transaction-state" style="color:var(--rev);">· Bloqueado<?php echo ! empty( $tx->unlock_date ) ? ' até ' . esc_html( date_i18n( 'd/m/Y', strtotime( (string) $tx->unlock_date ) ) ) : ''; ?></span><?php else: ?><span class="finance-transaction-state" style="color:var(--success);">· Disponível</span><?php endif; ?></div></div>
                                <div class="mono finance-transaction-value" style="color:<?php echo $tx_credit ? 'var(--success)' : 'var(--danger)'; ?>;"><?php echo $tx_credit ? '+' : '−'; ?><?php echo esc_html( $fmt( abs( $tx_val ) ) ); ?> MT</div>
                            </div>
                        <?php endforeach; ?>
                        </div>
                        <?php if ( $finance_view === 'statement' ): ?>
                            <div style="padding:0 22px 18px;"><?php rmbz_vip_render_pager( $tx_page, $tx_total, $statement_per_page, 'tx_page', 'financas', [ 'fview' => 'statement', 'tx_q' => $tx_search, 'tx_flow' => $tx_flow ] ); ?></div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </section>

            <!-- ═══ ESTATÍSTICAS ═══ -->
            <section class="sect<?php echo $vip_sect === 'stats' ? ' on' : ''; ?>" data-sect="stats" data-screen-label="Estatísticas">
                <div class="stats-toolbar">
                    <div class="stats-toolbar-copy">
                        <div class="stats-toolbar-title"><?php echo $stats_has_distribution ? 'Desempenho da tua música' : 'A tua atividade na 1MZ'; ?></div>
                        <div class="stats-toolbar-subtitle"><?php echo $stats_has_distribution ? 'Streams e ganhos dos relatórios aprovados pela 1MZ.' : 'Videoclipes, envios, carteira, convites e percurso num único resumo.'; ?></div>
                    </div>
                    <?php if ( $stats_has_distribution ): ?>
                        <div class="stats-toolbar-actions">
                            <span class="stats-range<?php echo $insight_range_active ? ' custom' : ''; ?>"><span class="ms">date_range</span><?php echo $insight_range_active ? esc_html( date_i18n( 'd/m/Y', strtotime( $insight_date_from ) ) . ' – ' . date_i18n( 'd/m/Y', strtotime( $insight_date_to ) ) ) : 'Todo o período'; ?></span>
                            <button type="button" class="pill stats-filter-action" data-dialog="rmbz-vip-stats-filter"><span class="ms">filter_alt</span>Filtrar por data</button>
                            <?php if ( $insight_range_active || $insight_date_error !== '' ): ?><a href="<?php echo esc_url( add_query_arg( [ 'sect' => 'stats' ], home_url( '/minha-conta/' ) ) ); ?>" class="chip">Mostrar tudo</a><?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <?php if ( $stats_has_distribution && $insight_date_error !== '' ): ?><div class="stats-error"><span class="ms">error</span><span><?php echo esc_html( $insight_date_error ); ?> Os dados abaixo continuam a mostrar todo o período.</span></div><?php endif; ?>

                <?php if ( $stats_has_distribution ): ?>
                    <div class="scrim" id="rmbz-vip-stats-filter">
                        <div class="dialog" style="width:min(500px,96vw);">
                            <div style="display:flex; align-items:center; gap:12px; margin-bottom:18px;"><span class="ms" style="width:42px;height:42px;border-radius:14px;align-items:center;justify-content:center;background:var(--brand-soft);color:var(--brand-ink);">date_range</span><div style="flex:1;"><h2 data-dialog-title style="font-family:'Bricolage Grotesque',sans-serif;font-size:20px;margin:0;">Filtrar estatísticas</h2><div style="font-size:11.5px;color:var(--muted);margin-top:2px;">Escolhe o início e o fim do intervalo.</div></div><button type="button" class="rmbz-vip-dclose" aria-label="Fechar" style="border:0;background:none;color:var(--muted);cursor:pointer;"><span class="ms">close</span></button></div>
                            <form method="get" action="<?php echo esc_url( home_url( '/minha-conta/' ) ); ?>">
                                <input type="hidden" name="sect" value="stats">
                                <div class="grid2" style="gap:12px;"><label><span style="display:block;font-size:10.5px;font-weight:750;color:var(--muted);margin:0 0 6px 2px;">DATA INICIAL</span><input class="inp" type="date" name="stats_from" value="<?php echo esc_attr( $insight_date_from ); ?>" max="<?php echo esc_attr( $insight_date_max ); ?>" required></label><label><span style="display:block;font-size:10.5px;font-weight:750;color:var(--muted);margin:0 0 6px 2px;">DATA FINAL</span><input class="inp" type="date" name="stats_to" value="<?php echo esc_attr( $insight_date_to ); ?>" max="<?php echo esc_attr( $insight_date_max ); ?>" required></label></div>
                                <div style="border-radius:13px;padding:10px 12px;margin-top:12px;background:var(--elev);color:var(--muted);font-size:11.5px;line-height:1.5;">Sem filtro, são apresentados todos os dados desde o primeiro relatório aprovado.</div>
                                <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:18px;flex-wrap:wrap;"><a href="<?php echo esc_url( add_query_arg( [ 'sect' => 'stats' ], home_url( '/minha-conta/' ) ) ); ?>" class="pill" style="border:1px solid var(--border);background:none;color:var(--text2);">Todo o período</a><button type="submit" class="pill" style="border:0;background:var(--brand);color:var(--on-brand);"><span class="ms">check</span>Aplicar intervalo</button></div>
                            </form>
                        </div>
                    </div>

                    <?php if ( is_array( $insight_view ) ): ?><div class="stats-insight-hero"><span class="ms stats-insight-icon">auto_awesome</span><div><div class="stats-insight-title"><?php echo esc_html( $insight_view['headline'] ?? 'Resumo do período' ); ?></div><div class="stats-insight-summary"><?php echo esc_html( $insight_view['summary'] ?? '' ); ?></div></div></div><?php endif; ?>

                    <?php if ( is_array( $insight_facts ) ):
                        $stream_delta = $insight_facts['streams']['delta'] ?? [ 'pct' => 0, 'direction' => 'flat' ];
                        $earn_delta = $insight_facts['earnings']['delta'] ?? [ 'pct' => 0, 'direction' => 'flat' ];
                        $delta_meta = static function ( $delta ) { $dir = (string) ( $delta['direction'] ?? 'flat' ); return [ $dir === 'up' ? 'trending_up' : ( $dir === 'down' ? 'trending_down' : 'trending_flat' ), $dir === 'up' ? 'success' : ( $dir === 'down' ? 'danger' : 'muted' ) ]; };
                        [ $stream_icon, $stream_tone ] = $delta_meta( $stream_delta ); [ $earn_icon, $earn_tone ] = $delta_meta( $earn_delta );
                        $top_platform = $insight_facts['top_platform'] ?? null; $top_country = $insight_facts['top_country'] ?? null; $top_track = $insight_facts['top_track'] ?? null;
                    ?>
                        <div class="stats-metric-grid">
                            <div class="stats-metric-card" style="--stat-tone:var(--text);--stat-soft:var(--brand-soft);"><div class="stats-metric-head"><span class="ms stats-metric-icon">headphones</span><span class="stats-metric-label"><?php echo $insight_range_active ? 'Streams no intervalo' : 'Streams de sempre'; ?></span></div><div class="stats-metric-value"><?php echo esc_html( number_format( (int) ( $insight_facts['streams']['current'] ?? 0 ) ) ); ?></div><div class="stats-metric-detail<?php echo $insight_period !== 'all' ? ' trend' : ''; ?>" style="--stat-tone:var(--<?php echo esc_attr( $stream_tone ); ?>);"><?php if ( $insight_period !== 'all' ): ?><span class="ms"><?php echo esc_html( $stream_icon ); ?></span><?php echo esc_html( number_format( abs( (float) ( $stream_delta['pct'] ?? 0 ) ), 1, ',', '.' ) ); ?>% face ao anterior<?php else: ?>Reproduções confirmadas<?php endif; ?></div></div>
                            <div class="stats-metric-card" style="--stat-tone:var(--success);--stat-soft:var(--success-soft);"><div class="stats-metric-head"><span class="ms stats-metric-icon">payments</span><span class="stats-metric-label"><?php echo $insight_range_active ? 'Ganhos no intervalo' : 'Ganhos de sempre'; ?></span></div><div class="stats-metric-value">$ <?php echo esc_html( number_format( (float) ( $insight_facts['earnings']['current'] ?? 0 ), 2, ',', '.' ) ); ?></div><div class="stats-metric-detail<?php echo $insight_period !== 'all' ? ' trend' : ''; ?>" style="--stat-tone:var(--<?php echo esc_attr( $earn_tone ); ?>);"><?php if ( $insight_period !== 'all' ): ?><span class="ms"><?php echo esc_html( $earn_icon ); ?></span><?php echo esc_html( number_format( abs( (float) ( $earn_delta['pct'] ?? 0 ) ), 1, ',', '.' ) ); ?>% face ao anterior<?php else: ?>Royalties confirmados<?php endif; ?></div></div>
                            <div class="stats-metric-card" style="--stat-tone:var(--brand-ink);--stat-soft:var(--brand-soft);"><div class="stats-metric-head"><span class="ms stats-metric-icon">movie</span><span class="stats-metric-label">Produções 1MZ</span></div><div class="stats-metric-value"><?php echo (int) $project_total; ?></div><div class="stats-metric-detail">Videoclipes submetidos</div></div>
                        </div>
                        <div class="stats-highlight-grid">
                            <div class="stats-highlight-card"><span class="ms stats-highlight-icon">headphones</span><div><div class="stats-highlight-label">Plataforma principal</div><div class="stats-highlight-value"><?php echo esc_html( $top_platform['store'] ?? 'Sem dados' ); ?></div><div class="stats-highlight-detail"><?php echo $top_platform ? esc_html( number_format( (float) $top_platform['percentage'], 1, ',', '.' ) ) . '% dos streams' : 'A aguardar relatórios'; ?></div></div></div>
                            <div class="stats-highlight-card"><span class="ms stats-highlight-icon">public</span><div><div class="stats-highlight-label">País principal</div><div class="stats-highlight-value"><?php echo esc_html( trim( (string) ( $top_country['flag'] ?? '' ) . ' ' . (string) ( $top_country['name'] ?? 'Sem dados' ) ) ); ?></div><div class="stats-highlight-detail"><?php echo $top_country ? esc_html( number_format( (float) $top_country['percentage'], 1, ',', '.' ) ) . '% dos streams' : 'A aguardar relatórios'; ?></div></div></div>
                            <div class="stats-highlight-card"><span class="ms stats-highlight-icon">music_note</span><div><div class="stats-highlight-label">Faixa principal</div><div class="stats-highlight-value"><?php echo esc_html( $top_track['title'] ?? 'Sem dados' ); ?></div><div class="stats-highlight-detail"><?php echo $top_track ? esc_html( number_format( (int) $top_track['streams'] ) ) . ' streams' : 'A aguardar relatórios'; ?></div></div></div>
                        </div>
                    <?php else: ?><div class="stats-activity-hero"><span class="ms stats-activity-hero-icon">schedule</span><div><div class="stats-activity-hero-title">Distribuição iniciada</div><div class="stats-activity-hero-copy">Os indicadores musicais aparecerão assim que chegar o primeiro relatório aprovado.</div></div><span class="stats-activity-hero-badge"><span class="ms">sync</span>A aguardar dados</span></div><?php endif; ?>
                <?php else: ?>
                    <div class="stats-activity-hero"><span class="ms stats-activity-hero-icon">space_dashboard</span><div><div class="stats-activity-hero-title">O teu percurso na 1MZ</div><div class="stats-activity-hero-copy">Este resumo acompanha o que já fizeste no site e ajuda-te a encontrar o próximo passo.</div></div><span class="stats-activity-hero-badge"><span class="ms">verified</span>Atividade real</span></div>
                    <div class="stats-activity-grid">
                        <?php foreach ( $stats_activity_cards as $activity ): $activity_tone = $activity[5]; ?>
                            <button type="button" class="stats-activity-card" data-nav="<?php echo esc_attr( $activity[4] ); ?>" style="--activity-tone:var(--<?php echo esc_attr( $activity_tone === 'brand' ? 'brand-ink' : $activity_tone ); ?>);--activity-soft:var(--<?php echo esc_attr( $activity_tone === 'brand' ? 'brand' : $activity_tone ); ?>-soft);"><span class="ms stats-activity-icon"><?php echo esc_html( $activity[0] ); ?></span><span class="stats-activity-content"><span class="stats-activity-label"><?php echo esc_html( $activity[1] ); ?></span><span class="stats-activity-value"><?php echo esc_html( $activity[2] ); ?></span><span class="stats-activity-detail"><?php echo esc_html( $activity[3] ); ?></span></span><span class="ms stats-activity-arrow">chevron_right</span></button>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <div class="stats-ai-card" style="border-color:<?php echo $ai_entitled ? 'var(--brand)' : 'var(--border)'; ?>;">
                    <div class="stats-ai-head"><span class="ms stats-ai-icon">psychology</span><div class="stats-ai-copy"><div class="stats-ai-title">Assistente 1MZ</div><div class="stats-ai-subtitle"><?php echo $ai_entitled ? ( $stats_has_distribution ? 'Pergunta sobre os teus números e lançamentos.' : 'Pergunta sobre videoclipes, envios, carteira ou próximos passos.' ) : 'Esta ferramenta precisa do add-on de IA na tua subscrição.'; ?></div></div><?php if ( ! $ai_entitled ): ?><button type="button" class="pill" data-nav="perfil" style="background:var(--brand);color:var(--on-brand);border:0;">Ver planos com IA</button><?php endif; ?></div>
                    <?php if ( $ai_entitled ): ?><form id="rmbz-vip-ai-form" style="margin-top:14px;display:flex;gap:10px;align-items:flex-end;"><label style="flex:1;"><span style="display:block;font-size:11px;font-weight:750;color:var(--muted);margin-bottom:5px;">A TUA PERGUNTA</span><textarea class="inp" id="rmbz-vip-ai-question" maxlength="400" rows="2" required placeholder="<?php echo $stats_has_distribution ? 'Ex.: Qual música devo promover primeiro?' : 'Ex.: Qual deve ser o meu próximo passo na 1MZ?'; ?>"></textarea></label><button type="submit" class="pill" id="rmbz-vip-ai-send" style="background:var(--brand);color:var(--on-brand);min-height:45px;"><span class="ms">send</span>Perguntar</button></form><div id="rmbz-vip-ai-answer" aria-live="polite" style="display:none;margin-top:14px;background:var(--elev);border-radius:16px;padding:14px 16px;font-size:13px;color:var(--text2);line-height:1.65;white-space:pre-line;"></div><?php endif; ?>
                </div>

                <div class="stats-achievements">
                    <div class="stats-achievements-head"><div><div class="stats-achievements-title"><?php echo $stats_has_distribution ? 'Conquistas reais' : 'Conquistas da tua conta'; ?></div><div class="stats-achievements-subtitle">Metas verificadas automaticamente pelos teus dados.</div></div><span class="status" style="background:var(--brand-soft);color:var(--brand-ink);"><?php echo (int) $milestone_achieved_count; ?> de <?php echo (int) $milestone_total_count; ?></span></div>
                    <?php if ( empty( $stats_milestone_groups ) ): ?><p style="font-size:12px;color:var(--muted);">As conquistas serão calculadas assim que existirem dados suficientes.</p><?php else: $stats_group_index = 0; $stats_group_icons = [ 'catalog' => 'library_music', 'audience' => 'headphones', 'financial' => 'savings', 'time' => 'calendar_month', 'community' => 'groups' ]; ?>
                        <?php foreach ( $stats_milestone_groups as $category => $group ): $stats_group_achieved = count( array_filter( $group, static fn( $item ) => ! empty( $item['achieved'] ) ) ); ?>
                            <details class="stats-achievement-group"<?php echo $stats_group_index++ === 0 ? ' open' : ''; ?>><summary><span class="ms stats-achievement-group-icon"><?php echo esc_html( $stats_group_icons[ $category ] ?? 'emoji_events' ); ?></span><span class="stats-achievement-group-name"><?php echo esc_html( $milestone_category_labels[ $category ] ?? $category ); ?></span><span class="stats-achievement-group-count"><?php echo (int) $stats_group_achieved; ?> / <?php echo count( $group ); ?></span><span class="ms stats-achievement-chevron">expand_more</span></summary><div class="stats-achievement-grid">
                                <?php foreach ( $group as $milestone ): ?><div class="stats-achievement-card<?php echo $milestone['achieved'] ? ' achieved' : ''; ?>"><span class="ms stats-achievement-icon"><?php echo esc_html( $milestone['icon'] ); ?></span><div><div class="stats-achievement-title"><?php echo esc_html( $milestone['title'] ); ?></div><?php if ( $milestone['description'] !== '' ): ?><div class="stats-achievement-description"><?php echo esc_html( $milestone['description'] ); ?></div><?php endif; ?><div class="stats-achievement-progress"><span style="width:<?php echo (int) $milestone['pct']; ?>%;"></span></div><div class="stats-achievement-meta"><?php echo $milestone['achieved'] ? 'Conquistado em ' . esc_html( date_i18n( 'd/m/Y', strtotime( $milestone['achieved_at'] ) ) ) : esc_html( number_format( $milestone['current'], 0, ',', '.' ) . ' / ' . number_format( $milestone['target'], 0, ',', '.' ) ); ?></div></div></div><?php endforeach; ?>
                            </div></details>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </section>

            <!-- ═══ NOTIFICAÇÕES ═══ -->
            <section class="sect<?php echo $vip_sect === 'notifs' ? ' on' : ''; ?>" data-sect="notifs" data-screen-label="Notificações">
                <?php if ( ( $_GET['saved'] ?? '' ) === 'prefs' ): ?><div style="background:var(--success-soft); color:var(--success); border:1px solid var(--success); border-radius:14px; padding:11px 14px; font-size:12.5px; font-weight:650; margin-bottom:14px;">Preferências guardadas.</div><?php endif; ?>
                <div style="display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; max-width:920px; margin-bottom:14px;">
                    <div><div style="font-size:16px; font-weight:800;">Centro de notificações</div><div style="font-size:12px; color:var(--muted); margin-top:2px;"><?php echo (int) $notif_total; ?> aviso(s) ativo(s) · sincronizado com a App.</div></div>
                    <?php if ( ! empty( $notifs ) ): ?><button type="button" class="chip" id="rmbz-vip-notif-clear"><span class="ms" style="font-size:16px;">done_all</span> Marcar tudo como visto</button><?php endif; ?>
                </div>
                <?php if ( empty( $notifs ) ): ?>
                    <div class="card" style="text-align:center; max-width:920px;"><span class="ms" style="font-size:42px; color:var(--muted);">notifications_none</span><p style="font-weight:700; margin:6px 0 0;">Tudo em dia</p><p style="font-size:12.5px; color:var(--muted); margin:4px 0 0;">Não tens notificações pendentes.</p></div>
                <?php else: ?>
                    <div style="display:flex; flex-direction:column; gap:10px; max-width:920px;">
                    <?php foreach ( $notifs as $n ):
                        $n_tone = [ 'info' => 'info', 'success' => 'success', 'warning' => 'rev', 'danger' => 'danger' ][ $n['severity'] ?? 'info' ] ?? 'info';
                        $n_icon = [ 'info' => 'info', 'success' => 'check_circle', 'warning' => 'warning', 'danger' => 'error' ][ $n['severity'] ?? 'info' ] ?? 'notifications';
                    ?>
                        <div class="card rmbz-vip-notif" tabindex="0" role="button" aria-expanded="false" data-nid="<?php echo (int) $n['id']; ?>" data-source="<?php echo esc_attr( $n['source'] ?? 'native' ); ?>" data-read="<?php echo $n['lida'] ? '1' : '0'; ?>" style="padding:15px 18px; display:flex; gap:14px; align-items:flex-start; border-color:var(--<?php echo esc_attr( $n_tone ); ?>); cursor:pointer;">
                            <span class="ms" style="font-size:20px; color:var(--<?php echo esc_attr( $n_tone ); ?>); background:var(--<?php echo esc_attr( $n_tone ); ?>-soft); width:40px; height:40px; border-radius:13px; align-items:center; justify-content:center; flex-shrink:0; font-variation-settings:'FILL' 1;"><?php echo esc_html( $n_icon ); ?></span>
                            <div style="flex:1; min-width:0;">
                                <div style="font-size:14px; font-weight:700;"><?php echo esc_html( $n['titulo'] ); ?></div>
                                <?php if ( $n['texto'] !== '' ): ?>
                                    <div class="rmbz-vip-notif-snip" style="font-size:12.5px; color:var(--text2); margin-top:3px; line-height:1.5;"><?php echo esc_html( mb_substr( $n['texto'], 0, 180 ) ); ?><?php echo mb_strlen( $n['texto'] ) > 180 ? '…' : ''; ?></div>
                                    <div class="rmbz-vip-notif-full" style="display:none; font-size:12.5px; color:var(--text2); margin-top:3px; line-height:1.6; white-space:pre-line;"><?php echo esc_html( $n['texto'] ); ?></div>
                                <?php endif; ?>
                                <div style="font-size:11px; color:var(--muted); margin-top:6px;"><?php echo esc_html( $n['quando'] ); ?></div>
                                <?php if ( ! empty( $n['action_url'] ) ): ?><a class="pill rmbz-vip-notif-action" href="<?php echo esc_url( $n['action_url'] ); ?>" style="margin-top:10px; display:inline-flex; background:var(--brand-soft); color:var(--brand-ink); text-decoration:none; font-size:11.5px; padding:7px 12px;"><?php echo esc_html( $n['action_label'] ?: 'Ver detalhes' ); ?> <span class="ms" style="font-size:15px;">arrow_forward</span></a><?php endif; ?>
                            </div>
                            <span class="ms" style="font-size:18px; color:var(--muted);">expand_more</span>
                        </div>
                    <?php endforeach; ?>
                    </div>
                    <?php rmbz_vip_render_pager( $notif_page, $notif_total, $notif_per_page, 'notif_page', 'notifs' ); ?>
                <?php endif; ?>

                <?php if ( ! empty( $notif_categories ) ): ?>
                    <form method="post" action="<?php echo esc_url( $post_url ); ?>" class="card" style="max-width:920px; margin-top:20px;">
                        <input type="hidden" name="action" value="rmbz_vip_save_notif_prefs">
                        <?php wp_nonce_field( 'rmbz_vip_notif_prefs' ); ?>
                        <div style="font-size:14px; font-weight:800;">Preferências de push</div>
                        <p style="font-size:12px; color:var(--muted); margin:4px 0 14px;">Escolhe quais categorias podem tocar no teu telemóvel. Os avisos continuam guardados no centro.</p>
                        <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:10px;">
                            <?php foreach ( $notif_categories as $key => $cat ): $enabled = (bool) ( $notif_prefs[ $key ] ?? true ); ?>
                                <label style="display:flex; align-items:center; gap:11px; background:var(--elev); border:1px solid var(--border); border-radius:15px; padding:12px 14px; cursor:pointer;">
                                    <input type="checkbox" name="pref_<?php echo esc_attr( $key ); ?>" value="1" <?php checked( $enabled ); ?> style="width:20px; height:20px; accent-color:var(--brand);">
                                    <span style="font-size:20px;"><?php echo esc_html( $cat['icon'] ?? '🔔' ); ?></span>
                                    <span><span style="display:block; font-size:12.5px; font-weight:750;"><?php echo esc_html( $cat['label'] ?? $key ); ?></span><span style="display:block; font-size:10.5px; color:var(--muted); line-height:1.35; margin-top:2px;"><?php echo esc_html( $cat['desc'] ?? '' ); ?></span></span>
                                </label>
                            <?php endforeach; ?>
                        </div>
                        <button type="submit" class="pill" style="margin-top:14px; background:var(--brand); color:var(--on-brand);">Guardar preferências</button>
                    </form>
                <?php endif; ?>
            </section>

            <!-- ═══ PERFIL & VIP ═══ -->
            <section class="sect<?php echo $vip_sect === 'perfil' ? ' on' : ''; ?>" data-sect="perfil" data-screen-label="Perfil">
                <div class="vip-profile-grid">
                    <div class="card vip-profile-identity">
                        <div class="vip-profile-avatar"><?php echo esc_html( $inicial ); ?></div>
                        <div class="vip-profile-name"><?php echo esc_html( $nome ); ?></div>
                        <div class="vip-profile-role">Artista 1MZ</div>
                        <div class="vip-membership">
                            <div class="vip-membership-head">
                                <span class="ms">workspace_premium</span>
                                Subscrição VIP
                                <span class="vip-membership-state<?php echo $has_subscription ? '' : ' inactive'; ?>"><?php echo $has_subscription ? 'Ativa' : 'Inativa'; ?></span>
                            </div>
                            <div class="vip-membership-plan"><?php echo esc_html( $has_subscription ? $vip_plan_name : 'Sem plano ativo' ); ?></div>
                            <div class="vip-membership-facts">
                                <div class="vip-membership-fact"><span>Válido até</span><strong><?php echo esc_html( $has_subscription ? $vip_data : '—' ); ?></strong></div>
                                <div class="vip-membership-fact"><span>Tempo restante</span><strong><?php echo $has_subscription ? (int) $vip_dias . ' ' . ( $vip_dias === 1 ? 'dia' : 'dias' ) : 'Expirado'; ?></strong></div>
                            </div>
                            <button type="button" class="vip-membership-link" id="rmbz-vip-plan-open"><span class="ms">autorenew</span><?php echo $has_subscription ? 'Renovar ou mudar plano' : 'Escolher um plano'; ?></button>
                        </div>
                    </div>
                    <div class="card vip-account-card">
                        <div class="vip-section-head">
                            <span class="ms vip-section-icon">manage_accounts</span>
                            <div class="vip-section-copy"><div class="vip-section-title">Dados de conta</div><div class="vip-section-subtitle">Informação usada para identificar e proteger a tua conta.</div></div>
                            <span class="vip-account-badge"><span class="ms">lock</span> Dados privados</span>
                        </div>
                        <?php
                        $campos = [
                            [ 'call', 'TELEMÓVEL', '+258 ' . $tel9 ],
                            [ 'mail', 'EMAIL', $email !== '' ? $email : '—' ],
                            [ 'artist', 'NOME ARTÍSTICO', $nome ],
                            [ 'account_balance_wallet', 'SALDO ATUAL', $fmt( $saldo_total ) . ' MT' ],
                        ];
                        ?>
                        <div class="vip-account-grid">
                            <?php foreach ( $campos as $c ): ?>
                                <div class="vip-account-field"><span class="ms"><?php echo esc_html( $c[0] ); ?></span><div class="vip-account-field-copy"><div class="vip-account-field-label"><?php echo esc_html( $c[1] ); ?></div><div class="vip-account-field-value"><?php echo esc_html( $c[2] ); ?></div></div></div>
                            <?php endforeach; ?>
                        </div>

                        <?php // [1.5.415] Editar email + província (com verificação OTP — igual ao antigo). ?>
                        <div class="vip-account-actions">
                            <button type="button" class="pill vip-account-action rmbz-vip-toggle" data-target="rmbz-vip-profedit"><span class="ms">edit</span> Atualizar email / província</button>
                            <a href="<?php echo esc_url( $logout_url ); ?>" class="pill vip-account-action danger"><span class="ms">logout</span> Terminar sessão</a>
                        </div>
                        <form method="post" action="<?php echo esc_url( $post_url ); ?>" id="rmbz-vip-profedit" class="vip-account-edit" style="display:none;">
                            <input type="hidden" name="action" value="rmbz_update_profile_request">
                            <?php wp_nonce_field( 'rmbz_update_profile_nonce' ); ?>
                            <label style="display:block; font-size:11px; font-weight:750; color:var(--muted); letter-spacing:.05em; margin-bottom:4px;">EMAIL</label>
                            <input class="inp" type="email" name="user_email" required value="<?php echo esc_attr( $email ); ?>" placeholder="O teu melhor email…">
                            <label style="display:block; font-size:11px; font-weight:750; color:var(--muted); letter-spacing:.05em; margin:12px 0 4px;">PROVÍNCIA</label>
                            <select class="inp" name="user_provincia">
                                <?php foreach ( [ 'Maputo Cidade','Maputo Província','Gaza','Inhambane','Sofala','Manica','Tete','Zambézia','Nampula','Cabo Delgado','Niassa','Diáspora' ] as $prov ): ?>
                                    <option value="<?php echo esc_attr( $prov ); ?>" <?php selected( (string) ( $user->user_provincia ?? '' ), $prov ); ?>><?php echo esc_html( $prov ); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <p style="font-size:11.5px; color:var(--muted); margin:10px 0;">Ao mudar o email recebes um código de confirmação (OTP) para validar.</p>
                            <button type="submit" class="pill" style="background:var(--brand); color:var(--on-brand); font-size:12.5px;">Guardar e receber código</button>
                        </form>
                    </div>
                </div>

                <div class="card" style="margin-top:20px;">
                    <div style="display:flex; align-items:center; gap:13px; flex-wrap:wrap; margin-bottom:16px;">
                        <span class="ms" style="width:46px; height:46px; border-radius:15px; background:var(--brand-soft); color:var(--brand-ink); align-items:center; justify-content:center; font-size:24px; font-variation-settings:'FILL' 1;">workspace_premium</span>
                        <div style="flex:1; min-width:220px;">
                            <div style="font-size:15px; font-weight:800;">Serviços incluídos no teu VIP</div>
                            <div style="font-size:12px; color:var(--muted); margin-top:2px;">
                                <?php echo esc_html( $vip_plan_name ); ?> · <?php echo (int) count( $vip_service_items ); ?> <?php echo count( $vip_service_items ) === 1 ? 'serviço contratado' : 'serviços contratados'; ?>
                            </div>
                        </div>
                        <span class="status" style="background:var(--success-soft); color:var(--success);"><span class="ms" style="font-size:15px; margin-right:5px; font-variation-settings:'FILL' 1;">verified</span> Plano ativo</span>
                    </div>

                    <?php if ( empty( $vip_service_items ) ): ?>
                        <div style="border:1px dashed var(--border2); border-radius:18px; padding:18px; background:var(--elev); color:var(--muted); font-size:12.5px;">Não foi encontrado nenhum serviço associado a este plano. Consulta os pacotes abaixo ou contacta o suporte.</div>
                    <?php else: ?>
                        <div class="vip-services-grid">
                            <?php foreach ( $vip_service_items as $service ):
                                $service_available = ! empty( $service['available'] );
                                $service_state = $service_available ? 'Disponível' : 'Suspenso';
                                $service_action = $service_available ? 'Abrir serviço' : 'Ver situação';
                            ?>
                                <button type="button"
                                        class="vip-service<?php echo $service_available ? '' : ' is-paused'; ?>"
                                        data-nav="<?php echo esc_attr( $service['nav'] ); ?>"
                                        title="<?php echo esc_attr( $service_available ? $service['title'] : $service['reason'] ); ?>">
                                    <div style="display:flex; align-items:flex-start; justify-content:space-between; gap:10px;">
                                        <span class="ms vip-service-icon"><?php echo esc_html( $service['icon'] ); ?></span>
                                        <span class="vip-service-state<?php echo $service_available ? '' : ' is-paused'; ?>">
                                            <span class="ms" style="font-size:14px; font-variation-settings:'FILL' 1;"><?php echo $service_available ? 'check_circle' : 'schedule'; ?></span>
                                            <?php echo esc_html( $service_state ); ?>
                                        </span>
                                    </div>
                                    <div style="font-size:14px; font-weight:800; margin-top:14px;"><?php echo esc_html( $service['title'] ); ?></div>
                                    <div style="font-size:11.5px; line-height:1.5; color:var(--muted); margin-top:5px;"><?php echo esc_html( $service['description'] ); ?></div>
                                    <?php if ( ! $service_available && $service['reason'] !== '' ): ?><div style="font-size:10.5px; line-height:1.4; color:var(--rev); margin-top:6px;"><?php echo esc_html( $service['reason'] ); ?></div><?php endif; ?>
                                    <div class="vip-service-go"><?php echo esc_html( $service_action ); ?> <span class="ms" style="font-size:16px;">arrow_forward</span></div>
                                </button>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="card vip-security-card">
                    <div class="vip-section-head">
                        <span class="ms vip-section-icon info">security</span>
                        <div class="vip-section-copy"><div class="vip-section-title">Centro de segurança</div><div class="vip-section-subtitle">Controla os telemóveis que mantêm uma sessão ativa na App 1MZ.</div></div>
                        <div class="vip-security-head-actions">
                            <span class="vip-security-count"><span class="ms">devices</span><?php echo (int) count( $app_sessions ); ?> <?php echo count( $app_sessions ) === 1 ? 'sessão móvel' : 'sessões móveis'; ?></span>
                            <?php if ( count( $app_sessions ) > 1 ): ?>
                                <form method="post" action="<?php echo esc_url( $post_url ); ?>" data-vip-confirm-submit="Terminar todas as sessões da App? Terás de iniciar sessão novamente em cada telemóvel.">
                                    <input type="hidden" name="action" value="rmbz_vip_revoke_all_app_sessions">
                                    <?php wp_nonce_field( 'rmbz_vip_revoke_all_sessions' ); ?>
                                    <button type="submit" class="pill vip-security-all"><span class="ms">logout</span> Terminar todas</button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php if ( in_array( (string) ( $_GET['saved'] ?? '' ), [ 'session', 'sessions' ], true ) ): ?><div class="vip-security-success"><span class="ms">check_circle</span>Sessões atualizadas com sucesso.</div><?php endif; ?>
                    <?php if ( empty( $app_sessions ) ): ?>
                        <div class="vip-security-empty"><span class="ms">phonelink_off</span><span>Não há sessões móveis ativas. A sessão deste site é independente.</span></div>
                    <?php else: ?>
                        <div class="vip-session-list">
                            <?php foreach ( $app_sessions as $session ):
                                $session_label = trim( (string) ( $session->device_label ?? '' ) );
                                if ( $session_label === '' ) $session_label = 'Dispositivo móvel';
                                $session_seen = ! empty( $session->last_used_at ) ? get_date_from_gmt( (string) $session->last_used_at ) : get_date_from_gmt( (string) $session->created_at );
                            ?>
                                <div class="vip-session">
                                    <span class="ms vip-session-icon">smartphone</span>
                                    <div class="vip-session-copy"><div class="vip-session-name"><?php echo esc_html( $session_label ); ?></div><div class="vip-session-meta">Última atividade em <?php echo esc_html( date_i18n( 'd/m/Y H:i', strtotime( $session_seen ) ) ); ?><?php echo ! empty( $session->ip_address ) ? ' · IP ' . esc_html( $session->ip_address ) : ''; ?></div></div>
                                    <span class="vip-session-state">Ativa</span>
                                    <form method="post" action="<?php echo esc_url( $post_url ); ?>" data-vip-confirm-submit="Terminar esta sessão da App?">
                                        <input type="hidden" name="action" value="rmbz_vip_revoke_app_session">
                                        <input type="hidden" name="session_id" value="<?php echo (int) $session->id; ?>">
                                        <?php wp_nonce_field( 'rmbz_vip_revoke_session' ); ?>
                                        <button type="submit" class="pill vip-session-end">Terminar</button>
                                    </form>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                    <div class="vip-security-note"><span class="ms">info</span><span>Terminar uma sessão revoga o acesso à App imediatamente. Os teus dados e esta sessão no navegador não são apagados.</span></div>
                </div>

                <?php // ═══ [1.5.415] RENOVAR / COMPRAR VIP (pacotes reais do antigo) ═══ ?>
                <div class="card vip-packages-card" id="rmbz-vip-packages">
                    <div class="vip-section-head">
                        <span class="ms vip-section-icon">workspace_premium</span>
                        <div class="vip-section-copy"><div class="vip-section-title"><?php echo $has_subscription ? 'Renovar ou mudar de plano' : 'Escolher um plano VIP'; ?></div><div class="vip-section-subtitle">Compara os serviços, escolhe a duração e ativa diretamente com o saldo da carteira.</div></div>
                        <span class="vip-packages-wallet"><span class="ms">account_balance_wallet</span>Saldo: <?php echo esc_html( $fmt( $saldo_total ) ); ?> MT</span>
                    </div>
                    <p class="vip-packages-intro"><?php echo $has_subscription ? 'O teu ' . esc_html( $vip_plan_name ) . ' está ativo até ' . esc_html( $vip_data ) . '. Mostramos apenas a renovação atual e upgrades que mantêm todos os teus serviços.' : 'Sem uma subscrição ativa, os serviços VIP permanecem suspensos. Escolhe o pacote que corresponde ao teu trabalho.'; ?></p>
                    <?php
                    $vip_package_max_services = 0;
                    foreach ( $vip_change_packages as $vip_package_candidate ) {
                        $vip_candidate_perms = isset( $vip_package_candidate['perms'] ) && is_array( $vip_package_candidate['perms'] ) ? $vip_package_candidate['perms'] : [];
                        $vip_candidate_services = array_intersect_key( $vip_candidate_perms, array_flip( $vip_package_service_keys ) );
                        $vip_package_max_services = max( $vip_package_max_services, count( array_filter( $vip_candidate_services ) ) );
                    }
                    $vip_complete_badge_used = false;
                    ?>
                    <?php if ( empty( $vip_change_packages ) ): ?>
                        <div class="vip-package-empty"><span class="ms">verified</span><div><strong>Já tens o plano mais completo disponível</strong><small>Não existe neste momento outro pacote que mantenha todos os teus serviços. Contacta o suporte para uma configuração personalizada.</small></div></div>
                    <?php else: ?>
                    <div class="vip-packages-grid" id="rmbz-vip-packages-grid">
                        <?php foreach ( $vip_change_packages as $pk_i => $pk ):
                            $pk_perms = ( isset( $pk['perms'] ) && is_array( $pk['perms'] ) ) ? $pk['perms'] : [];
                            $pk_durs  = function_exists( 'rmbz_vip_package_duration_options' ) ? rmbz_vip_package_duration_options( $pk ) : [];
                            $pk_ai    = ! empty( $pk['ai_offered'] );
                            $pk_ai_pr = isset( $pk['ai_price'] ) ? (float) $pk['ai_price'] : 0.0;
                            $pk_name  = trim( (string) ( $pk['nome'] ?? 'Pacote VIP' ) );
                            $pk_service_count = count( array_filter( array_intersect_key( $pk_perms, array_flip( $vip_package_service_keys ) ) ) );
                            $pk_is_current = ! empty( $pk['_vip_is_current'] );
                            $pk_added_services = (int) ( $pk['_vip_added_services'] ?? 0 );
                            $pk_ai_required = ! empty( $pk['_vip_ai_required'] );
                            $pk_badge = '';
                            $pk_badge_class = '';
                            if ( $pk_is_current ) {
                                $pk_badge = 'Plano atual';
                                $pk_badge_class = ' current';
                            } elseif ( $pk_added_services > 0 ) {
                                $pk_badge = 'Upgrade +' . $pk_added_services;
                            } elseif ( ! empty( $pk['popular'] ) ) {
                                $pk_badge = 'Mais escolhido';
                            } elseif ( ! $vip_complete_badge_used && $pk_service_count === $vip_package_max_services && $vip_package_max_services > 0 ) {
                                $pk_badge = 'Mais completo';
                                $vip_complete_badge_used = true;
                            }
                            $perm_lbl = [
                                'site'       => [ 'language', 'Músicas no site' ],
                                'social'     => [ 'campaign', 'Promoção nas redes' ],
                                'distribute' => [ 'public', 'Distribuição digital' ],
                                'video'      => [ 'movie', 'Candidatura a videoclipe' ],
                            ];
                        ?>
                            <div class="vip-package<?php echo ( ! empty( $pk['popular'] ) || $pk_added_services > 0 ) ? ' is-featured' : ''; ?><?php echo $pk_is_current ? ' is-current' : ''; ?>">
                                <div class="vip-package-head">
                                    <span class="ms vip-package-icon">workspace_premium</span>
                                    <div><div class="vip-package-name"><?php echo esc_html( $pk_name ); ?></div><div class="vip-package-count"><?php echo (int) $pk_service_count; ?> de 4 serviços principais</div></div>
                                    <?php if ( $pk_badge !== '' ): ?><span class="vip-package-badge<?php echo esc_attr( $pk_badge_class ); ?>"><?php echo esc_html( $pk_badge ); ?></span><?php endif; ?>
                                </div>
                                <div class="mono vip-package-price rmbz-vip-pk-price" data-base="<?php echo esc_attr( (float) ( $pk['preco'] ?? 0 ) ); ?>"><?php echo esc_html( $fmt( (float) ( $pk['preco'] ?? 0 ) ) ); ?> MT</div>
                                <div class="vip-package-days rmbz-vip-pk-days"><span class="ms">calendar_month</span><?php echo (int) ( $pk['dias'] ?? 30 ); ?> dias de acesso</div>
                                <div class="vip-package-services">
                                    <?php foreach ( $perm_lbl as $pkk => $pk_service ): $pk_included = ! empty( $pk_perms[ $pkk ] ); ?>
                                        <div class="vip-package-service<?php echo $pk_included ? '' : ' not-included'; ?>"><span class="ms"><?php echo $pk_included ? 'check_circle' : 'remove'; ?></span><span><?php echo esc_html( $pk_service[1] ); ?></span></div>
                                    <?php endforeach; ?>
                                </div>
                                <form method="post" action="<?php echo esc_url( $post_url ); ?>" class="rmbz-vip-pk-form">
                                    <input type="hidden" name="action" value="rmbz_buy_vip_package">
                                    <input type="hidden" name="package_id" value="<?php echo esc_attr( $pk['id'] ?? $pk_i ); ?>">
                                    <?php wp_nonce_field( 'rmbz_buy_package_nonce' ); ?>
                                    <?php if ( ! empty( $pk_durs ) ): ?>
                                        <label class="vip-package-field-label">Duração do acesso</label>
                                        <select class="inp vip-package-select rmbz-vip-pk-months" name="months">
                                            <?php foreach ( $pk_durs as $du ): ?>
                                                <option value="<?php echo (int) $du['months']; ?>"
                                                        data-price="<?php echo esc_attr( $du['price'] ); ?>"
                                                        data-price-ai="<?php echo esc_attr( $du['price_with_ai'] ); ?>"
                                                        data-days="<?php echo (int) $du['days']; ?>">
                                                    <?php echo esc_html( $du['label'] ); ?><?php echo $du['discount_pct'] > 0 ? ' · -' . (int) $du['discount_pct'] . '%' : ''; ?> — <?php echo esc_html( $fmt( (float) $du['price'] ) ); ?> MT
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    <?php endif; ?>
                                    <?php if ( $pk_ai ): ?>
                                        <label class="vip-package-addon">
                                            <?php if ( $pk_ai_required ): ?>
                                                <input type="hidden" name="include_ai" value="1">
                                                <input type="checkbox" class="rmbz-vip-pk-ai" value="1" checked disabled>
                                            <?php else: ?>
                                                <input type="checkbox" class="rmbz-vip-pk-ai" name="include_ai" value="1">
                                            <?php endif; ?>
                                            <span class="ms vip-package-addon-icon">psychology</span>
                                            <span><strong>Assistente de IA 1MZ</strong><small><?php echo $pk_ai_required ? 'Mantido para não reduzir o teu plano' : 'Adicionar por +' . esc_html( $fmt( $pk_ai_pr ) ) . ' MT/mês'; ?></small></span>
                                        </label>
                                    <?php endif; ?>
                                    <button type="submit" class="pill vip-package-submit" data-vip-confirm-click="Confirmar a compra deste plano com o saldo da carteira?"><span class="ms">account_balance_wallet</span><?php echo $pk_is_current ? 'Renovar com o saldo' : 'Ativar upgrade'; ?></button>
                                </form>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </section>
        </div>
    </main>

    <!-- MODAL DE RENOVAÇÃO / UPGRADE VIP -->
    <div class="scrim" id="rmbz-vip-plan-scrim" aria-hidden="true">
        <div class="dialog vip-plan-dialog" role="dialog" aria-modal="true" aria-labelledby="rmbz-vip-plan-title">
            <div class="vip-plan-modal-head">
                <span class="ms vip-plan-modal-icon">workspace_premium</span>
                <div class="vip-plan-modal-copy">
                    <div class="vip-plan-modal-title" id="rmbz-vip-plan-title"><?php echo $has_subscription ? 'Renovar ou melhorar o teu VIP' : 'Escolher um plano VIP'; ?></div>
                    <div class="vip-plan-modal-subtitle"><?php echo $has_subscription ? 'Plano atual: ' . esc_html( $vip_plan_name ) . ' · válido até ' . esc_html( $vip_data ) : 'Escolhe os serviços e a duração que precisas.'; ?></div>
                </div>
                <span class="vip-plan-modal-wallet"><span class="ms">account_balance_wallet</span><?php echo esc_html( $fmt( $saldo_total ) ); ?> MT</span>
                <button type="button" class="vip-plan-modal-close" id="rmbz-vip-plan-close" aria-label="Fechar"><span class="ms">close</span></button>
            </div>
            <?php if ( $has_subscription ): ?>
                <div class="vip-plan-modal-note"><span class="ms">verified_user</span><span>Proteção contra downgrade ativa: aparecem apenas o teu plano atual e upgrades que mantêm todos os serviços já contratados.</span></div>
            <?php endif; ?>
            <div class="vip-plan-modal-body" id="rmbz-vip-plan-modal-body"></div>
        </div>
    </div>

    <!-- DIALOG LEVANTAMENTO (3 passos) -->
    <div class="scrim" id="rmbz-vip-wd-scrim" data-screen-label="Levantamento">
        <div class="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(--brand-ink); letter-spacing:.08em;" id="rmbz-vip-wd-lbl">PASSO 1 DE 3 — VALOR</div>
                <button type="button" class="rmbz-vip-wd-x" style="border:none; background:none; color:var(--muted); cursor:pointer; display:flex;"><span class="ms" style="font-size:22px;">close</span></button>
            </div>
            <?php /* [1.5.415] BUGFIX: os nomes dos campos estavam errados (source/
                  payment_method/payment_details) — o handler lê rmbz_withdrawal_source/
                  rmbz_payment_method/rmbz_payment_details e o pedido chegava vazio. */ ?>
            <?php // [1.5.454] Estados do ANTIGO: bloqueado e pedido pendente
                  // travam ANTES de preencher (o servidor rejeitaria na mesma). ?>
            <?php if ( $wd_blocked ): ?>
                <div style="border-radius:14px; padding:14px 16px; background:var(--danger-soft); color:var(--danger); font-size:12.5px; font-weight:650;"><?php echo esc_html( $wd_block_message ); ?></div>
            <?php elseif ( $has_pending_wd ): ?>
                <div style="border-radius:14px; padding:14px 16px; background:var(--rev-soft); color:var(--rev); font-size:12.5px; font-weight:650;">Já tens um pedido de levantamento pendente. Aguarda o processamento (até 24 horas úteis) antes de pedires outro.</div>
            <?php elseif ( ! $wallet_eligible && ! $royalties_eligible ): ?>
                <div style="border-radius:18px; padding:18px; background:var(--rev-soft); border:1px solid var(--rev);">
                    <div style="display:flex; gap:10px; align-items:center; color:var(--rev); font-weight:800;"><span class="ms">account_balance_wallet</span> Saldo abaixo do mínimo</div>
                    <p style="font-size:12.5px; line-height:1.6; color:var(--text2); margin:8px 0 0;">Carteira: <b><?php echo esc_html( $fmt( $retiravel ) ); ?> MT</b> · Royalties: <b>$ <?php echo esc_html( number_format( $roy_usd, 2, ',', '.' ) ); ?></b>. Precisas de pelo menos <?php echo esc_html( $fmt( $min_wd ) ); ?> MT ou $ <?php echo esc_html( number_format( $min_wd_usd, 2, ',', '.' ) ); ?> USD.</p>
                </div>
            <?php else: ?>
            <?php $wd_default_source = $wallet_eligible ? 'wallet' : 'royalties'; ?>
            <form method="post" action="<?php echo esc_url( $post_url ); ?>" id="rmbz-vip-wd-form">
                <input type="hidden" name="action" value="rmbz_request_withdrawal">
                <input type="hidden" name="rmbz_withdrawal_source" id="rmbz-vip-wd-source" value="<?php echo esc_attr( $wd_default_source ); ?>">
                <?php wp_nonce_field( 'rmbz_withdrawal_nonce' ); ?>
                <input type="hidden" name="rmbz_payment_method" id="rmbz-vip-wd-method" value="M-Pesa">
                <input type="hidden" name="rmbz_payment_details" id="rmbz-vip-wd-details" value="">

                <div class="wstep on" data-wstep="1">
                    <h2 style="margin:0 0 4px; font-family:'Bricolage Grotesque',sans-serif; font-size:22px; font-weight:700;">Quanto queres levantar?</h2>
                    <p style="margin:2px 0 0; font-size:12.5px; color:var(--muted);">Escolhe de onde o valor será retirado.</p>
                    <div class="wd-source-grid">
                        <button type="button" class="wd-source rmbz-vip-wd-src<?php echo $wd_default_source === 'wallet' ? ' on' : ''; ?>" data-src="wallet" <?php disabled( ! $wallet_eligible ); ?>>
                            <span class="ms wd-source-icon">account_balance_wallet</span><span style="flex:1;"><span style="display:block; font-size:12.5px; font-weight:800;">Carteira em Metical</span><span class="mono" style="display:block; font-size:14px; margin-top:3px;"><?php echo esc_html( $fmt( $retiravel ) ); ?> MT</span><span style="display:block; font-size:10px; color:var(--<?php echo $wallet_eligible ? 'success' : 'muted'; ?>); margin-top:2px;"><?php echo $wallet_eligible ? 'Disponível para levantar' : 'Abaixo do mínimo'; ?></span></span>
                        </button>
                        <button type="button" class="wd-source rmbz-vip-wd-src<?php echo $wd_default_source === 'royalties' ? ' on' : ''; ?>" data-src="royalties" <?php disabled( ! $royalties_eligible ); ?>>
                            <span class="ms wd-source-icon">music_note</span><span style="flex:1;"><span style="display:block; font-size:12.5px; font-weight:800;">Royalties em USD</span><span class="mono" style="display:block; font-size:14px; margin-top:3px;">$ <?php echo esc_html( number_format( $roy_usd, 2, ',', '.' ) ); ?></span><span style="display:block; font-size:10px; color:var(--<?php echo $royalties_eligible ? 'success' : 'muted'; ?>); margin-top:2px;"><?php echo $royalties_eligible ? 'Convertido para MT ao levantar' : 'Abaixo do mínimo'; ?></span></span>
                        </button>
                    </div>
                    <p style="margin:0 0 10px; font-size:12.5px; color:var(--muted);" id="rmbz-vip-wd-hint"><?php echo $wd_default_source === 'wallet' ? 'Saldo retirável: <b>' . esc_html( $fmt( $retiravel ) ) . ' MT</b> · mínimo ' . esc_html( $fmt( $min_wd ) ) . ' MT' : 'Royalties: <b>$ ' . esc_html( number_format( $roy_usd, 2, '.', '' ) ) . '</b> · mínimo $ ' . esc_html( number_format( $min_wd_usd, 2, '.', '' ) ) . ' USD'; ?></p>
                    <div style="display:flex; align-items:baseline; gap:8px; background:var(--elev); border:1px solid var(--border2); border-radius:18px; padding:15px 20px;">
                        <input name="<?php echo $wd_default_source === 'wallet' ? 'rmbz_withdrawal_amount' : 'rmbz_withdrawal_amount_usd'; ?>" id="rmbz-vip-wd-amount" type="number" min="0" step="0.01" placeholder="0" inputmode="decimal" autocomplete="off" style="flex:1; border:none; background:none; outline:none; font-family:'JetBrains Mono',monospace; font-size:28px; font-weight:600; color:var(--text); min-width:0; width:100%;">
                        <span id="rmbz-vip-wd-unit" style="font-size:15px; font-weight:750; color:var(--muted);"><?php echo $wd_default_source === 'wallet' ? 'MT' : 'USD'; ?></span>
                    </div>
                    <div id="rmbz-vip-wd-conversion" style="display:<?php echo $wd_default_source === 'royalties' ? 'block' : 'none'; ?>; margin-top:8px; border-radius:12px; padding:9px 12px; background:var(--info-soft); color:var(--info); font-size:11.5px;">Conversão estimada: <b id="rmbz-vip-wd-conversion-value">0,00 MT</b> ao câmbio atual.</div>
                    <div style="display:flex; gap:8px; margin-top:12px; flex-wrap:wrap;" id="rmbz-vip-wd-chips"></div>
                    <div id="rmbz-vip-wd-err" style="display:none; margin-top:12px; font-size:12.5px; font-weight:650; color:var(--danger);"></div>
                    <button type="button" class="pill rmbz-vip-wd-next" data-to="2" style="width:100%; justify-content:center; margin-top:20px; background:var(--brand); color:var(--on-brand); padding:15px;">Continuar</button>
                </div>

                <div class="wstep" data-wstep="2">
                    <h2 style="margin:0 0 4px; font-family:'Bricolage Grotesque',sans-serif; font-size:22px; font-weight:700;">Para onde enviamos?</h2>
                    <p style="margin:0 0 16px; font-size:12.5px; color:var(--muted);">Escolhe a carteira móvel para receber.</p>
                    <button type="button" class="met on" data-method="M-Pesa"><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;">M-P</span><span style="flex:1;"><span style="display:block; font-size:15px; font-weight:750; color:var(--text);">M-Pesa</span><span style="display:block; font-size:11.5px; color:var(--muted);">Vodacom · 84 / 85</span></span><span class="ms metchk" style="font-size:22px; color:var(--brand-ink); font-variation-settings:'FILL' 1;">check_circle</span></button>
                    <button type="button" class="met" data-method="E-Mola"><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;">eM</span><span style="flex:1;"><span style="display:block; font-size:15px; font-weight:750; color:var(--text);">eMola</span><span style="display:block; font-size:11.5px; color:var(--muted);">Movitel · 86 / 87</span></span><span class="ms metchk" style="font-size:22px; color:var(--border2);">radio_button_unchecked</span></button>
                    <?php if ( ! empty( $saved_payouts ) ): ?>
                        <div style="font-size:10.5px; font-weight:800; color:var(--muted); letter-spacing:.06em; margin:14px 0 7px;">CONTACTOS USADOS ANTES</div>
                        <div style="display:flex; gap:7px; flex-wrap:wrap;">
                            <?php foreach ( $saved_payouts as $payout ):
                                $payout_method = sanitize_text_field( (string) ( $payout['method'] ?? '' ) );
                                $payout_number = preg_replace( '/\D+/', '', (string) ( $payout['number'] ?? '' ) );
                                if ( $payout_method === '' || strlen( $payout_number ) !== 9 ) continue;
                            ?><button type="button" class="wd-contact" data-method="<?php echo esc_attr( $payout_method ); ?>" data-number="<?php echo esc_attr( $payout_number ); ?>"><span class="ms" style="font-size:16px;">history</span><?php echo esc_html( $payout_method . ' · ' . $payout_number ); ?></button><?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                    <div style="font-size:11px; font-weight:750; color:var(--muted); letter-spacing:.06em; margin:14px 0 6px;">NÚMERO DA CARTEIRA</div>
                    <div style="display:flex; align-items:center; gap:10px; background:var(--elev); border:1px solid var(--border2); border-radius:16px; padding:12px 17px;"><span style="font-size:13.5px; font-weight:700; color:var(--muted);">+258</span><input id="rmbz-vip-wd-phone" inputmode="numeric" maxlength="9" value="<?php echo esc_attr( $tel9 ); ?>" style="flex:1; border:none; background:none; outline:none; font-family:'JetBrains Mono',monospace; font-size:16px; font-weight:600; color:var(--text); min-width:0;"></div>
                    <div id="rmbz-vip-wd-err2" style="display:none; margin-top:12px; font-size:12.5px; font-weight:650; color:var(--danger);"></div>
                    <div style="display:flex; gap:10px; margin-top:20px;"><button type="button" class="pill rmbz-vip-wd-back" data-to="1" style="border:1px solid var(--border); background:none; color:var(--brand-ink);">Voltar</button><button type="button" class="pill rmbz-vip-wd-next" data-to="3" style="flex:1; justify-content:center; background:var(--brand); color:var(--on-brand);">Rever pedido</button></div>
                </div>

                <div class="wstep" data-wstep="3">
                    <h2 style="margin:0 0 16px; font-family:'Bricolage Grotesque',sans-serif; font-size:22px; font-weight:700;">Confirma o levantamento</h2>
                    <div style="background:var(--elev); border:1px solid var(--border); border-radius:18px; padding:6px 18px;">
                        <div style="display:flex; justify-content:space-between; padding:12px 0; border-bottom:1px solid var(--border); font-size:13px;"><span style="color:var(--muted);">Origem</span><span style="font-weight:650;" id="rmbz-vip-sum-source">—</span></div>
                        <div style="display:flex; justify-content:space-between; padding:12px 0; border-bottom:1px solid var(--border); font-size:13px;"><span style="color:var(--muted);">Valor</span><span class="mono" style="font-weight:600;" id="rmbz-vip-sum-amt">—</span></div>
                        <div style="display:flex; justify-content:space-between; padding:12px 0; border-bottom:1px solid var(--border); font-size:13px;"><span style="color:var(--muted);">Carteira</span><span style="font-weight:650;" id="rmbz-vip-sum-met">—</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(--success);" id="rmbz-vip-sum-amt2">—</span></div>
                    </div>
                    <p style="margin:12px 2px 0; font-size:11.5px; color:var(--muted);">O pedido é processado pela 1MZ Records em até 24 horas úteis.</p>
                    <div style="display:flex; gap:10px; margin-top:18px;"><button type="button" class="pill rmbz-vip-wd-back" data-to="2" style="border:1px solid var(--border); background:none; color:var(--brand-ink);">Voltar</button><button type="submit" class="pill" style="flex:1; justify-content:center; background:var(--brand); color:var(--on-brand);">Confirmar levantamento</button></div>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>

    <!-- VISUALIZADOR FULLSCREEN DE COMPROVATIVOS -->
    <div class="scrim deposit-proof-viewer" id="rmbz-vip-proof-viewer" aria-hidden="true">
        <div class="dialog deposit-proof-dialog">
            <div class="deposit-proof-toolbar">
                <span class="ms deposit-proof-toolbar-icon" aria-hidden="true">receipt_long</span>
                <div class="deposit-proof-toolbar-copy">
                    <h2 class="deposit-proof-title" data-proof-title>Comprovativo do depósito</h2>
                    <div class="deposit-proof-subtitle">Visualização em ecrã inteiro</div>
                </div>
                <a class="deposit-proof-original" data-proof-original href="#" target="_blank" rel="noopener"><span class="ms" aria-hidden="true">open_in_new</span><span>Abrir original</span></a>
                <button type="button" class="rmbz-vip-dclose deposit-proof-close" aria-label="Fechar comprovativo"><span class="ms" aria-hidden="true">close</span></button>
            </div>
            <div class="deposit-proof-stage" data-proof-stage>
                <img class="deposit-proof-full" data-proof-full alt="Comprovativo do depósito">
            </div>
        </div>
    </div>

    <!-- DIALOG DEPÓSITO (form REAL — mesmo handler do antigo) -->
    <div class="scrim" id="rmbz-vip-dep-scrim" data-screen-label="Depósito">
        <div class="dialog" style="width:460px;">
            <div style="display:flex; align-items:center; justify-content:space-between;"><h2 style="margin:0; font-family:'Bricolage Grotesque',sans-serif; font-size:21px; font-weight:700;">Depositar na carteira</h2><button type="button" class="rmbz-vip-dep-x" style="border:none; background:none; color:var(--muted); cursor:pointer; display:flex;"><span class="ms" style="font-size:22px;">close</span></button></div>
            <?php if ( $has_pending_deposit ): ?>
                <div style="margin-top:14px; border-radius:14px; padding:12px 16px; background:var(--rev-soft); color:var(--rev); font-size:12.5px; font-weight:650;">⏳ Já tens um depósito pendente — aguarda a aprovação antes de enviar outro.</div>
            <?php elseif ( $dep_blocked ): ?>
                <div style="margin-top:14px; border-radius:14px; padding:12px 16px; background:var(--danger-soft); color:var(--danger); font-size:12.5px; font-weight:650;"><?php echo esc_html( $dep_block_message ); ?></div>
            <?php else: ?>
                <p style="margin:8px 0 14px; font-size:12.5px; color:var(--muted); line-height:1.55;">1) Transfere para uma das contas 1MZ · 2) preenche os dados e envia o comprovativo — o saldo entra após aprovação.</p>
                <div style="background:var(--elev); border:1px solid var(--border); border-radius:16px; padding:12px 16px; margin-bottom:8px; display:flex; align-items:center; gap:13px;"><span style="width:38px; height:38px; border-radius:10px; background:#E60000; color:#fff; display:flex; align-items:center; justify-content:center; font-weight:800; font-size:11px;">M-P</span><div><div style="font-size:13px; font-weight:700;">M-Pesa · <?php echo esc_html( $dep_mpesa ); ?></div><div style="font-size:11px; color:var(--muted);"><?php echo esc_html( $dep_mpesa_name ); ?></div></div></div>
                <div style="background:var(--elev); border:1px solid var(--border); border-radius:16px; padding:12px 16px; display:flex; align-items:center; gap:13px;"><span style="width:38px; height:38px; border-radius:10px; background:#F26522; color:#fff; display:flex; align-items:center; justify-content:center; font-weight:800; font-size:11px;">eM</span><div><div style="font-size:13px; font-weight:700;">eMola · <?php echo esc_html( $dep_emola ); ?></div><div style="font-size:11px; color:var(--muted);"><?php echo esc_html( $dep_emola_name ); ?></div></div></div>

                <form method="post" action="<?php echo esc_url( $post_url ); ?>" enctype="multipart/form-data" style="margin-top:16px;">
                    <input type="hidden" name="action" value="rmbz_processar_deposito">
                    <?php wp_nonce_field( 'rmbz_deposit_nonce', '_rmbz_deposit_nonce' ); ?>
                    <label style="display:block; font-size:11px; font-weight:750; color:var(--muted); letter-spacing:.05em; margin-bottom:4px;">VALOR TRANSFERIDO (MT)</label>
                    <input class="inp mono" type="number" name="deposit_amount" min="1" max="50000" step="0.01" required placeholder="0,00">
                    <label style="display:block; font-size:11px; font-weight:750; color:var(--muted); letter-spacing:.05em; margin:12px 0 4px;">MÉTODO USADO</label>
                    <div style="display:flex; gap:8px;">
                        <label class="chip" style="flex:1; text-align:center; cursor:pointer;"><input type="radio" name="payment_method" value="M-Pesa" checked style="margin-right:6px;">M-Pesa</label>
                        <label class="chip" style="flex:1; text-align:center; cursor:pointer;"><input type="radio" name="payment_method" value="E-Mola" style="margin-right:6px;">eMola</label>
                    </div>
                    <label style="display:block; font-size:11px; font-weight:750; color:var(--muted); letter-spacing:.05em; margin:12px 0 4px;">NÚMERO QUE ENVIOU (9 dígitos)</label>
                    <input class="inp mono" type="tel" name="sender_phone" pattern="8[4-7][0-9]{7}" maxlength="9" required placeholder="8XXXXXXXX" value="<?php echo esc_attr( $tel9 ); ?>">
                    <label style="display:block; font-size:11px; font-weight:750; color:var(--muted); letter-spacing:.05em; margin:12px 0 4px;">COMPROVATIVO</label>
                    <div style="display:flex; gap:8px; margin-bottom:8px;">
                        <label class="chip" style="flex:1; text-align:center; cursor:pointer;"><input type="radio" name="proof_type" value="id" checked class="rmbz-vip-dep-pt" style="margin-right:6px;">ID da transação</label>
                        <label class="chip" style="flex:1; text-align:center; cursor:pointer;"><input type="radio" name="proof_type" value="image" class="rmbz-vip-dep-pt" style="margin-right:6px;">Imagem (print)</label>
                    </div>
                    <input class="inp mono" type="text" name="transaction_id" id="rmbz-vip-dep-txid" placeholder="Ex.: CGxxxxxxx">
                    <input class="inp" type="file" name="proof_image" id="rmbz-vip-dep-img" accept="image/*" style="display:none;">
                    <button type="submit" class="pill" style="margin-top:16px; width:100%; justify-content:center; background:var(--brand); color:var(--on-brand);">Enviar depósito para aprovação</button>
                </form>
            <?php endif; ?>
        </div>
    </div>

    <!-- DIALOG MULTA (pagar com PIN — mesmo handler do antigo) -->
    <div class="scrim" id="rmbz-vip-fine-scrim" data-screen-label="Multa">
        <?php $fine_dialog_amount = max( 0, (float) ( $fine['amount'] ?? 0 ) ); ?>
        <div class="dialog fine-pay-dialog">
            <div class="fine-pay-head">
                <span class="ms fine-pay-head-icon" aria-hidden="true">account_balance_wallet</span>
                <div class="fine-pay-head-copy">
                    <div class="fine-pay-kicker">Regularização do projeto</div>
                    <div class="fine-pay-title">Pagar dívida da produção</div>
                </div>
                <button type="button" class="rmbz-vip-dclose fine-pay-close" aria-label="Fechar"><span class="ms">close</span></button>
            </div>
            <div class="fine-pay-summary">
                <div class="fine-pay-summary-label">Total a debitar</div>
                <div class="fine-pay-summary-value"><?php echo esc_html( $fmt( $fine_dialog_amount ) ); ?> <small>MT</small></div>
                <div class="fine-pay-wallet"><span><span class="ms">wallet</span>Saldo disponível</span><b><?php echo esc_html( $fmt( $saldo_total ) ); ?> MT</b></div>
            </div>
            <p class="fine-pay-note">O pagamento será retirado da carteira e associado automaticamente ao projeto. Confirma a operação com o teu PIN.</p>
            <?php if ( $fine_dialog_amount > $saldo_total ): ?>
                <div class="fine-pay-balance-warning"><span class="ms">info</span><span>O saldo atual não cobre o valor total. Faz primeiro um depósito na carteira para concluir o pagamento.</span></div>
            <?php endif; ?>
            <form method="post" action="<?php echo esc_url( $post_url ); ?>">
                <input type="hidden" name="action" value="rmbz_pay_project_fine">
                <?php wp_nonce_field( 'rmbz_pay_fine_nonce' ); ?>
                <label class="fine-pay-label" for="rmbz-vip-fine-pin">PIN da carteira</label>
                <input class="inp mono" id="rmbz-vip-fine-pin" type="password" name="pin" inputmode="numeric" maxlength="8" required placeholder="Introduz o PIN" style="text-align:center; letter-spacing:5px;">
                <button type="submit" class="pill fine-pay-submit"><span class="ms">lock_open</span>Confirmar pagamento</button>
            </form>
        </div>
    </div>

    <!-- DIALOG REGRAS DO PROJETO (pendente) -->
    <div class="scrim" id="rmbz-vip-rules-scrim" data-screen-label="Regras">
        <div class="dialog" style="width:520px;">
            <div style="display:flex; align-items:center; justify-content:space-between;"><h2 style="margin:0; font-family:'Bricolage Grotesque',sans-serif; font-size:19px; font-weight:700;">📜 Regras do Projeto de Vídeo</h2><button type="button" class="rmbz-vip-dclose" style="border:none; background:none; color:var(--muted); cursor:pointer; display:flex;"><span class="ms" style="font-size:22px;">close</span></button></div>
            <ol style="font-size:13px; color:var(--text2); line-height:1.7; padding-left:20px; margin:14px 0 0;">
                <li><b>Prazos de resposta</b> — quando a equipa te pede uma ação (escolher local, confirmar datas, assinar contrato), tens prazos definidos; sem resposta o projeto pode ser cancelado automaticamente.</li>
                <li><b>Subscrição ativa</b> — enquanto o videoclipe está em produção a subscrição tem de estar paga; se expirar, acumula multa por atraso.</li>
                <li><b>Contrato & identidade</b> — o pagamento e a gravação só avançam depois de assinares o contrato e a tua identidade ser validada.</li>
                <li><b>Comunicação</b> — todas as novidades chegam por notificação (email, sino e app); mantém o teu email válido.</li>
            </ol>
        </div>
    </div>
    </div>

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

        // [1.5.414] RE-PARENTAR para o <body>: o painel nasce dentro dos
        // wrappers do tema e qualquer ancestor com transform/filter cria um
        // stacking context que PRENDE o z-index lá dentro — o menu do tema
        // ficava por cima mesmo com z-index máximo. Direto no <body>, o
        // position:fixed volta a ser relativo ao viewport e ganha sempre.
        if (root.parentNode !== document.body) {
            document.body.appendChild(root);
        }

        // navegação
        var titles = {
            inicio:['Olá, <?php echo esc_js( $nome ); ?>','O teu estúdio 1MZ num só ecrã.'],
            musicas:['Músicas & Ganhos','Programa de parceria, catálogo, controlo e monetização.'],
            arttracks:['Art Tracks','As tuas músicas publicadas no site da 1MZ.'],
            projetos:['Videoclipes','Os teus projetos com a equipa 1MZ.'],
            distro:['Distribuição digital','Releases, streams e royalties.'],
            envios:['Envios','Músicas para o site e vídeos para as redes.'],
            financas:['Finanças','Depósitos, levantamentos e extrato.'],
            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 serverSect = <?php echo wp_json_encode( $vip_sect ); ?>;
        var accountUrl = <?php echo wp_json_encode( home_url( '/minha-conta/' ) ); ?>;
        function go(key) {
            if (key !== serverSect) {
                showSplash();
                location.href = accountUrl + '?sect=' + encodeURIComponent(key);
                return;
            }
            root.querySelectorAll('[data-nav]').forEach(function (b) { if (b.classList.contains('navbtn')) b.classList.toggle('on', b.getAttribute('data-nav') === key); });
            root.querySelectorAll('[data-sect]').forEach(function (s) { s.classList.toggle('on', s.getAttribute('data-sect') === key); });
            var t = titles[key]; if (t) { document.getElementById('rmbz-vip-title').textContent = t[0]; document.getElementById('rmbz-vip-sub').textContent = t[1]; }
            root.querySelector('.main').scrollTop = 0;
        }
        root.querySelectorAll('[data-nav]').forEach(function (b) { b.addEventListener('click', function () { go(b.getAttribute('data-nav')); }); });

        // tema
        var themeBtn = document.getElementById('rmbz-vip-theme');
        function applyTheme(t) {
            root.setAttribute('data-theme', t);
            themeBtn.querySelector('.ms').textContent = t === 'oled' ? 'light_mode' : 'dark_mode';
            themeBtn.querySelector('.lbl').textContent = t === 'oled' ? 'Tema claro' : 'Tema escuro';
        }
        var saved = 'oled';
        try { saved = localStorage.getItem('rmbz_vip_theme') || 'oled'; } catch (e) {}
        applyTheme(saved);
        themeBtn.addEventListener('click', function () {
            var t = root.getAttribute('data-theme') === 'oled' ? 'claro' : 'oled';
            applyTheme(t); try { localStorage.setItem('rmbz_vip_theme', t); } catch (e) {}
        });

        // ═══ [1.5.435] DIÁLOGOS M3 — substituem os alert()/confirm() do browser.
        // vipAlert(msg) → Promise<void> · vipConfirm(msg) → Promise<bool>.
        // Se a mensagem começar por emoji, ele vira o ícone do diálogo.
        var dlgScrim = document.getElementById('rmbz-vip-dlg');
        var dlgMsg = document.getElementById('rmbz-vip-dlg-msg');
        var dlgIco = document.getElementById('rmbz-vip-dlg-ico');
        var dlgOk = document.getElementById('rmbz-vip-dlg-ok');
        var dlgNo = document.getElementById('rmbz-vip-dlg-no');
        var dlgResolve = null;
        function vipDialog(msg, confirmMode){
            msg = String(msg || '');
            var ico = confirmMode ? '❓' : '💬';
            var lead = ['✅','⚠️','❌','💡','🚀','⏳','💸','📄','🎼','⚠'];
            for (var li = 0; li < lead.length; li++){
                if (msg.indexOf(lead[li]) === 0){ ico = lead[li]; msg = msg.slice(lead[li].length).replace(/^\s+/, ''); break; }
            }
            return new Promise(function (res) {
                dlgResolve = res;
                dlgMsg.textContent = msg;
                dlgIco.textContent = ico;
                dlgNo.style.display = confirmMode ? '' : 'none';
                dlgOk.textContent = confirmMode ? 'Confirmar' : 'OK';
                dlgScrim.classList.add('open');
            });
        }
        function dlgClose(v){ dlgScrim.classList.remove('open'); if (dlgResolve){ var r = dlgResolve; dlgResolve = null; r(v); } }
        dlgOk.addEventListener('click', function(){ dlgClose(true); });
        dlgNo.addEventListener('click', function(){ dlgClose(false); });
        dlgScrim.addEventListener('click', function(e){ if (e.target === dlgScrim) dlgClose(false); });
        function vipAlert(m){ return vipDialog(m, false); }
        function vipConfirm(m){ return vipDialog(m, true); }
        // [1.5.438] Diálogos auto-abertos (boas-vindas VIP / cupão): fechar.
        root.querySelectorAll('.rmbz-vip-autoclose').forEach(function(b){
            b.addEventListener('click', function(){ var s = b.closest('.scrim'); if (s) s.classList.remove('open'); });
        });
        // [1.5.443] Desistência: passo 2 (assinatura) + validação no tema.
        var rvguOpen2 = document.getElementById('rvgu-open2');
        if (rvguOpen2){
            var rvguS1 = document.getElementById('rvgu-s1'), rvguS2 = document.getElementById('rvgu-s2');
            rvguOpen2.addEventListener('click', function(){ rvguS1.style.display = 'none'; rvguS2.hidden = false; });
            document.getElementById('rvgu-back1').addEventListener('click', function(){ rvguS2.hidden = true; rvguS1.style.display = 'flex'; });
            var rvguForm = document.getElementById('rvgu-form');
            rvguForm.addEventListener('submit', function(e){
                var n = rvguForm.querySelector('[name="sign_name"]').value.trim();
                var telIn = rvguForm.querySelector('[name="sign_tel"]');
                // O +258 já está fixo à frente — o artista só põe o número dele.
                var t = telIn.value.replace(/\D+/g, '');
                if (t.indexOf('258') !== 0) t = '258' + t;
                if (n.length < 3){ e.preventDefault(); vipAlert('✍️ Escreve o teu nome completo (assinatura).'); return; }
                if (t !== rvguForm.getAttribute('data-acc')){ e.preventDefault(); vipAlert('❌ O número da conta não confere.'); return; }
                telIn.value = t; // envia o número completo (258…) ao servidor
            });
        }

        // [1.5.438] Projeto cancelado: "Compreendi" dispensa no servidor.
        var cnScrim = document.getElementById('rmbz-vip-cancel');
        if (cnScrim){
            document.getElementById('rmbz-vip-cancel-ok').addEventListener('click', function(){
                cnScrim.classList.remove('open');
                var fd = new FormData();
                fd.append('action','rmbz_dismiss_cancel_notice');
                fd.append('notice_id', cnScrim.getAttribute('data-nid') || '');
                fd.append('_nonce', cnScrim.getAttribute('data-nonce') || '');
                fetch(ajaxUrl, { method:'POST', body:fd, credentials:'same-origin' }).catch(function(){});
            });
        }
        // Forms com [data-vip-confirm]: intercepta o submit nativo, pergunta
        // no diálogo do tema e só então re-submete (requestSubmit refaz o
        // ciclo completo — o splash de navegação continua a funcionar).
        root.addEventListener('submit', function (e) {
            var f = e.target;
            if (!f || !f.hasAttribute || !f.hasAttribute('data-vip-confirm')) return;
            if (f.dataset.vipOk === '1'){ delete f.dataset.vipOk; return; }
            e.preventDefault(); e.stopImmediatePropagation();
            vipConfirm(f.getAttribute('data-vip-confirm')).then(function (ok) {
                if (!ok) return;
                f.dataset.vipOk = '1';
                if (f.requestSubmit) f.requestSubmit(); else f.submit();
            });
        }, true);
        // Botões com [data-vip-confirm-click] (ex.: submit de compra).
        root.addEventListener('click', function (e) {
            var b = e.target && e.target.closest ? e.target.closest('[data-vip-confirm-click]') : null;
            if (!b) return;
            if (b.dataset.vipOk === '1'){ delete b.dataset.vipOk; return; }
            e.preventDefault(); e.stopImmediatePropagation();
            vipConfirm(b.getAttribute('data-vip-confirm-click')).then(function (ok) {
                if (!ok) return;
                b.dataset.vipOk = '1';
                b.click();
            });
        }, true);

        // Renovação/upgrade VIP: abre os formulários reais num modal. Os
        // cartões são movidos (não clonados), preservando listeners e nonces.
        var vipPlanOpen = document.getElementById('rmbz-vip-plan-open');
        var vipPlanScrim = document.getElementById('rmbz-vip-plan-scrim');
        var vipPlanClose = document.getElementById('rmbz-vip-plan-close');
        var vipPlanBody = document.getElementById('rmbz-vip-plan-modal-body');
        var vipPlanContent = document.getElementById('rmbz-vip-packages-grid');
        if (!vipPlanContent) vipPlanContent = root.querySelector('#rmbz-vip-packages .vip-package-empty');
        var vipPlanHome = vipPlanContent ? vipPlanContent.parentNode : null;
        var vipPlanNext = vipPlanContent ? vipPlanContent.nextSibling : null;
        function openVipPlanModal(){
            if (!vipPlanScrim || !vipPlanBody || !vipPlanContent) return;
            vipPlanBody.appendChild(vipPlanContent);
            vipPlanScrim.classList.add('open');
            vipPlanScrim.setAttribute('aria-hidden', 'false');
            if (vipPlanClose) vipPlanClose.focus();
        }
        function closeVipPlanModal(){
            if (!vipPlanScrim) return;
            vipPlanScrim.classList.remove('open');
            vipPlanScrim.setAttribute('aria-hidden', 'true');
            if (vipPlanHome && vipPlanContent){
                if (vipPlanNext && vipPlanNext.parentNode === vipPlanHome) vipPlanHome.insertBefore(vipPlanContent, vipPlanNext);
                else vipPlanHome.appendChild(vipPlanContent);
            }
            if (vipPlanOpen) vipPlanOpen.focus();
        }
        if (vipPlanOpen) vipPlanOpen.addEventListener('click', openVipPlanModal);
        if (vipPlanClose) vipPlanClose.addEventListener('click', closeVipPlanModal);
        if (vipPlanScrim) vipPlanScrim.addEventListener('click', function(e){ if (e.target === vipPlanScrim) closeVipPlanModal(); });
        document.addEventListener('keydown', function(e){ if (e.key === 'Escape' && vipPlanScrim && vipPlanScrim.classList.contains('open')) closeVipPlanModal(); });

        // levantamento
        var saldo = <?php echo json_encode( round( $retiravel, 2 ) ); ?>;
        var minWd = <?php echo json_encode( $min_wd ); ?>;
        var roySaldo = <?php echo wp_json_encode( round( $roy_usd, 2 ) ); ?>;
        var cambio = <?php echo wp_json_encode( round( $cambio, 2 ) ); ?>;
        var minWdUsd = <?php echo wp_json_encode( $min_wd_usd ); ?>;
        var wdSrc = <?php echo wp_json_encode( isset( $wd_default_source ) ? $wd_default_source : 'wallet' ); ?>;
        var wdScrim = document.getElementById('rmbz-vip-wd-scrim');
        var amtIn = document.getElementById('rmbz-vip-wd-amount');
        var errEl = document.getElementById('rmbz-vip-wd-err');
        var phoneIn = document.getElementById('rmbz-vip-wd-phone');
        var methodIn = document.getElementById('rmbz-vip-wd-method');
        var detailsIn = document.getElementById('rmbz-vip-wd-details');
        var stepLbls = {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 fmtUsd(n){ return '$ ' + n.toLocaleString('pt-PT',{minimumFractionDigits:2,maximumFractionDigits:2}).replace(/[\u00A0\u202F]/g,' '); }
        function amount(){ var n = parseFloat(String(amtIn.value).replace(/\s/g,'').replace(',','.')); return isFinite(n)?n:0; }
        function wstep(n){
            wdScrim.querySelectorAll('.wstep').forEach(function(s){ s.classList.toggle('on', s.getAttribute('data-wstep')===String(n)); });
            document.getElementById('rmbz-vip-wd-lbl').textContent = stepLbls[n]||'';
            if (n===3){
                var a=amount(), royalty=wdSrc==='royalties';
                document.getElementById('rmbz-vip-sum-source').textContent=royalty?'Royalties em USD':'Carteira em MT';
                document.getElementById('rmbz-vip-sum-amt').textContent=royalty?fmtUsd(a):fmt(a);
                document.getElementById('rmbz-vip-sum-amt2').textContent=royalty?fmt(a*cambio):fmt(a);
                document.getElementById('rmbz-vip-sum-met').textContent=methodIn.value+' · +258 '+phoneIn.value;
            }
        }
        // [1.5.454] O form pode não existir (bloqueado / pedido pendente) —
        // o modal abre na mesma para mostrar o aviso, mas o resto é guardado.
        root.querySelectorAll('#rmbz-vip-wd,[data-wallet-action="withdraw"]').forEach(function(button){
            button.addEventListener('click', function(){ wdScrim.classList.add('open'); if (amtIn){ amtIn.value=''; errEl.style.display='none'; updateWdConversion(); wstep(1); } });
        });
        root.querySelectorAll('.rmbz-vip-wd-x').forEach(function(b){ b.addEventListener('click', function(){ wdScrim.classList.remove('open'); }); });
        wdScrim.addEventListener('click', function(e){ if(e.target===wdScrim) wdScrim.classList.remove('open'); });

        if (amtIn){
        var chipsWrap = document.getElementById('rmbz-vip-wd-chips');
        var addChip = function(label,v){ var b=document.createElement('button'); b.type='button'; b.className='chip'; b.textContent=label; b.addEventListener('click',function(){ amtIn.value=String(v); errEl.style.display='none'; updateWdConversion(); }); chipsWrap.appendChild(b); };
        function renderWdChips(){
            chipsWrap.innerHTML='';
            if (wdSrc==='royalties'){
                [minWdUsd,10,25,50].filter(function(v,i,a){ return v<=roySaldo && a.indexOf(v)===i; }).forEach(function(v){ addChip(fmtUsd(v),v); });
                if(roySaldo>=minWdUsd) addChip('Tudo ('+fmtUsd(roySaldo)+')',roySaldo);
            } else {
                [minWd,100,500,1000,2500,5000].filter(function(v,i,a){ return v<=saldo && a.indexOf(v)===i; }).forEach(function(v){ addChip(fmt(v),v); });
                if(saldo>=minWd) addChip('Tudo ('+fmt(saldo)+')',saldo);
            }
        }
        function updateWdConversion(){
            var box=document.getElementById('rmbz-vip-wd-conversion'), value=document.getElementById('rmbz-vip-wd-conversion-value');
            if(!box||!value) return;
            box.style.display=wdSrc==='royalties'?'block':'none';
            value.textContent=fmt(amount()*cambio);
        }
        amtIn.addEventListener('input',updateWdConversion);
        renderWdChips(); updateWdConversion();

        var err2El = document.getElementById('rmbz-vip-wd-err2');
        wdScrim.querySelectorAll('.rmbz-vip-wd-next').forEach(function(b){
            b.addEventListener('click', function(){
                var to = parseInt(b.getAttribute('data-to'),10);
                if (to===2){
                    var a=amount(), err='';
                    if(wdSrc==='royalties'){
                        if(a<minWdUsd) err='O valor mínimo é '+fmtUsd(minWdUsd)+'.';
                        else if(a>roySaldo) err='O valor excede os teus royalties.';
                    } else {
                        if(a<minWd) err='O valor mínimo é '+fmt(minWd)+'.';
                        else if(a>saldo) err='O valor excede o teu saldo retirável.';
                    }
                    if(err){ errEl.textContent=err; errEl.style.display='block'; return; }
                    errEl.style.display='none';
                }
                if (to===3){
                    var d=String(phoneIn.value).replace(/\D+/g,'');
                    if(d.length!==9){ err2El.textContent='O número tem de ter 9 dígitos (8XXXXXXXX).'; err2El.style.display='block'; phoneIn.focus(); return; }
                    // [1.5.454] Operadora ↔ prefixo (mesma regra do servidor):
                    // M-Pesa = Vodacom (84/85) · eMola = Movitel (86/87).
                    var pfx = d.substring(0,2), met = methodIn.value;
                    if (met === 'M-Pesa' && pfx !== '84' && pfx !== '85'){ err2El.textContent='O número ' + d + ' é Movitel (86/87) — para receber nesse número escolhe eMola, ou usa um número 84/85 para M-Pesa.'; err2El.style.display='block'; return; }
                    if (met === 'E-Mola' && pfx !== '86' && pfx !== '87'){ err2El.textContent='O número ' + d + ' é Vodacom (84/85) — para receber nesse número escolhe M-Pesa, ou usa um número 86/87 para eMola.'; err2El.style.display='block'; return; }
                    err2El.style.display='none';
                    phoneIn.value=d; detailsIn.value=d;
                }
                wstep(to);
            });
        });
        wdScrim.querySelectorAll('.rmbz-vip-wd-back').forEach(function(b){ b.addEventListener('click', function(){ wstep(parseInt(b.getAttribute('data-to'),10)); }); });
        wdScrim.querySelectorAll('.met').forEach(function(b){
            b.addEventListener('click', function(){
                wdScrim.querySelectorAll('.met').forEach(function(o){ var on=o===b; o.classList.toggle('on',on); var c=o.querySelector('.metchk'); c.textContent=on?'check_circle':'radio_button_unchecked'; c.style.color=on?'var(--brand-ink)':'var(--border2)'; c.style.fontVariationSettings=on?"'FILL' 1":"'FILL' 0"; });
                methodIn.value=b.getAttribute('data-method');
                if (err2El) err2El.style.display='none';
            });
        });
        wdScrim.querySelectorAll('.wd-contact').forEach(function(b){
            b.addEventListener('click',function(){
                phoneIn.value=b.getAttribute('data-number')||'';
                var wanted=(b.getAttribute('data-method')||'').toLowerCase().replace(/[^a-z]/g,'');
                wdScrim.querySelectorAll('.met').forEach(function(m){ var got=(m.getAttribute('data-method')||'').toLowerCase().replace(/[^a-z]/g,''); if(got===wanted) m.click(); });
                err2El.style.display='none';
            });
        });
        var initialPrefix=String(phoneIn.value||'').replace(/\D+/g,'').substring(0,2);
        if(initialPrefix==='86'||initialPrefix==='87'){ var em=wdScrim.querySelector('.met[data-method="E-Mola"]'); if(em) em.click(); }
        document.getElementById('rmbz-vip-wd-form').addEventListener('submit', function(){ detailsIn.value=String(phoneIn.value).replace(/\D+/g,''); });
        } // fim if(amtIn)

        // depósito
        var depScrim = document.getElementById('rmbz-vip-dep-scrim');
        root.querySelectorAll('#rmbz-vip-dep,[data-wallet-action="deposit"]').forEach(function(button){ button.addEventListener('click', function(){ depScrim.classList.add('open'); }); });
        root.querySelectorAll('.rmbz-vip-dep-x').forEach(function(b){ b.addEventListener('click', function(){ depScrim.classList.remove('open'); }); });
        depScrim.addEventListener('click', function(e){ if(e.target===depScrim) depScrim.classList.remove('open'); });

        /* ═══ [1.5.415] Funcionalidades portadas do painel antigo ═══ */
        var ajaxUrl = <?php echo wp_json_encode( $ajax_url ); ?>;
        var notifNonce = <?php echo wp_json_encode( $notif_nonce ); ?>;
        var vipNotifNonce = <?php echo wp_json_encode( $vip_notif_nonce ); ?>;
        var aiNonce = <?php echo wp_json_encode( $ai_nonce ); ?>;

        // Diálogos genéricos: [data-dialog] abre; .rmbz-vip-dclose e clique no fundo fecham.
        root.querySelectorAll('[data-dialog]').forEach(function(b){
            b.addEventListener('click', function(){ var d = document.getElementById(b.getAttribute('data-dialog')); if (d){ d._vipReturnFocus = b; d.classList.add('open'); } });
        });
        root.querySelectorAll('.scrim').forEach(function(s){
            var dialog = s.querySelector('.dialog');
            s.setAttribute('aria-hidden', s.classList.contains('open') ? 'false' : 'true');
            if (dialog){
                dialog.setAttribute('role','dialog'); dialog.setAttribute('aria-modal','true'); dialog.setAttribute('tabindex','-1');
                var heading = dialog.querySelector('h1,h2,h3,[data-dialog-title]');
                if (heading){ if (!heading.id) heading.id = 'rmbz-vip-dialog-title-' + Math.random().toString(36).slice(2,9); dialog.setAttribute('aria-labelledby',heading.id); }
            }
            new MutationObserver(function(){
                var open = s.classList.contains('open');
                s.setAttribute('aria-hidden', open ? 'false' : 'true');
                if (open && !s._vipWasOpen){
                    s._vipWasOpen = true;
                    if (!s._vipReturnFocus) s._vipReturnFocus = document.activeElement;
                    setTimeout(function(){
                        var first = s.querySelector('input:not([disabled]),select:not([disabled]),textarea:not([disabled]),button:not([disabled]),a[href],[tabindex]:not([tabindex="-1"])');
                        if (first) first.focus(); else if (dialog) dialog.focus();
                    },40);
                } else if (!open && s._vipWasOpen){
                    s._vipWasOpen = false;
                    var back = s._vipReturnFocus; s._vipReturnFocus = null;
                    if (back && document.contains(back)) setTimeout(function(){ back.focus(); },20);
                }
            }).observe(s,{attributes:true,attributeFilter:['class']});
            if (s.classList.contains('open')){
                s._vipWasOpen = true; s._vipReturnFocus = document.activeElement;
                setTimeout(function(){
                    var first = s.querySelector('input:not([disabled]),select:not([disabled]),textarea:not([disabled]),button:not([disabled]),a[href],[tabindex]:not([tabindex="-1"])');
                    if (first) first.focus(); else if (dialog) dialog.focus();
                },50);
            }
            s.addEventListener('click', function(e){ if (e.target === s) s.classList.remove('open'); });
            s.querySelectorAll('.rmbz-vip-dclose').forEach(function(x){ x.addEventListener('click', function(){ s.classList.remove('open'); }); });
        });
        // Comprovativos: reutiliza um visualizador fullscreen sem sair do painel.
        var proofViewer = document.getElementById('rmbz-vip-proof-viewer');
        var proofImage = proofViewer ? proofViewer.querySelector('[data-proof-full]') : null;
        var proofTitle = proofViewer ? proofViewer.querySelector('[data-proof-title]') : null;
        var proofOriginal = proofViewer ? proofViewer.querySelector('[data-proof-original]') : null;
        var proofStage = proofViewer ? proofViewer.querySelector('[data-proof-stage]') : null;
        root.querySelectorAll('.deposit-proof-trigger').forEach(function(trigger){
            trigger.addEventListener('click', function(){
                if (!proofViewer || !proofImage) return;
                var src = trigger.getAttribute('data-proof-src') || '';
                var title = trigger.getAttribute('data-proof-title') || 'Comprovativo do depósito';
                if (!src) return;
                proofViewer._vipReturnFocus = trigger;
                proofImage.src = src;
                proofImage.alt = title;
                if (proofTitle) proofTitle.textContent = title;
                if (proofOriginal) proofOriginal.href = src;
                proofViewer.classList.add('open');
            });
        });
        if (proofStage){
            proofStage.addEventListener('click', function(e){ if (e.target === proofStage && proofViewer) proofViewer.classList.remove('open'); });
        }
        if (proofViewer && proofImage){
            new MutationObserver(function(){
                if (proofViewer.classList.contains('open')) return;
                setTimeout(function(){
                    if (!proofViewer.classList.contains('open')) proofImage.removeAttribute('src');
                },220);
            }).observe(proofViewer,{attributes:true,attributeFilter:['class']});
        }
        document.addEventListener('keydown', function(e){
            var open = Array.prototype.slice.call(root.querySelectorAll('.scrim.open')).pop();
            if (!open) return;
            if (e.key === 'Escape'){
                e.preventDefault();
                if (open.id === 'rmbz-vip-dlg') dlgClose(false); else open.classList.remove('open');
                return;
            }
            if (e.key !== 'Tab') return;
            var focusable = Array.prototype.slice.call(open.querySelectorAll('a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])')).filter(function(el){ return el.offsetParent !== null; });
            if (!focusable.length){ e.preventDefault(); var d = open.querySelector('.dialog'); if (d) d.focus(); return; }
            var first = focusable[0], last = focusable[focusable.length-1];
            if (e.shiftKey && document.activeElement === first){ e.preventDefault(); last.focus(); }
            else if (!e.shiftKey && document.activeElement === last){ e.preventDefault(); first.focus(); }
        });
        // Toggles genéricos (mostrar/esconder blocos inline).
        root.querySelectorAll('.rmbz-vip-toggle').forEach(function(b){
            b.addEventListener('click', function(){ var t = document.getElementById(b.getAttribute('data-target')); if (t) t.style.display = (t.style.display === 'none' || !t.style.display) ? 'block' : 'none'; });
        });

        // Acordeao de projetos: o mais recente abre; os restantes ficam compactos.
        function setProjectOpen(card, open){
            var toggle = card.querySelector('.project-accordion-toggle');
            var body = card.querySelector('.project-accordion-body');
            card.classList.toggle('is-open', open);
            if (toggle) toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
            if (body) body.hidden = !open;
        }
        root.querySelectorAll('[data-project-accordion]').forEach(function(card){
            var toggle = card.querySelector('.project-accordion-toggle');
            if (!toggle) return;
            toggle.addEventListener('click', function(){
                var willOpen = !card.classList.contains('is-open');
                if (willOpen) {
                    root.querySelectorAll('[data-project-accordion].is-open').forEach(function(other){
                        if (other !== card) setProjectOpen(other, false);
                    });
                }
                setProjectOpen(card, willOpen);
            });
        });

        // Countdowns (bloqueios, prazo do contrato, fim da filmagem, agendamentos).
        var cds = root.querySelectorAll('.rmbz-vip-cd');
        if (cds.length){
            function tickCds(){
                var now = Math.floor(Date.now()/1000);
                cds.forEach(function(el){
                    var t = parseInt(el.getAttribute('data-until'),10)||0, r = Math.max(0, t-now);
                    var d = Math.floor(r/86400), h = Math.floor((r%86400)/3600), m = Math.floor((r%3600)/60), s = r%60;
                    el.textContent = (d>0? d+'d ' : '') + String(h).padStart(2,'0') + ':' + String(m).padStart(2,'0') + ':' + String(s).padStart(2,'0');
                });
            }
            tickCds(); setInterval(tickCds, 1000);
        }
        // Cronómetro REC (gravação ao vivo) — com offset do relógio do servidor.
        var clocks = root.querySelectorAll('.rmbz-vip-fsclock');
        if (clocks.length){
            var t0 = Date.now();
            function tickRec(){
                clocks.forEach(function(el){
                    var st = parseInt(el.getAttribute('data-started'),10)||0;
                    var sn = parseInt(el.getAttribute('data-servernow'),10)||0;
                    var now = sn + Math.floor((Date.now()-t0)/1000);
                    var e = Math.max(0, now-st);
                    el.textContent = String(Math.floor(e/3600)).padStart(2,'0')+':'+String(Math.floor((e%3600)/60)).padStart(2,'0')+':'+String(e%60).padStart(2,'0');
                });
            }
            tickRec(); setInterval(tickRec, 1000);
        }

        // Monitor unico: deteta tanto o inicio como o fim de uma filmagem.
        root.querySelectorAll('[data-filming-monitor]').forEach(function(monitor){
            var statusUrl = monitor.getAttribute('data-status-url');
            var initialProject = parseInt(monitor.getAttribute('data-active-project'), 10) || 0;
            var initialStarted = parseInt(monitor.getAttribute('data-active-started'), 10) || 0;
            var projectSection = monitor.closest('.sect');
            var checking = false;
            if (!statusUrl) return;
            function checkFilmingStatus(){
                if (checking || document.hidden || (projectSection && !projectSection.classList.contains('on'))) return;
                checking = true;
                fetch(statusUrl, { credentials:'same-origin', cache:'no-store' })
                    .then(function(response){ if (!response.ok) throw new Error('status'); return response.json(); })
                    .then(function(payload){
                        var data = payload && payload.data ? payload.data : payload;
                        if (!data) return;
                        var projectId = parseInt(data.active_project_id, 10) || 0;
                        var started = parseInt(data.started_ts, 10) || 0;
                        if (projectId !== initialProject || (projectId > 0 && started !== initialStarted)) {
                            if (typeof showSplash === 'function') showSplash();
                            window.location.reload();
                        }
                    })
                    .catch(function(){})
                    .then(function(){ checking = false; });
            }
            checkFilmingStatus();
            setInterval(checkFilmingStatus, 4000);
        });

        // Transferência: aceitar só com termos + nome + telefone válidos.
        root.querySelectorAll('.rmbz-vip-tr-form').forEach(function(f){
            var dlg = f.closest('.dialog');
            var ck = dlg.querySelector('.rmbz-vip-tr-ck'), nm = dlg.querySelector('.rmbz-vip-tr-nm'), tl = dlg.querySelector('.rmbz-vip-tr-tl'), ok = f.querySelector('.rmbz-vip-tr-ok');
            function upd(){ var td = (tl.value||'').replace(/[^0-9+]/g,''); ok.disabled = !(ck.checked && (nm.value||'').trim().length >= 2 && td.length >= 7); }
            [ck,nm,tl].forEach(function(el){ el.addEventListener('input', upd); el.addEventListener('change', upd); });
            f.addEventListener('submit', function(){ f.suggested_name.value = nm.value; f.suggested_tel.value = tl.value; });
        });

        // Notificações: mesma fonte da App; o clique expande e dispensa o aviso.
        function vipNotifSend(card) {
            if (!card || card.getAttribute('data-read') === '1') return;
            card.setAttribute('data-read','1');
            card.style.borderColor = 'var(--border)';
            var fd = new FormData();
            fd.append('action','rmbz_vip_notif_dismiss');
            fd.append('notif_id', card.getAttribute('data-nid'));
            fd.append('source', card.getAttribute('data-source') || 'native');
            fd.append('nonce', vipNotifNonce);
            try { fetch(ajaxUrl, { method:'POST', body:fd, credentials:'same-origin', keepalive:true }); } catch(e) {}
        }
        root.querySelectorAll('.rmbz-vip-notif').forEach(function(card){
            function activate(e){
                if (e && e.target && e.target.closest('.rmbz-vip-notif-action')) return;
                var sn = card.querySelector('.rmbz-vip-notif-snip'), fu = card.querySelector('.rmbz-vip-notif-full');
                if (sn && fu){ var open = fu.style.display !== 'none'; fu.style.display = open ? 'none' : 'block'; sn.style.display = open ? 'block' : 'none'; card.setAttribute('aria-expanded', open ? 'false' : 'true'); }
                vipNotifSend(card);
            }
            card.addEventListener('click', activate);
            card.addEventListener('keydown', function(e){ if(e.key === 'Enter' || e.key === ' '){ e.preventDefault(); activate(e); } });
            var action = card.querySelector('.rmbz-vip-notif-action');
            if (action) action.addEventListener('click', function(){ vipNotifSend(card); });
        });
        var clearBtn = document.getElementById('rmbz-vip-notif-clear');
        if (clearBtn) clearBtn.addEventListener('click', function(){
            vipConfirm('Marcar todas as notificações como vistas?').then(function(ok){
                if (!ok) return;
                var fd = new FormData(); fd.append('action','rmbz_vip_notif_dismiss_all'); fd.append('nonce', vipNotifNonce);
                fetch(ajaxUrl, { method:'POST', body:fd, credentials:'same-origin' }).then(function(){ location.reload(); });
            });
        });

        // Assistente de IA do site: reutiliza o mesmo endpoint, memória e limites da App.
        var aiForm = document.getElementById('rmbz-vip-ai-form');
        if (aiForm) aiForm.addEventListener('submit', function(e){
            e.preventDefault();
            var q = document.getElementById('rmbz-vip-ai-question');
            var answer = document.getElementById('rmbz-vip-ai-answer');
            var send = document.getElementById('rmbz-vip-ai-send');
            if (!q || !(q.value || '').trim()) return;
            send.disabled = true; answer.style.display = 'block'; answer.textContent = 'A analisar os teus dados…';
            var fd = new FormData(); fd.append('action','rmbz_vip_ai_ask'); fd.append('nonce',aiNonce); fd.append('question',q.value.trim());
            fetch(ajaxUrl,{method:'POST',body:fd,credentials:'same-origin'}).then(function(r){ return r.json(); }).then(function(j){
                if (!j || !j.success) throw new Error(j && j.data && j.data.message ? j.data.message : 'Não foi possível responder agora.');
                answer.textContent = (j.data && j.data.answer) ? j.data.answer : 'Sem resposta.';
                q.value = '';
            }).catch(function(err){ answer.textContent = err.message || 'Não foi possível responder agora.'; }).finally(function(){ send.disabled = false; });
        });

        // Confirmações assíncronas para ações de segurança.
        root.querySelectorAll('form[data-vip-confirm-submit]').forEach(function(form){
            form.addEventListener('submit', function(e){
                if (form.getAttribute('data-confirmed') === '1') return;
                e.preventDefault();
                vipConfirm(form.getAttribute('data-vip-confirm-submit') || 'Confirmar esta ação?').then(function(ok){
                    if (!ok) return;
                    form.setAttribute('data-confirmed','1');
                    HTMLFormElement.prototype.submit.call(form);
                });
            });
        });

        // Popup do admin: OK = dispensar (AJAX do antigo).
        var apOk = document.getElementById('rmbz-vip-adminpop-ok');
        if (apOk) apOk.addEventListener('click', function(){
            document.getElementById('rmbz-vip-adminpop').style.display = 'none';
            var fd = new FormData(); fd.append('action','rmbz_dismiss_admin_popup'); fd.append('nonce', notifNonce);
            fetch(ajaxUrl, { method:'POST', body:fd, credentials:'same-origin' });
        });

        // Depósito: alternar ID da transação vs imagem.
        root.querySelectorAll('.rmbz-vip-dep-pt').forEach(function(r){
            r.addEventListener('change', function(){
                var img = r.value === 'image';
                var tx = document.getElementById('rmbz-vip-dep-txid'), im = document.getElementById('rmbz-vip-dep-img');
                if (tx) { tx.style.display = img ? 'none' : 'block'; tx.required = !img; }
                if (im) { im.style.display = img ? 'block' : 'none'; im.required = img; }
            });
        });

        // Levantamento: fonte Carteira (MT) vs Royalties (USD) — troca o nome
        // do campo (rmbz_withdrawal_amount / _usd), o saldo validado e o resumo.
        var srcIn = document.getElementById('rmbz-vip-wd-source');
        if (amtIn){ // [1.5.454] só quando o form de levantamento existe
        function setSrc(s){
            wdSrc = s; if (srcIn) srcIn.value = s;
            amtIn.name = s === 'royalties' ? 'rmbz_withdrawal_amount_usd' : 'rmbz_withdrawal_amount';
            amtIn.min = s === 'royalties' ? String(minWdUsd) : String(minWd);
            amtIn.max = s === 'royalties' ? String(roySaldo) : String(saldo);
            var unit = document.getElementById('rmbz-vip-wd-unit'); if(unit) unit.textContent=s==='royalties'?'USD':'MT';
            var hint = document.getElementById('rmbz-vip-wd-hint');
            if (hint) hint.innerHTML = s === 'royalties'
                ? 'Royalties: <b>' + fmtUsd(roySaldo) + '</b> · mínimo ' + fmtUsd(minWdUsd) + ' · câmbio ' + cambio.toFixed(2)
                : 'Saldo retirável: <b>' + fmt(saldo) + '</b> · mínimo ' + fmt(minWd);
            root.querySelectorAll('.rmbz-vip-wd-src').forEach(function(c){ var on = c.getAttribute('data-src') === s; c.classList.toggle('on', on); });
            amtIn.value = '';
            renderWdChips(); updateWdConversion();
        }
        root.querySelectorAll('.rmbz-vip-wd-src').forEach(function(c){ c.addEventListener('click', function(){ setSrc(c.getAttribute('data-src')); }); });
        setSrc(wdSrc);
        } // fim if(amtIn) — fonte do levantamento

        // Pacotes VIP: recalcular preço com a duração e o add-on de IA.
        root.querySelectorAll('.rmbz-vip-pk-form').forEach(function(f){
            var card = f.closest('div');
            var priceEl = f.parentElement.querySelector('.rmbz-vip-pk-price');
            var daysEl = f.parentElement.querySelector('.rmbz-vip-pk-days');
            var sel = f.querySelector('.rmbz-vip-pk-months');
            var ai = f.querySelector('.rmbz-vip-pk-ai');
            function upd(){
                if (!sel || !priceEl) return;
                var o = sel.options[sel.selectedIndex]; if (!o) return;
                var v = parseFloat((ai && ai.checked) ? o.getAttribute('data-price-ai') : o.getAttribute('data-price')) || 0;
                priceEl.textContent = v.toLocaleString('pt-PT',{minimumFractionDigits:2,maximumFractionDigits:2}).replace(/[  ]/g,' ') + ' MT';
                if (daysEl) daysEl.textContent = (o.getAttribute('data-days')||'') + ' dias de acesso';
            }
            if (sel) sel.addEventListener('change', upd);
            if (ai) ai.addEventListener('change', upd);
            upd();
        });

        // Copiar código de referral.
        var refBtn = document.getElementById('rmbz-vip-refcopy');
        if (refBtn) refBtn.addEventListener('click', function(){
            var i = document.getElementById('rmbz-vip-refcode'); i.select();
            try { document.execCommand('copy'); refBtn.textContent = '✅ Copiado'; setTimeout(function(){ refBtn.textContent = 'Copiar'; }, 2000); } catch (e) {}
        });

        // Heartbeat anti-offline (igual ao antigo, a cada 3 min).
        setInterval(function(){
            var fd = new FormData(); fd.append('action','rmbz_artist_heartbeat'); fd.append('nonce', notifNonce);
            fetch(ajaxUrl, { method:'POST', body:fd, credentials:'same-origin' });
        }, 180000);

        /* ═══ [1.5.416] FORMULÁRIO DE ENVIO NATIVO (rvu-*) ═══ */
        var rvuForm = document.getElementById('rvu-form');
        if (rvuForm){
            var rvuType = document.getElementById('rvu-type-in');
            var rvuAudioNonce = (document.getElementById('rvu-audio-nonce')||{}).value || '';
            var rvuUploading = false;

            function rvuSelect(type){
                rvuType.value = type;
                root.querySelectorAll('.rvu-type').forEach(function(b){ b.classList.toggle('on', b.getAttribute('data-type') === type); });
                rvuForm.querySelectorAll('.rvu-sec').forEach(function(s){ s.style.display = s.getAttribute('data-sec') === type ? 'block' : 'none'; });
                // required só na secção ativa
                rvuForm.querySelectorAll('input,select,textarea').forEach(function(el){ if (el.type !== 'hidden') el.required = false; });
                var cls = { audio_site:'.rvu-req-site', video_social:'.rvu-req-social', win_video:'.rvu-req-proj' }[type];
                if (cls) rvuForm.querySelectorAll(cls).forEach(function(el){ el.required = true; });
                var reqNamed = {
                    audio_site: ['artist_name','music_title','music_genre','social_link'],
                    video_social: ['video_artist_name','video_title','video_link_url'],
                    win_video: ['project_artist','project_title','music_producer','project_pitch']
                }[type] || [];
                reqNamed.forEach(function(n){ var f = rvuForm.querySelector('[name="'+n+'"]'); if (f) f.required = true; });
                if (type === 'audio_site') rvuAlbum();
                if (type === 'win_video') rvuScen('basic');
            }
            root.querySelectorAll('.rvu-type').forEach(function(b){ b.addEventListener('click', function(){ rvuSelect(b.getAttribute('data-type')); }); });

            // Yes/No toggles genéricos (data-box + data-show).
            rvuForm.querySelectorAll('.rvu-yn input').forEach(function(r){
                r.addEventListener('change', function(){
                    var box = document.getElementById(r.getAttribute('data-box'));
                    if (!box) return;
                    if (r.getAttribute('data-show') === '1'){ box.style.display = 'block'; }
                    else { box.style.display = 'none'; box.querySelectorAll('input').forEach(function(i){ if (i.type!=='radio' && i.type!=='checkbox') i.value=''; }); }
                });
            });

            // Álbum vs single.
            var rvuAlbumChk = document.getElementById('rvu-album');
            function rvuAlbum(){
                if (!rvuAlbumChk) return;
                var on = rvuAlbumChk.checked;
                var s = document.getElementById('rvu-single-audio'), a = document.getElementById('rvu-album-audio'), l = document.getElementById('rvu-title-lbl');
                if (s) s.style.display = on ? 'none' : 'block';
                if (a) a.style.display = on ? 'block' : 'none';
                if (l) l.textContent = on ? 'Título do Álbum / EP *' : 'Título da Música *';
            }
            if (rvuAlbumChk) rvuAlbumChk.addEventListener('change', rvuAlbum);
            var rvuTrackN = 1;
            var addTrack = document.getElementById('rvu-add-track');
            if (addTrack) addTrack.addEventListener('click', function(){
                rvuTrackN++;
                var row = document.createElement('div');
                row.className = 'rvu-track'; row.style.cssText = 'display:flex; gap:8px; margin-bottom:8px; align-items:center;';
                row.innerHTML = '<span style="font-weight:700; color:var(--muted); width:18px;">'+rvuTrackN+'.</span><input class="inp" type="text" name="album_track_titles[]" placeholder="Título da faixa" style="flex:1;"><input type="file" name="album_track_files[]" accept=".mp3,.wav" style="max-width:160px; font-size:12px; color:var(--text2);"><button type="button" class="chip" style="padding:6px 10px;">✕</button>';
                row.querySelector('button').addEventListener('click', function(){ row.remove(); });
                document.getElementById('rvu-tracks').appendChild(row);
            });

            // Cenários.
            var rvuScenData = {
                basic:{ desc:'Produção simples, 1 locação, sem atores profissionais.', cost:'Baixo', chance:'Alta (fácil aprovação)', req:'Normal', c:'var(--success)' },
                professional:{ desc:'Produção média, múltiplas locações, modelos profissionais.', cost:'Médio', chance:'Média', req:'Boa qualidade musical', c:'var(--brand)' },
                cinema:{ desc:'Produção cinematográfica completa, atores avançados.', cost:'Alto', chance:'Baixa (exige hit)', req:'Alta qualidade e potencial', c:'var(--danger)' }
            };
            function rvuScen(key){
                var i = rvuScenData[key]; if (!i) return;
                var box = document.getElementById('rvu-scen-info');
                if (box) box.innerHTML = '<div style="border-left:3px solid '+i.c+'; padding-left:14px;"><div style="font-size:13px; color:var(--text); margin-bottom:8px;">'+i.desc+'</div><div style="display:grid; grid-template-columns:1fr 1fr; gap:8px; font-size:12px; color:var(--text2);"><div>💰 Custo: <b style="color:'+i.c+'">'+i.cost+'</b></div><div>🎯 Chance: <b style="color:'+i.c+'">'+i.chance+'</b></div><div style="grid-column:span 2;">⚠️ Exigência: '+i.req+'</div></div></div>';
                root.querySelectorAll('.rvu-scen').forEach(function(c){ c.classList.toggle('on', c.getAttribute('data-scen') === key); });
                var rad = rvuForm.querySelector('input[name="video_scenario"][value="'+key+'"]'); if (rad) rad.checked = true;
            }
            root.querySelectorAll('.rvu-scen').forEach(function(c){ c.addEventListener('click', function(){ rvuScen(c.getAttribute('data-scen')); }); });

            // Feat (win_video): mostrar caixa + verificação em tempo real.
            var featEnabled = document.getElementById('rvu-feat-enabled');
            if (featEnabled) featEnabled.addEventListener('change', function(){ document.getElementById('rvu-feat-proj').style.display = this.checked ? 'block' : 'none'; });
            var featHas = document.getElementById('rvu-feat-has');
            if (featHas) featHas.addEventListener('change', function(){ document.getElementById('rvu-feat-tel-wrap').style.display = this.checked ? 'block' : 'none'; rvuFeatCheck(); });
            var featTel = document.getElementById('rvu-feat-tel'), featStatus = document.getElementById('rvu-feat-status'), featTimer = null, featState = 'idle';
            function featShow(msg,c){ if (featStatus){ featStatus.style.display='block'; featStatus.style.color=c; featStatus.textContent=msg; } }
            function rvuFeatCheck(){
                if (!featTel || !featStatus) return;
                var tel = (featTel.value||'').replace(/[^0-9+]/g,'');
                if (tel.length < 7){ featState='idle'; featStatus.style.display='none'; return; }
                featState='checking'; featShow('A verificar a conta…','var(--muted)');
                var d = new URLSearchParams(); d.append('action','rmbz_feat_check_account'); d.append('tel',tel); d.append('_wpnonce', <?php echo wp_json_encode( $up_nonce_feat ); ?>);
                fetch(ajaxUrl, { method:'POST', body:d, credentials:'same-origin' }).then(function(r){ return r.json(); }).then(function(j){
                    if (j && j.self){ featState='invalid'; featShow('✕ Esse número é a tua própria conta.','var(--danger)'); }
                    else if (j && j.exists){ featState='valid'; featShow('✔ Artista válido — '+(j.name||'conta encontrada'),'var(--success)'); }
                    else { featState='invalid'; featShow('✕ Conta não encontrada. Confirma o número ou desmarca "tem conta 1MZ".','var(--danger)'); }
                }).catch(function(){ featState='idle'; featShow('Não foi possível verificar agora.','var(--brand-ink)'); });
            }
            if (featTel) featTel.addEventListener('input', function(){ clearTimeout(featTimer); featTimer=setTimeout(rvuFeatCheck, 450); });

            // Pré-visualização de imagens (capa / thumbnail).
            rvuForm.querySelectorAll('.rvu-drop').forEach(function(dz){
                var inp = document.getElementById(dz.getAttribute('data-target'));
                var prev = document.getElementById(dz.getAttribute('data-target')+'-prev');
                dz.addEventListener('click', function(){ inp.click(); });
                inp.addEventListener('change', function(){
                    if (!inp.files || !inp.files[0] || !prev) return;
                    var f = inp.files[0];
                    if (f.type.indexOf('image/') === 0){
                        var rd = new FileReader();
                        rd.onload = function(e){ prev.innerHTML = '<img src="'+e.target.result+'"><div>✅ '+f.name+'</div>'; prev.style.display='block'; };
                        rd.readAsDataURL(f);
                    } else { prev.innerHTML = '✅ '+f.name; prev.style.display='block'; }
                });
            });

            // Upload AJAX do áudio (mesma rota rmbz_async_audio_upload).
            function rvuSubBtns(disable){
                rvuForm.querySelectorAll('button[type="submit"]').forEach(function(b){ b.disabled = disable; b.style.opacity = disable ? '.5' : '1'; if (disable && !b.dataset.og){ b.dataset.og = b.textContent; b.textContent = 'A enviar áudio… ⏳'; } else if (!disable && b.dataset.og){ b.textContent = b.dataset.og; delete b.dataset.og; } });
            }
            rvuForm.querySelectorAll('.rvu-audio').forEach(function(dz){
                var inp = dz.querySelector('.rvu-audio-input'), urlIn = dz.querySelector('.rvu-audio-url');
                var idle = dz.querySelector('.rvu-audio-idle'), prog = dz.querySelector('.rvu-audio-prog'), ok = dz.querySelector('.rvu-audio-ok');
                var bar = dz.querySelector('.rvu-audio-bar'), pct = dz.querySelector('.rvu-audio-pct'), nameEl = dz.querySelector('.rvu-audio-name');
                function reset(){ idle.style.display='block'; prog.style.display='none'; ok.style.display='none'; inp.value=''; urlIn.value=''; dz.style.borderColor='var(--border2)'; rvuUploading=false; rvuSubBtns(false); }
                dz.addEventListener('click', function(e){ if (e.target.closest('.rvu-audio-reset')) return; if (!urlIn.value) inp.click(); });
                dz.querySelector('.rvu-audio-reset').addEventListener('click', function(e){ e.stopPropagation(); reset(); });
                inp.addEventListener('change', function(){
                    var f = inp.files[0]; if (!f) return;
                    if (f.size > 50*1024*1024){ vipAlert('A música excede 50 MB.'); inp.value=''; return; }
                    var ext = f.name.split('.').pop().toLowerCase();
                    if (['audio/mpeg','audio/wav','audio/x-wav','audio/mp3'].indexOf(f.type) === -1 && ext !== 'mp3' && ext !== 'wav'){ vipAlert('Formato inválido. Apenas MP3 ou WAV.'); inp.value=''; return; }
                    idle.style.display='none'; prog.style.display='block'; dz.style.borderColor='var(--brand)'; rvuUploading=true; rvuSubBtns(true);
                    var fd = new FormData(); fd.append('action','rmbz_async_audio_upload'); fd.append('security', rvuAudioNonce); fd.append('async_audio_file', f);
                    var xhr = new XMLHttpRequest(); xhr.open('POST', ajaxUrl, true);
                    xhr.upload.onprogress = function(e){ if (e.lengthComputable){ var p = Math.round(e.loaded/e.total*100); bar.style.width=p+'%'; pct.textContent=p+'%'; } };
                    xhr.onload = function(){
                        rvuUploading = false;
                        if (xhr.status === 200){ try { var res = JSON.parse(xhr.responseText); if (res.success){ prog.style.display='none'; ok.style.display='block'; nameEl.textContent=f.name; urlIn.value=res.data.url; dz.style.borderColor='var(--success)'; rvuSubBtns(false); return; } vipAlert('Erro no upload: '+(res.data&&res.data.message||'')); } catch(e){ vipAlert('Erro de resposta do servidor.'); } }
                        else vipAlert('Erro de conexão ('+xhr.status+').');
                        reset();
                    };
                    xhr.onerror = function(){ vipAlert('A ligação falhou. Verifica a internet.'); reset(); };
                    xhr.send(fd);
                });
            });

            // Validação de links + campos de ficheiro na submissão.
            function rvuValidLink(url, plat){
                if (!url || !url.trim()) return true; url = url.toLowerCase();
                if (plat==='youtube') return url.indexOf('youtube.com')>-1 || url.indexOf('youtu.be')>-1;
                if (plat==='spotify') return url.indexOf('spotify.com')>-1;
                if (plat==='apple') return url.indexOf('apple.com')>-1;
                if (plat==='drive') return ['drive.google.com','dropbox.com','wetransfer.com','1drv.ms','mega.nz'].some(function(d){ return url.indexOf(d)>-1; });
                return true;
            }
            rvuForm.addEventListener('submit', function(e){
                var type = rvuType.value;
                if (rvuUploading){ e.preventDefault(); vipAlert('Aguarda o upload do áudio terminar.'); return; }
                if (type === 'audio_site'){
                    if (!document.getElementById('rvu-cover').value){ e.preventDefault(); vipAlert('⚠️ Faz o upload da Capa da Música.'); return; }
                    var isAlbum = rvuAlbumChk && rvuAlbumChk.checked;
                    if (!isAlbum && !rvuForm.querySelector('#rvu-dz-site .rvu-audio-url').value){ e.preventDefault(); vipAlert('⚠️ Faz o upload do áudio (MP3) e aguarda concluir.'); return; }
                    var yt = rvuForm.querySelector('[name="youtube_link"]').value;
                    if (rvuForm.querySelector('[name="has_video"][value="yes"]').checked && !rvuValidLink(yt,'youtube')){ e.preventDefault(); vipAlert('❌ O link do videoclipe tem de ser do YouTube.'); return; }
                } else if (type === 'video_social'){
                    if (!document.getElementById('rvu-vthumb').value){ e.preventDefault(); vipAlert('⚠️ Faz o upload da Capa do Vídeo (thumbnail).'); return; }
                    if (!rvuValidLink(rvuForm.querySelector('[name="video_link_url"]').value,'drive')){ e.preventDefault(); vipAlert('❌ O link do HD deve ser Google Drive, Dropbox, WeTransfer ou Mega.'); return; }
                } else if (type === 'win_video'){
                    if (!rvuForm.querySelector('#rvu-dz-project .rvu-audio-url').value){ e.preventDefault(); vipAlert('⚠️ Faz o upload do MP3 da demo e aguarda concluir.'); return; }
                    if (featEnabled && featEnabled.checked && featHas && featHas.checked && featState !== 'valid'){ e.preventDefault(); rvuFeatCheck(); featShow('✕ Verifica a conta do participante (tem de aparecer "Artista válido").','var(--danger)'); if (featStatus) featStatus.scrollIntoView({behavior:'smooth',block:'center'}); return; }
                }
            });

            // Auto-selecionar o primeiro tipo disponível.
            var firstType = root.querySelector('.rvu-type');
            if (firstType) rvuSelect(firstType.getAttribute('data-type'));
        }

        /* ═══ [1.5.420] Sub-vistas da Distribuição (visão geral/stats/perfis) ═══ */
        function rvdView(name){
            root.querySelectorAll('.rvd-view').forEach(function(v){ v.hidden = v.getAttribute('data-dview') !== name; });
            root.querySelectorAll('.rvd-tab').forEach(function(t){
                var on = t.getAttribute('data-dview') === name;
                t.classList.toggle('on', on);
            });
        }
        root.querySelectorAll('.rvd-tab, .rvd-goview').forEach(function(b){ b.addEventListener('click', function(){ rvdView(b.getAttribute('data-dview')); root.querySelector('.main').scrollTop = 0; }); });

        // O módulo SOMAS usa links próprios; preserva a sub-vista do painel
        // ao escolher entre novo registo e validação de membro existente.
        root.querySelectorAll('.rvd-somas-native a[href*="somas_path="], .rvd-somas-native a[href*="distro_action=licensing-somas"]').forEach(function(a){
            try {
                var u = new URL(a.href, location.href), path = u.searchParams.get('somas_path');
                var nativeUrl = <?php echo wp_json_encode( home_url( '/minha-conta/' ) ); ?> + '?sect=distro&dview=somas';
                if (path) nativeUrl += '&somas_path=' + encodeURIComponent(path);
                a.href = nativeUrl;
            } catch(e) {}
        });

        // Licenciamento SOMAS nativo, partilhado pelo wizard e pelo detalhe.
        function licEsc(value){ var el=document.createElement('div'); el.textContent=String(value==null?'':value); return el.innerHTML; }
        function licFmt(value){ return Number(value||0).toLocaleString('pt-PT',{minimumFractionDigits:2,maximumFractionDigits:2}).replace(/[\u00a0\u202f]/g,' ') + ' MT'; }
        function loadLicensePanel(box, force){
            if (!box) return Promise.resolve();
            var releaseId = box.getAttribute('data-release-id');
            if (!releaseId) return Promise.resolve();
            if (box.getAttribute('data-loaded') === '1' && !force) return Promise.resolve();
            box.setAttribute('data-loaded','1');
            box.innerHTML = '<div class="card" style="padding:15px 17px; color:var(--muted); font-size:12.5px;">A carregar licenciamento SOMAS…</div>';
            var fd = new FormData(); fd.append('action','rmbz_vip_distro_license_panel'); fd.append('nonce',<?php echo wp_json_encode( $rvd_nonce_distro ); ?>); fd.append('release_id',releaseId);
            return fetch(ajaxUrl,{method:'POST',body:fd,credentials:'same-origin'}).then(function(r){ return r.json(); }).then(function(j){
                if (!j || !j.success) throw new Error((j && j.data && (j.data.message||j.data)) || 'Licenciamento indisponível.');
                var d=j.data||{};
                if (!d.enabled){ box.innerHTML=''; box.style.display='none'; return; }
                box.style.display='block';
                var head='<div class="release-license-head"><span class="ms release-license-icon" aria-hidden="true">music_note</span><div class="release-license-head-copy"><div class="release-license-title">Licenciamento musical SOMAS</div><div class="release-license-subtitle">Opcional. Protege a obra e permite receber direitos de execução pública.</div></div></div>';
                if (d.license){
                    var labels={pending:'Pedido em análise',processing:'Em processamento na SOMAS',approved:'Licenciado',rejected:'Pedido rejeitado',refunded:'Valor devolvido'};
                    var tone=d.license.status==='approved'?'var(--success)':(d.license.status==='rejected'?'var(--danger)':'var(--rev)');
                    box.innerHTML='<div class="card" style="padding:16px 18px;border-color:'+tone+';">'+head+'<div style="margin-top:13px;padding:11px 13px;border-radius:12px;background:var(--elev);"><b style="color:'+tone+';">'+licEsc(labels[d.license.status]||d.license.status)+'</b><div style="font-size:12px;color:var(--text2);margin-top:3px;">'+d.license.track_count+' faixa(s) · '+licFmt(d.license.amount_charged)+(d.license.coupon_discount?' · desconto '+licFmt(d.license.coupon_discount):'')+'</div></div></div>';
                    return;
                }
                var reg=d.registration;
                if (!reg || reg.status==='rejected'){
                    box.innerHTML='<div class="card release-license-registration"><div class="release-license-registration-copy">'+head+'<p>Para licenciar precisas primeiro de um registo SOMAS aprovado. A taxa única de registo é <b>'+licFmt(d.registration_price)+'</b>.</p></div><a class="release-license-registration-action" href="<?php echo esc_url( add_query_arg( [ 'sect' => 'distro', 'dview' => 'somas' ], home_url( '/minha-conta/' ) ) ); ?>"><span class="ms" aria-hidden="true">add_circle</span>Criar registo SOMAS</a></div>';
                    return;
                }
                if (reg.status==='pending' || reg.status==='returned'){
                    box.innerHTML='<div class="card" style="padding:16px 18px;">'+head+'<div style="margin-top:12px;padding:11px 13px;border-radius:12px;background:var(--rev-soft);color:var(--rev);font-size:12.5px;font-weight:650;">'+(reg.status==='returned'?'O pedido SOMAS precisa de correções.':'O pedido SOMAS está em análise.')+'</div><a href="<?php echo esc_url( add_query_arg( [ 'sect' => 'distro', 'dview' => 'somas' ], home_url( '/minha-conta/' ) ) ); ?>" style="display:inline-block;margin-top:10px;color:var(--brand-ink);font-size:12px;font-weight:750;">Abrir gestão SOMAS</a></div>';
                    return;
                }
                var disabled=d.track_count<1 || Number(d.balance)<Number(d.base_total);
                box.innerHTML='<div class="card" style="padding:16px 18px;">'+head+'<div style="margin-top:14px;display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;"><div style="background:var(--elev);padding:10px;border-radius:11px;"><small style="color:var(--muted);">FAIXAS</small><div style="font-weight:800;">'+d.track_count+'</div></div><div style="background:var(--elev);padding:10px;border-radius:11px;"><small style="color:var(--muted);">TOTAL</small><div class="rvlic-total" style="font-weight:800;">'+licFmt(d.base_total)+'</div></div><div style="background:var(--elev);padding:10px;border-radius:11px;"><small style="color:var(--muted);">SALDO</small><div style="font-weight:800;">'+licFmt(d.balance)+'</div></div></div><div style="display:flex;gap:8px;margin-top:12px;flex-wrap:wrap;"><input class="inp rvlic-code" type="text" maxlength="50" placeholder="Cupão (opcional)" style="flex:1;min-width:150px;text-transform:uppercase;margin:0;"><button type="button" class="chip rvlic-apply">Aplicar</button><button type="button" class="pill rvlic-submit" '+(disabled?'disabled':'')+' style="background:var(--brand);color:var(--on-brand);">Licenciar agora</button></div><div class="rvlic-msg" style="font-size:11.5px;color:var(--muted);margin-top:7px;">'+(d.track_count<1?'Adiciona pelo menos uma faixa.':(disabled?'Saldo insuficiente para licenciar.':'Preço: '+licFmt(d.unit_price)+' por faixa.'))+'</div></div>';
                var code='', msg=box.querySelector('.rvlic-msg'), total=box.querySelector('.rvlic-total'), submit=box.querySelector('.rvlic-submit');
                box.querySelector('.rvlic-apply').addEventListener('click',function(){
                    code=(box.querySelector('.rvlic-code').value||'').trim().toUpperCase(); if(!code){msg.textContent='Insere o código do cupão.';return;}
                    msg.textContent='A validar cupão…'; var cf=new FormData(); cf.append('action','rmbz_validate_licensing_coupon'); cf.append('_nonce',d.license_nonce); cf.append('code',code); cf.append('release_id',releaseId);
                    fetch(ajaxUrl,{method:'POST',body:cf,credentials:'same-origin'}).then(function(r){return r.json();}).then(function(cj){var cd=cj&&cj.data||{};if(cj&&cj.success&&cd.valid){total.textContent=licFmt(cd.final_total);msg.style.color='var(--success)';msg.textContent='Cupão aplicado: desconto de '+licFmt(cd.discount);submit.disabled=Number(d.balance)<Number(cd.final_total);}else{code='';msg.style.color='var(--danger)';msg.textContent=cd.error||cd.msg||'Cupão inválido.';}}).catch(function(){msg.textContent='Não foi possível validar o cupão.';});
                });
                submit.addEventListener('click',function(){
                    vipConfirm('Confirmas o licenciamento? O valor será debitado da tua carteira.').then(function(ok){if(!ok)return;submit.disabled=true;submit.textContent='A processar…';var sf=new FormData();sf.append('action','rmbz_submit_license');sf.append('_nonce',d.license_nonce);sf.append('release_id',releaseId);sf.append('coupon_code',code);fetch(ajaxUrl,{method:'POST',body:sf,credentials:'same-origin'}).then(function(r){return r.json();}).then(function(sj){if(!sj||!sj.success)throw new Error((sj&&sj.data&&(sj.data.msg||sj.data.message))||'Falha ao submeter.');return vipAlert('Pedido de licenciamento submetido com sucesso.');}).then(function(){box.setAttribute('data-loaded','0');loadLicensePanel(box,true);}).catch(function(err){submit.disabled=false;submit.textContent='Licenciar agora';msg.style.color='var(--danger)';msg.textContent=err.message;});});
                });
            }).catch(function(err){ box.innerHTML='<div class="card" style="padding:14px 16px;border-color:var(--danger);color:var(--danger);font-size:12.5px;">'+licEsc(err.message)+'</div>'; });
        }
        loadLicensePanel(document.getElementById('rvd-license-box'));

        // Splits: o módulo oficial mantém as validações, fases e notificações.
        var splitsOpen = document.getElementById('rvd-splits-open');
        if (splitsOpen) splitsOpen.addEventListener('click', function(){
            if (typeof window.rmbzOpenSplitsModal === 'function') window.rmbzOpenSplitsModal();
            else vipAlert('Não foi possível abrir os splits agora. Recarrega a página e tenta novamente.');
        });
        var storesOpen = document.getElementById('rvd-stores-open');
        if (storesOpen) storesOpen.addEventListener('click', function(){
            if (typeof window.rmbzOpenStoresModal === 'function') {
                var storesForm = document.getElementById('rmbz-stores-fe-form');
                if (storesForm && !storesForm.querySelector('[name="return_to"]')){
                    var back = document.createElement('input'); back.type='hidden'; back.name='return_to'; back.value='vip'; storesForm.appendChild(back);
                }
                window.rmbzOpenStoresModal();
            } else vipAlert('Não foi possível abrir a gestão de lojas agora. Recarrega a página e tenta novamente.');
        });

        // Takedown nativo: pré-valida idade do release e holdings antes do envio.
        var tdScrim = document.getElementById('rvd-td-scrim');
        if (tdScrim){
            var tdRid = tdScrim.getAttribute('data-rid');
            var tdCheck = document.getElementById('rvd-td-check');
            var tdCode = document.getElementById('rvd-td-code');
            var tdReason = document.getElementById('rvd-td-reason');
            var tdSend = document.getElementById('rvd-td-send');
            var tdFb = document.getElementById('rvd-td-fb');
            function tdMessage(j, fallback){
                if (j && typeof j.data === 'string') return j.data;
                if (j && j.data && j.data.message) return j.data.message;
                return fallback;
            }
            function tdPrecheck(){
                tdSend.disabled = true;
                tdCheck.style.background = 'var(--elev)'; tdCheck.style.color = 'var(--text2)';
                tdCheck.textContent = 'A verificar se este lançamento pode ser retirado…';
                tdFb.textContent = '';
                var fd = new FormData(); fd.append('action','rmbz_takedown_precheck'); fd.append('nonce',<?php echo wp_json_encode( $rvd_nonce_distro ); ?>); fd.append('release_id',tdRid);
                fetch(ajaxUrl,{method:'POST',body:fd,credentials:'same-origin'}).then(function(r){ return r.json(); }).then(function(j){
                    if (!j || !j.success) throw new Error(tdMessage(j,'Não foi possível verificar este lançamento.'));
                    var d = j.data || {};
                    if (!d.eligible){
                        tdCheck.style.background = 'var(--rev-soft)'; tdCheck.style.color = 'var(--rev)';
                        tdCheck.textContent = 'Ainda não elegível. Faltam ' + (d.days_left || 0) + ' dia(s) para cumprir o prazo mínimo de ' + (d.min_days || 0) + ' dias nas lojas.';
                        return;
                    }
                    tdCheck.style.background = 'var(--success-soft)'; tdCheck.style.color = 'var(--success)';
                    tdCheck.textContent = d.has_holdings
                        ? 'Pedido permitido. Atenção: existem $ ' + Number(d.holdings_total || 0).toFixed(2) + ' retidos para colaboradores; a equipa irá rever esses valores.'
                        : 'Pedido permitido. Preenche o motivo para enviar à equipa.';
                    tdSend.disabled = false;
                }).catch(function(err){
                    tdCheck.style.background = 'var(--danger-soft)'; tdCheck.style.color = 'var(--danger)'; tdCheck.textContent = err.message;
                });
            }
            root.querySelectorAll('[data-dialog="rvd-td-scrim"]').forEach(function(b){ b.addEventListener('click', tdPrecheck); });
            tdSend.addEventListener('click', function(){
                var code = tdCode.value, reason = tdReason.value.trim();
                if (!code){ tdFb.style.color='var(--danger)'; tdFb.textContent='Seleciona o motivo do pedido.'; tdCode.focus(); return; }
                if (code === 'other' && reason.length < 10){ tdFb.style.color='var(--danger)'; tdFb.textContent='Explica o outro motivo com pelo menos 10 caracteres.'; tdReason.focus(); return; }
                tdSend.disabled = true; tdFb.style.color='var(--muted)'; tdFb.textContent='A enviar pedido…';
                var fd = new FormData(); fd.append('action','rmbz_request_takedown'); fd.append('nonce',<?php echo wp_json_encode( $rvd_nonce_distro ); ?>); fd.append('release_id',tdRid); fd.append('reason_code',code); fd.append('reason',reason);
                fetch(ajaxUrl,{method:'POST',body:fd,credentials:'same-origin'}).then(function(r){ return r.json(); }).then(function(j){
                    if (!j || !j.success) throw new Error(tdMessage(j,'Não foi possível enviar o pedido.'));
                    tdFb.style.color='var(--success)'; tdFb.textContent=tdMessage(j,'Pedido enviado para análise.');
                    setTimeout(function(){ location.reload(); },900);
                }).catch(function(err){ tdSend.disabled=false; tdFb.style.color='var(--danger)'; tdFb.textContent=err.message; });
            });
        }

        // Perfis nas lojas — guardar/limpar via AJAX (rmbz_artist_profile_save).
        var profWrap = document.getElementById('rvd-profiles');
        if (profWrap){
            var profNonce = profWrap.getAttribute('data-nonce') || '';
            function profSave(card, url){
                var dsp = card.getAttribute('data-dsp');
                var msg = card.querySelector('.rvd-prof-msg');
                var fd = new FormData(); fd.append('action','rmbz_artist_profile_save'); fd.append('nonce', profNonce); fd.append('dsp', dsp); fd.append('url', url);
                msg.style.display='block'; msg.style.color='var(--muted)'; msg.textContent='A guardar…';
                fetch(ajaxUrl, { method:'POST', body:fd, credentials:'same-origin' }).then(function(r){ return r.json(); }).then(function(j){
                    if (j && j.success){
                        msg.style.color='var(--success)'; msg.textContent = (j.data && j.data.message) || '✓ Guardado.';
                        var ok = card.querySelector('.rvd-prof-ok'), clr = card.querySelector('.rvd-prof-clear');
                        if (url){ if (ok) ok.style.display='inline'; if (clr) clr.style.display='inline-block'; card.style.borderColor='var(--success)'; }
                        else { if (ok) ok.style.display='none'; if (clr) clr.style.display='none'; card.style.borderColor='var(--border)'; }
                    } else { msg.style.color='var(--danger)'; msg.textContent = (j && j.data) ? (j.data.message || j.data) : 'Erro ao guardar.'; }
                }).catch(function(){ msg.style.color='var(--danger)'; msg.textContent='Falha de ligação.'; });
            }
            profWrap.querySelectorAll('.rvd-prof').forEach(function(card){
                var input = card.querySelector('.rvd-prof-url');
                var save = card.querySelector('.rvd-prof-save'), clear = card.querySelector('.rvd-prof-clear');
                if (save) save.addEventListener('click', function(){ profSave(card, input.value.trim()); });
                if (clear) clear.addEventListener('click', function(){ vipConfirm('Limpar este perfil?').then(function(ok){ if (!ok) return; input.value=''; profSave(card, ''); }); });
            });
        }

        /* ═══ [1.5.422] WIZARD NATIVO DE CRIAR LANÇAMENTO ═══ */
        var wz = root.querySelector('.rvd-view[data-dview="create"]');
        if (wz){
            var wzNonce = wz.getAttribute('data-nonce') || '';
            var wzUNonce = wz.getAttribute('data-unonce') || '';
            var wzType = 'single';
            var relIdEl = document.getElementById('rvw-release-id');
            var wzMsg = document.getElementById('rvw-msg');
            function wzShow(msg, ok){ wzMsg.style.display='block'; wzMsg.style.background = ok ? 'var(--success-soft)' : 'var(--danger-soft)'; wzMsg.style.color = ok ? 'var(--success)' : 'var(--danger)'; wzMsg.textContent = msg; wzMsg.scrollIntoView({behavior:'smooth',block:'nearest'}); }
            function wzHide(){ wzMsg.style.display='none'; }
            function wzStep(n){
                wz.querySelectorAll('.rvw-panel').forEach(function(p){ p.hidden = parseInt(p.getAttribute('data-step'),10) !== n; });
                wz.querySelectorAll('.rvw-step').forEach(function(s){ var i = parseInt(s.getAttribute('data-step'),10); var on = i === n, done = i < n; s.style.background = on ? 'var(--brand-soft)' : (done ? 'var(--success-soft)' : 'var(--elev)'); s.style.color = on ? 'var(--brand-ink)' : (done ? 'var(--success)' : 'var(--muted)'); });
                if (n === 4){ var licBox=document.getElementById('rvw-license-box'); if(licBox){ licBox.setAttribute('data-release-id',relIdEl.value||''); loadLicensePanel(licBox,true); } }
                wz.querySelector('.main') || root.querySelector('.main').scrollTo({top:0,behavior:'smooth'});
                wzHide();
            }
            // Tipo de lançamento
            wz.querySelectorAll('.rvw-type').forEach(function(c){ c.addEventListener('click', function(){ wzType = c.getAttribute('data-type'); wz.querySelectorAll('.rvw-type').forEach(function(o){ var on=o===c; o.style.borderColor = on?'var(--brand)':'var(--border)'; o.style.background = on?'var(--brand-soft)':'var(--elev)'; o.querySelector('input').checked = on; }); }); });
            wz.querySelectorAll('.rvw-back').forEach(function(b){ b.addEventListener('click', function(){ wzStep(parseInt(b.getAttribute('data-to'),10)); }); });

            function wzPost(fd){ return fetch(ajaxUrl, { method:'POST', body:fd, credentials:'same-origin' }).then(function(r){ return r.json(); }); }
            function wzErr(j){ return (j && j.data) ? (typeof j.data === 'string' ? j.data : (j.data.message || 'Erro.')) : 'Erro.'; }

            // PASSO 1 — guardar rascunho
            document.getElementById('rvw-next-1').addEventListener('click', function(){
                var title = document.getElementById('rvw-title').value.trim();
                var genre = document.getElementById('rvw-genre').value;
                var dateEl = wz.querySelector('input[name="release_date"]');
                var legEl = wz.querySelector('input[name="is_legacy"]');
                var date = dateEl ? dateEl.value : '';
                if (title.length < 2){ wzShow('Indica o título (mínimo 2 caracteres).'); return; }
                if (!genre){ wzShow('Escolhe o género.'); return; }
                if (!date){ wzShow('Escolhe a data de lançamento.'); return; }
                var btn = this; btn.disabled = true; btn.textContent = 'A guardar…';
                var fd = new FormData();
                fd.append('action','onemz_save_release_draft'); fd.append('nonce', wzNonce);
                fd.append('release_id', relIdEl.value || '0');
                fd.append('release_title', title);
                fd.append('language', document.getElementById('rvw-language').value);
                fd.append('primary_genre', genre);
                fd.append('release_type', wzType);
                fd.append('release_date', date);
                fd.append('is_legacy', (legEl && legEl.value === '1') ? '1' : '');
                fd.append('label_name', document.getElementById('rvw-label').value);
                fd.append('recording_location', document.getElementById('rvw-recloc').value);
                fd.append('upc_code', document.getElementById('rvw-upc').value);
                wzPost(fd).then(function(j){
                    btn.disabled = false; btn.textContent = 'Guardar e continuar';
                    if (j && j.success){ relIdEl.value = j.data.release_id; wzStep(2); }
                    else wzShow(wzErr(j));
                }).catch(function(){ btn.disabled=false; btn.textContent='Guardar e continuar'; wzShow('Falha de ligação.'); });
            });

            // PASSO 2 — territórios + lojas + exclusivos
            var terrMode = 'worldwide';
            function terrDsp(cb){ var l = cb.closest('label'); if (l){ l.style.borderColor = cb.checked ? 'var(--brand)' : 'var(--border)'; l.style.background = cb.checked ? 'var(--brand-soft)' : 'var(--elev)'; } }
            wz.querySelectorAll('.rvw-dsp-cb').forEach(function(cb){ terrDsp(cb); cb.addEventListener('change', function(){ terrDsp(cb); dspCount(); }); });
            function dspCount(){ var n = wz.querySelectorAll('.rvw-dsp-cb:checked').length, tot = wz.querySelectorAll('.rvw-dsp-cb').length; var el = document.getElementById('rvw-dsp-count'); if (el) el.textContent = n + ' de ' + tot + ' selecionadas'; }
            dspCount();
            wz.querySelectorAll('.rvw-dsp-all').forEach(function(b){ b.addEventListener('click', function(){
                var set = b.getAttribute('data-set');
                wz.querySelectorAll('.rvw-dsp-cb').forEach(function(cb){ cb.checked = (set === 'all') || (set === 'essential' && cb.getAttribute('data-tier') === '1'); terrDsp(cb); });
                dspCount();
            }); });
            // Territórios
            var terrCountriesBox = document.getElementById('rvw-terr-countries');
            var terrHint = document.getElementById('rvw-terr-hint');
            wz.querySelectorAll('.rvw-terr').forEach(function(b){ b.addEventListener('click', function(){
                terrMode = b.getAttribute('data-mode');
                document.getElementById('rvw-terr-mode').value = terrMode;
                wz.querySelectorAll('.rvw-terr').forEach(function(o){ var on=o===b; o.style.borderColor = on?'var(--brand)':'var(--border)'; o.style.background = on?'var(--brand-soft)':'var(--elev)'; });
                if (terrMode === 'worldwide'){ terrCountriesBox.style.display='none'; }
                else { terrCountriesBox.style.display='block'; terrHint.textContent = terrMode === 'worldwide_except' ? 'Marca os países a EXCLUIR (a obra sai em todo o mundo exceto estes).' : 'Marca APENAS os países onde queres lançar.'; }
            }); });
            wz.querySelectorAll('.rvw-region-all').forEach(function(ra){ ra.addEventListener('change', function(){
                wz.querySelectorAll('.rvw-terr-cc[data-region="'+ra.getAttribute('data-region')+'"]').forEach(function(cc){ cc.checked = ra.checked; });
            }); });
            document.getElementById('rvw-next-2').addEventListener('click', function(){
                var dsps = Array.prototype.map.call(wz.querySelectorAll('.rvw-dsp-cb:checked'), function(c){ return c.value; });
                if (!dsps.length){ wzShow('Escolhe pelo menos uma loja.'); return; }
                var terrs = [];
                if (terrMode !== 'worldwide'){
                    terrs = Array.prototype.map.call(wz.querySelectorAll('.rvw-terr-cc:checked'), function(c){ return c.value; });
                    if (terrMode === 'selected' && !terrs.length){ wzShow('Escolhe pelo menos um país (ou usa "Todo o mundo").'); return; }
                }
                var btn = this; btn.disabled = true; btn.textContent = 'A guardar…';
                var fd = new FormData();
                fd.append('action','rmbz_save_release_platforms'); fd.append('nonce', wzNonce);
                fd.append('release_id', relIdEl.value);
                fd.append('territory_mode', terrMode);
                terrs.forEach(function(t){ fd.append('territories[]', t); });
                dsps.forEach(function(d){ fd.append('dsps[]', d); });
                wz.querySelectorAll('.rvw-excl:checked').forEach(function(e){ fd.append(e.getAttribute('data-field'), '1'); });
                wzPost(fd).then(function(j){
                    btn.disabled = false; btn.textContent = 'Guardar e continuar';
                    if (j && j.success) wzStep(3); else wzShow(wzErr(j));
                }).catch(function(){ btn.disabled=false; btn.textContent='Guardar e continuar'; wzShow('Falha de ligação.'); });
            });

            // Serviços exclusivos — aviso obrigatório + contagem de 10s.
            var exclScrim = document.getElementById('rvw-excl-scrim');
            var exclTarget = null, exclTimer = null;
            function exclState(cb){ var st = cb.closest('.rvw-excl-row').querySelector('.rvw-excl-state'); if (st){ if (cb.checked){ st.textContent = '— solicitado ✅'; st.style.color = 'var(--success)'; } else { st.textContent = '— não solicitado'; st.style.color = 'var(--muted)'; } } }
            wz.querySelectorAll('.rvw-excl').forEach(function(cb){ exclState(cb); });
            function exclOpen(cb){
                exclTarget = cb;
                document.getElementById('rvw-excl-title').textContent = cb.getAttribute('data-name') || 'Serviço exclusivo';
                document.getElementById('rvw-excl-notice').textContent = cb.getAttribute('data-notice') || '';
                var acc = document.getElementById('rvw-excl-accept');
                var n = 10;
                // Recria SEMPRE o botão (o span da contagem é destruído quando um
                // aviso anterior é aceite — sem isto o 2.º modal rebentava).
                acc.disabled = true; acc.style.opacity = '.5';
                acc.innerHTML = 'Aguarda <span id="rvw-excl-cd">'+n+'</span>s…';
                clearInterval(exclTimer);
                exclTimer = setInterval(function(){
                    n--; var c = document.getElementById('rvw-excl-cd'); if (c) c.textContent = n;
                    if (n <= 0){ clearInterval(exclTimer); acc.disabled = false; acc.style.opacity = '1'; acc.textContent = '✅ Li e aceito'; }
                }, 1000);
                exclScrim.classList.add('open');
                document.getElementById('rvw-excl-notice').scrollTop = 0;
            }
            function exclClose(){ clearInterval(exclTimer); exclScrim.classList.remove('open'); exclTarget = null; }
            wz.querySelectorAll('.rvw-excl').forEach(function(cb){
                cb.addEventListener('click', function(e){ if (cb.checked){ e.preventDefault(); cb.checked = false; exclOpen(cb); } else { exclState(cb); } });
            });
            wz.querySelectorAll('.rvw-excl-read').forEach(function(b){ b.addEventListener('click', function(){ var cb = b.closest('.rvw-excl-row').querySelector('.rvw-excl'); if (cb.checked){ vipConfirm('Já está solicitado. Queres CANCELAR este serviço exclusivo?').then(function(ok){ if (ok){ cb.checked = false; exclState(cb); } }); } else { exclOpen(cb); } }); });
            exclScrim.querySelectorAll('.rvw-excl-x').forEach(function(x){ x.addEventListener('click', exclClose); });
            exclScrim.addEventListener('click', function(e){ if (e.target === exclScrim) exclClose(); });
            document.getElementById('rvw-excl-accept').addEventListener('click', function(){ if (this.disabled) return; if (exclTarget){ exclTarget.checked = true; exclState(exclTarget); } exclClose(); });

            // PASSO 3 — upload de faixa + gravar + lista
            var tracks = []; // {id, title, songwriter, explicit, name}
            var dz = document.getElementById('rvw-audio-dz');
            var dzInput = dz.querySelector('.rvw-audio-input');
            var dzIdle = dz.querySelector('.rvu-audio-idle'), dzProg = dz.querySelector('.rvu-audio-prog');
            var dzBar = dz.querySelector('.rvw-audio-bar'), dzPct = dz.querySelector('.rvw-audio-pct');
            dz.addEventListener('click', function(){ if (dzProg.style.display === 'none') dzInput.click(); });
            function dzReset(){ dzIdle.style.display='block'; dzProg.style.display='none'; dzBar.style.width='0%'; dzPct.textContent='0%'; dzInput.value=''; }
            // [1.5.434] Metadata COMPLETA por faixa (espelha o editor do módulo).
            function defMeta(){ return { language:'Portuguese', isrc_code:'', is_instrumental:0, collaborators:[], songwriters:[], has_lyrics:0, lyrics:'', previously_released:0, original_isrc:'', is_cover:0, cover_original_title:'', cover_original_composer:'', preview_start_seconds:0, moods:[], splits:[], duration:0 }; }
            function trackMissing(t){
                var miss = [];
                if (!(t.title||'').trim()) miss.push('título');
                var m = t.meta;
                var hasSw = (m && (m.songwriters||[]).some(function(s){ return (s.name||'').trim() !== ''; })) || (t.songwriter||'').trim() !== '';
                if (!hasSw) miss.push('compositor');
                if (m){
                    if (m.has_lyrics && !(m.lyrics||'').trim()) miss.push('letra');
                    if (m.is_cover && (!(m.cover_original_title||'').trim() || !(m.cover_original_composer||'').trim())) miss.push('dados do cover');
                    if (m.previously_released && String(m.original_isrc||'').replace(/[^A-Za-z0-9]/g,'').length !== 12) miss.push('ISRC original');
                }
                return miss;
            }
            function fmtDur(s){ s = parseInt(s,10)||0; return s > 0 ? Math.floor(s/60) + ':' + ('0'+(s%60)).slice(-2) : '--:--'; }
            function wzEsc(v){ var d=document.createElement('div'); d.textContent=String(v||''); return d.innerHTML; }
            function renderTracks(){
                var wrap = document.getElementById('rvw-tracks');
                wrap.innerHTML = '';
                tracks.forEach(function(t, i){
                    var row = document.createElement('div');
                    row.style.cssText = 'border:1px solid var(--border); border-radius:14px; padding:12px 14px; background:var(--elev);';
                    var miss = trackMissing(t);
                    var isrcTxt = (t.meta && t.meta.isrc_code) ? t.meta.isrc_code : 'pendente';
                    var durTxt = (t.meta && t.meta.duration) ? ' · ' + fmtDur(t.meta.duration) : '';
                    var audio = t.url ? '<audio controls preload="none" src="'+wzEsc(t.url)+'" style="width:100%; height:34px; margin:0 0 9px;"></audio>' : '';
                    row.innerHTML = audio +
                        '<div style="display:flex; align-items:center; gap:10px; margin-bottom:8px;"><span style="font-weight:800; color:var(--muted);">'+(i+1)+'.</span>'
                        + '<span style="flex:1; font-size:12px; color:var(--muted); white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">🎵 '+ wzEsc(t.name||'') +' <span style="opacity:.75;">· ISRC: '+ wzEsc(isrcTxt) + durTxt +'</span></span>'
                        + '<button type="button" class="chip rvw-tup" aria-label="Mover para cima" '+(i===0?'disabled':'')+' style="padding:6px 9px;">↑</button>'
                        + '<button type="button" class="chip rvw-tdown" aria-label="Mover para baixo" '+(i===tracks.length-1?'disabled':'')+' style="padding:6px 9px;">↓</button>'
                        + '<button type="button" class="chip rvw-tdet" style="padding:6px 12px; border-color:var(--brand); color:var(--brand-ink);">✏️ Detalhes</button>'
                        + '<button type="button" class="chip rvw-tdel" style="padding:6px 10px;">✕</button></div>'
                        + '<input class="inp rvw-ttitle" placeholder="Título da faixa *" value="'+ wzEsc(t.title||'') +'" style="font-size:13px;">'
                        + '<input class="inp rvw-tsw" placeholder="Compositor / autor da letra *" value="'+ wzEsc(t.songwriter||'') +'" style="font-size:13px; margin-top:8px;">'
                        + '<div style="display:flex; align-items:center; gap:10px; margin-top:8px;">'
                        + '<label style="display:flex; gap:8px; align-items:center; font-size:12px; cursor:pointer;"><input type="checkbox" class="rvw-texp" '+(t.explicit?'checked':'')+'> Conteúdo explícito</label>'
                        + '<span style="flex:1;"></span>'
                        + '<span class="rvw-tstate" style="font-size:11.5px; font-weight:700; color:'+ (miss.length ? 'var(--rev)' : 'var(--success)') +';">'+ (miss.length ? '⚠ Falta: '+miss.join(', ') : '✓ Pronta para distribuição') +'</span></div>';
                    var tt = row.querySelector('.rvw-ttitle'), sw = row.querySelector('.rvw-tsw'), ex = row.querySelector('.rvw-texp');
                    function saveMeta(){
                        t.title = tt.value.trim(); t.songwriter = sw.value.trim(); t.explicit = ex.checked;
                        // sincroniza o compositor rápido com a lista completa do modal
                        var m = t.meta || (t.meta = defMeta());
                        if (t.songwriter){ if (m.songwriters.length) m.songwriters[0].name = t.songwriter; else m.songwriters = [{name:t.songwriter}]; }
                        wzSaveTrackMeta(t);
                        var ms = trackMissing(t); var st = row.querySelector('.rvw-tstate');
                        st.style.color = ms.length ? 'var(--rev)' : 'var(--success)';
                        st.textContent = ms.length ? '⚠ Falta: '+ms.join(', ') : '✓ Pronta para distribuição';
                    }
                    tt.addEventListener('blur', saveMeta); sw.addEventListener('blur', saveMeta); ex.addEventListener('change', saveMeta);
                    row.querySelector('.rvw-tdet').addEventListener('click', function(){ rvtOpen(t); });
                    row.querySelector('.rvw-tdel').addEventListener('click', function(){ wzDeleteTrack(t, i); });
                    row.querySelector('.rvw-tup').addEventListener('click', function(){ if (i > 0) wzReorderTrack(t, i, 'up'); });
                    row.querySelector('.rvw-tdown').addEventListener('click', function(){ if (i < tracks.length-1) wzReorderTrack(t, i, 'down'); });
                    wrap.appendChild(row);
                });
            }
            dzInput.addEventListener('change', function(){
                var f = dzInput.files[0]; if (!f) return;
                if (f.size > 200*1024*1024){ wzShow('O áudio excede 200 MB.'); dzInput.value=''; return; }
                dzIdle.style.display='none'; dzProg.style.display='block'; wzHide();
                var fd = new FormData(); fd.append('action','onemz_upload_music_chunk'); fd.append('nonce', wzUNonce); fd.append('is_distro_track','1'); fd.append('music_file', f);
                var xhr = new XMLHttpRequest(); xhr.open('POST', ajaxUrl, true);
                xhr.upload.onprogress = function(e){ if (e.lengthComputable){ var p = Math.round(e.loaded/e.total*100); dzBar.style.width=p+'%'; dzPct.textContent=p+'%'; } };
                xhr.onload = function(){
                    var j = null; try { j = JSON.parse(xhr.responseText); } catch(e){}
                    if (j && j.success){
                        // encadeia save_distro_track
                        var fd2 = new FormData(); fd2.append('action','onemz_save_distro_track'); fd2.append('nonce', wzNonce); fd2.append('release_id', relIdEl.value); fd2.append('track_title','');
                        if (j.data.upload_token) fd2.append('upload_token', j.data.upload_token); else fd2.append('file_url', j.data.url);
                        if (!j.data.upload_token && j.data.audio_info) fd2.append('audio_info', JSON.stringify(j.data.audio_info));
                        wzPost(fd2).then(function(k){
                            dzReset();
                            if (k && k.success){ tracks.push({ id:k.data.track_id, title:'', songwriter:'', explicit:false, name:f.name, url:j.data.url||'', loaded:true, meta:defMeta() }); renderTracks(); }
                            else wzShow(wzErr(k));
                        }).catch(function(){ dzReset(); wzShow('Falha ao guardar a faixa.'); });
                    } else { dzReset(); wzShow(wzErr(j) || 'Falha no upload do áudio.'); }
                };
                xhr.onerror = function(){ dzReset(); wzShow('Falha de ligação no upload.'); };
                xhr.send(fd);
            });
            // [1.5.434] Payload COMPLETO (o handler reconstrói o extra_data
            // inteiro a partir do payload — mandar só parte apagava o resto).
            function wzTrackPayload(t){
                var m = t.meta || (t.meta = defMeta());
                var sws = (m.songwriters && m.songwriters.length) ? m.songwriters : (t.songwriter ? [{name:t.songwriter}] : []);
                return {
                    track_id: t.id, release_id: parseInt(relIdEl.value,10),
                    track_title: t.title||'', isrc_code: m.isrc_code||'',
                    is_explicit: t.explicit?1:0, is_instrumental: m.is_instrumental?1:0,
                    language: m.language||'Portuguese',
                    collaborators: m.collaborators||[], songwriters: sws,
                    has_lyrics: m.has_lyrics?1:0, lyrics: m.lyrics||'',
                    previously_released: m.previously_released?1:0, original_isrc: m.original_isrc||'',
                    is_cover: m.is_cover?1:0, cover_original_title: m.cover_original_title||'', cover_original_composer: m.cover_original_composer||'',
                    preview_start_seconds: parseInt(m.preview_start_seconds,10)||0,
                    moods: m.moods||[], splits: m.splits||[]
                };
            }
            function wzSaveTrackMeta(t){
                if (!t.id) return Promise.resolve(null);
                var fd = new FormData(); fd.append('action','rmbz_track_editor_save'); fd.append('nonce', wzNonce); fd.append('payload', JSON.stringify(wzTrackPayload(t)));
                return wzPost(fd); // best-effort; validação forte é na finalização
            }

            // ═══ [1.5.434] MODAL "DETALHES DA FAIXA" (4 tabs, nativo) ═══
            var rvtScrim = document.getElementById('rvt-scrim');
            var rvtCur = null;
            var RVT_ROLES = <?php echo wp_json_encode( $rvt_roles ); ?>;
            function rvtEl(id){ return document.getElementById(id); }
            function rvtTab(name){
                rvtScrim.querySelectorAll('.rvt-pane').forEach(function(p){ p.hidden = p.getAttribute('data-t') !== name; });
                rvtScrim.querySelectorAll('.rvt-tab').forEach(function(b){
                    var on = b.getAttribute('data-t') === name;
                    b.style.background = on ? 'var(--brand-soft)' : 'transparent';
                    b.style.color = on ? 'var(--brand-ink)' : 'var(--text2)';
                });
            }
            rvtScrim.querySelectorAll('.rvt-tab').forEach(function(b){ b.addEventListener('click', function(){ rvtTab(b.getAttribute('data-t')); }); });
            rvtScrim.querySelectorAll('.rvt-x').forEach(function(b){ b.addEventListener('click', function(){ rvtScrim.classList.remove('open'); }); });
            rvtScrim.addEventListener('click', function(e){ if (e.target === rvtScrim) rvtScrim.classList.remove('open'); });
            // linhas dinâmicas
            function rvtRowShell(){ var d = document.createElement('div'); d.style.cssText = 'display:flex; gap:8px; align-items:center;'; return d; }
            function rvtDelBtn(d){ var x = document.createElement('button'); x.type='button'; x.className='chip'; x.textContent='✕'; x.style.padding='6px 10px'; x.addEventListener('click', function(){ d.remove(); rvtSplitsTotal(); }); return x; }
            function rvtSwRow(v){
                var d = rvtRowShell();
                var i = document.createElement('input'); i.className='inp rvt-sw-name'; i.placeholder='Nome do compositor'; i.value = (v && v.name) || ''; i.style.cssText='font-size:13px; flex:1;';
                d.appendChild(i); d.appendChild(rvtDelBtn(d)); return d;
            }
            function rvtCollabRow(v){
                var d = rvtRowShell();
                var i = document.createElement('input'); i.className='inp rvt-co-name'; i.placeholder='Nome'; i.value = (v && v.name) || ''; i.style.cssText='font-size:13px; flex:1;';
                var s = document.createElement('select'); s.className='inp rvt-co-role'; s.style.cssText='font-size:13px; max-width:200px;';
                Object.keys(RVT_ROLES).forEach(function(k){ var o=document.createElement('option'); o.value=k; o.textContent=RVT_ROLES[k]; s.appendChild(o); });
                s.value = (v && v.role && RVT_ROLES[v.role]) ? v.role : 'feature';
                d.appendChild(i); d.appendChild(s); d.appendChild(rvtDelBtn(d)); return d;
            }
            function rvtSplitRow(v){
                var d = rvtRowShell();
                var n = document.createElement('input'); n.className='inp rvt-sp-name'; n.placeholder='Nome'; n.value=(v&&v.name)||''; n.style.cssText='font-size:13px; flex:1.2;';
                var tl = document.createElement('input'); tl.className='inp rvt-sp-tel'; tl.placeholder='Telemóvel (ex: 258…)'; tl.value=(v&&v.telemovel)||''; tl.style.cssText='font-size:13px; flex:1;';
                var p = document.createElement('input'); p.className='inp rvt-sp-pct'; p.type='number'; p.min='0'; p.max='100'; p.step='0.01'; p.placeholder='%'; p.value=(v&&v.percentage)||''; p.style.cssText='font-size:13px; width:90px;';
                p.addEventListener('input', rvtSplitsTotal);
                d.appendChild(n); d.appendChild(tl); d.appendChild(p); d.appendChild(rvtDelBtn(d)); return d;
            }
            function rvtSplitsTotal(){
                var tot = 0; rvtScrim.querySelectorAll('.rvt-sp-pct').forEach(function(p){ tot += parseFloat(p.value)||0; });
                var el = rvtEl('rvt-splits-total');
                if (!rvtScrim.querySelectorAll('.rvt-sp-pct').length){ el.textContent = ''; return; }
                el.textContent = 'Total: ' + (Math.round(tot*100)/100) + '%';
                el.style.color = Math.abs(tot-100) <= 0.01 ? 'var(--success)' : 'var(--danger)';
            }
            rvtEl('rvt-sw-add').addEventListener('click', function(){ rvtEl('rvt-sw-list').appendChild(rvtSwRow(null)); });
            rvtEl('rvt-collab-add').addEventListener('click', function(){ rvtEl('rvt-collab-list').appendChild(rvtCollabRow(null)); });
            rvtEl('rvt-split-add').addEventListener('click', function(){ rvtEl('rvt-splits-list').appendChild(rvtSplitRow(null)); rvtSplitsTotal(); });
            // toggles condicionais
            rvtEl('rvt-haslyrics').addEventListener('change', function(){ rvtEl('rvt-lyrics-wrap').hidden = !this.checked; });
            rvtEl('rvt-prev').addEventListener('change', function(){ rvtEl('rvt-prev-wrap').hidden = !this.checked; });
            rvtEl('rvt-iscover').addEventListener('change', function(){ rvtEl('rvt-cover-wrap').hidden = !this.checked; });
            rvtEl('rvt-inst').addEventListener('change', function(){ if (this.checked){ rvtEl('rvt-haslyrics').checked = false; rvtEl('rvt-lyrics-wrap').hidden = true; } });
            // moods (máx. 5)
            rvtScrim.querySelectorAll('.rvt-mood').forEach(function(ch){
                ch.addEventListener('click', function(){
                    var on = ch.classList.contains('on');
                    if (!on && rvtScrim.querySelectorAll('.rvt-mood.on').length >= 5) return;
                    ch.classList.toggle('on', !on);
                    ch.style.background = !on ? 'var(--brand-soft)' : '';
                    ch.style.borderColor = !on ? 'var(--brand)' : '';
                    ch.style.color = !on ? 'var(--brand-ink)' : '';
                });
            });
            function rvtFill(t){
                var m = t.meta || (t.meta = defMeta());
                rvtEl('rvt-title').value = t.title||'';
                rvtEl('rvt-lang').value = m.language||'Portuguese';
                rvtEl('rvt-dur').textContent = fmtDur(m.duration);
                rvtEl('rvt-isrc').value = m.isrc_code||'';
                rvtEl('rvt-exp').checked = !!t.explicit;
                rvtEl('rvt-inst').checked = !!m.is_instrumental;
                var swl = rvtEl('rvt-sw-list'); swl.innerHTML='';
                (m.songwriters.length ? m.songwriters : (t.songwriter ? [{name:t.songwriter}] : [{name:''}])).forEach(function(s){ swl.appendChild(rvtSwRow(s)); });
                var col = rvtEl('rvt-collab-list'); col.innerHTML='';
                (m.collaborators||[]).forEach(function(c){ col.appendChild(rvtCollabRow(c)); });
                rvtEl('rvt-haslyrics').checked = !!m.has_lyrics; rvtEl('rvt-lyrics-wrap').hidden = !m.has_lyrics; rvtEl('rvt-lyrics').value = m.lyrics||'';
                rvtEl('rvt-prev').checked = !!m.previously_released; rvtEl('rvt-prev-wrap').hidden = !m.previously_released; rvtEl('rvt-origisrc').value = m.original_isrc||'';
                rvtEl('rvt-iscover').checked = !!m.is_cover; rvtEl('rvt-cover-wrap').hidden = !m.is_cover;
                rvtEl('rvt-covertitle').value = m.cover_original_title||''; rvtEl('rvt-covercomposer').value = m.cover_original_composer||'';
                var spl = rvtEl('rvt-splits-list'); spl.innerHTML='';
                (m.splits||[]).forEach(function(s){ spl.appendChild(rvtSplitRow(s)); });
                rvtSplitsTotal();
                rvtEl('rvt-preview').value = m.preview_start_seconds||'';
                rvtScrim.querySelectorAll('.rvt-mood').forEach(function(ch){
                    var on = (m.moods||[]).indexOf(ch.getAttribute('data-mood')) !== -1;
                    ch.classList.toggle('on', on);
                    ch.style.background = on ? 'var(--brand-soft)' : '';
                    ch.style.borderColor = on ? 'var(--brand)' : '';
                    ch.style.color = on ? 'var(--brand-ink)' : '';
                });
            }
            function rvtOpen(t){
                rvtCur = t; rvtTab('basic'); rvtFill(t); rvtScrim.classList.add('open');
                if (!t.loaded && t.id){
                    var fd = new FormData(); fd.append('action','rmbz_track_editor_load'); fd.append('nonce', wzNonce); fd.append('track_id', t.id);
                    wzPost(fd).then(function(j){
                        if (!(j && j.success && j.data)) return;
                        t.loaded = true;
                        var tr = j.data.track||{}, ex = j.data.extra||{}, sp = j.data.splits||[];
                        var m = t.meta;
                        if (tr.track_title && !t.title) t.title = tr.track_title;
                        t.explicit = String(tr.is_explicit) === '1' || tr.is_explicit === 1 || t.explicit;
                        m.isrc_code = tr.isrc_code||m.isrc_code;
                        m.language = ex.language||m.language;
                        m.duration = parseInt(ex.duration_seconds,10)||m.duration;
                        m.is_instrumental = ex.is_instrumental?1:0;
                        m.collaborators = ex.collaborators||[];
                        if (ex.songwriters && ex.songwriters.length) m.songwriters = ex.songwriters;
                        m.has_lyrics = ex.has_lyrics?1:0; m.lyrics = ex.lyrics||'';
                        m.previously_released = ex.previously_released?1:0; m.original_isrc = ex.original_isrc||'';
                        m.is_cover = ex.is_cover?1:0; m.cover_original_title = ex.cover_original_title||''; m.cover_original_composer = ex.cover_original_composer||'';
                        m.preview_start_seconds = parseInt(ex.preview_start_seconds,10)||0;
                        m.moods = ex.moods||[];
                        m.splits = sp.map(function(s){ return { name:s.collaborator_name||'', telemovel:s.collaborator_telemovel||'', percentage:parseFloat(s.percentage)||0, role:s.role||'feature' }; });
                        if (rvtCur === t) rvtFill(t);
                    });
                }
            }
            rvtEl('rvt-save').addEventListener('click', function(){
                var t = rvtCur; if (!t) return;
                var m = t.meta || (t.meta = defMeta());
                var title = rvtEl('rvt-title').value.trim();
                if (!title){ vipAlert('O título da faixa é obrigatório.'); rvtTab('basic'); return; }
                // splits têm de somar 100% (se existirem)
                var splits = [];
                rvtEl('rvt-splits-list').querySelectorAll(':scope > div').forEach(function(d){
                    var pct = parseFloat(d.querySelector('.rvt-sp-pct').value)||0;
                    if (pct <= 0) return;
                    splits.push({ name:d.querySelector('.rvt-sp-name').value.trim(), telemovel:d.querySelector('.rvt-sp-tel').value.trim(), percentage:pct, role:'feature' });
                });
                if (splits.length){ var tot = splits.reduce(function(a,s){ return a+s.percentage; },0); if (Math.abs(tot-100) > 0.01){ vipAlert('Os splits têm de somar 100% (atual: '+(Math.round(tot*100)/100)+'%).'); rvtTab('splits'); return; } }
                t.title = title;
                t.explicit = rvtEl('rvt-exp').checked;
                m.language = rvtEl('rvt-lang').value;
                m.isrc_code = rvtEl('rvt-isrc').value.trim();
                m.is_instrumental = rvtEl('rvt-inst').checked?1:0;
                m.songwriters = [];
                rvtEl('rvt-sw-list').querySelectorAll('.rvt-sw-name').forEach(function(i){ if (i.value.trim()) m.songwriters.push({name:i.value.trim()}); });
                m.collaborators = [];
                rvtEl('rvt-collab-list').querySelectorAll(':scope > div').forEach(function(d){ var n=d.querySelector('.rvt-co-name').value.trim(); if (n) m.collaborators.push({ name:n, role:d.querySelector('.rvt-co-role').value }); });
                m.has_lyrics = rvtEl('rvt-haslyrics').checked?1:0; m.lyrics = rvtEl('rvt-lyrics').value;
                m.previously_released = rvtEl('rvt-prev').checked?1:0; m.original_isrc = rvtEl('rvt-origisrc').value.trim();
                m.is_cover = rvtEl('rvt-iscover').checked?1:0;
                m.cover_original_title = rvtEl('rvt-covertitle').value.trim(); m.cover_original_composer = rvtEl('rvt-covercomposer').value.trim();
                m.preview_start_seconds = parseInt(rvtEl('rvt-preview').value,10)||0;
                m.moods = []; rvtScrim.querySelectorAll('.rvt-mood.on').forEach(function(ch){ m.moods.push(ch.getAttribute('data-mood')); });
                m.splits = splits;
                t.songwriter = m.songwriters.length ? m.songwriters[0].name : '';
                var btn = rvtEl('rvt-save'); btn.disabled = true; btn.textContent = 'A guardar…';
                wzSaveTrackMeta(t).then(function(j){
                    btn.disabled = false; btn.textContent = 'Guardar detalhes';
                    if (j && j.success){ rvtScrim.classList.remove('open'); renderTracks(); }
                    else vipAlert((j && j.data && (j.data.message||j.data)) || 'Falha ao guardar os detalhes.');
                }).catch(function(){ btn.disabled = false; btn.textContent = 'Guardar detalhes'; vipAlert('Falha de ligação.'); });
            });
            function wzDeleteTrack(t, i){
                vipConfirm('Apagar esta faixa?').then(function(ok){
                    if (!ok) return;
                    var fd = new FormData(); fd.append('action','onemz_delete_distro_track'); fd.append('nonce', wzNonce); fd.append('track_id', t.id);
                    wzPost(fd).then(function(j){ if (j && j.success){ tracks.splice(i,1); renderTracks(); } else wzShow(wzErr(j)); });
                });
            }
            function wzReorderTrack(t, i, direction){
                var fd = new FormData(); fd.append('action','onemz_reorder_distro_track'); fd.append('nonce', wzNonce); fd.append('track_id', t.id); fd.append('direction', direction);
                wzPost(fd).then(function(j){
                    if (!j || !j.success){ wzShow(wzErr(j)); return; }
                    var target = direction === 'up' ? i-1 : i+1;
                    var moved = tracks.splice(i,1)[0]; tracks.splice(target,0,moved); renderTracks();
                }).catch(function(){ wzShow('Falha ao guardar a ordem das faixas.'); });
            }
            document.getElementById('rvw-next-3').addEventListener('click', function(){
                if (!tracks.length){ wzShow('Adiciona pelo menos uma faixa.'); return; }
                // Sincroniza os inputs (caso não tenha havido blur) e valida.
                var rows = document.getElementById('rvw-tracks').children;
                for (var i=0;i<tracks.length;i++){
                    var r = rows[i]; if (!r) continue;
                    tracks[i].title = r.querySelector('.rvw-ttitle').value.trim();
                    tracks[i].songwriter = r.querySelector('.rvw-tsw').value.trim();
                    tracks[i].explicit = r.querySelector('.rvw-texp').checked;
                    var m = tracks[i].meta || (tracks[i].meta = defMeta());
                    if (tracks[i].songwriter){ if (m.songwriters.length) m.songwriters[0].name = tracks[i].songwriter; else m.songwriters = [{name:tracks[i].songwriter}]; }
                }
                for (var j=0;j<tracks.length;j++){ var missing=trackMissing(tracks[j]); if (missing.length){ wzShow('Faixa '+(j+1)+': falta '+missing.join(', ')+'.'); return; } }
                var nextBtn = this; nextBtn.disabled = true; nextBtn.textContent = 'A guardar faixas…';
                Promise.all(tracks.map(wzSaveTrackMeta)).then(function(results){
                    var failed = results.find(function(result){ return !result || !result.success; });
                    if (failed) throw new Error(wzErr(failed));
                    wzStep(4);
                }).catch(function(err){ wzShow(err.message || 'Falha ao guardar as faixas.'); }).then(function(){ nextBtn.disabled=false; nextBtn.textContent='Guardar faixas e continuar'; });
            });

            // PASSO 4 — capa + finalizar
            var cdz = document.getElementById('rvw-cover-dz'), cInput = document.getElementById('rvw-cover-input'), cPrev = document.getElementById('rvw-cover-prev'), finBtn = document.getElementById('rvw-finalize');
            cdz.addEventListener('click', function(){ cInput.click(); });
            cInput.addEventListener('change', function(){
                var f = cInput.files[0]; if (!f) return;
                if (['image/jpeg','image/png'].indexOf(f.type) === -1){ wzShow('A capa tem de ser JPG ou PNG.'); return; }
                if (f.size < 100*1024){ wzShow('A capa é demasiado pequena (mín. 100 KB).'); return; }
                if (f.size > 10*1024*1024){ wzShow('A capa excede 10 MB.'); return; }
                var img = new Image(); img.onload = function(){
                    if (img.width < 1400 || img.height < 1400){ wzShow('A capa tem de ter no mínimo 1400×1400 px.'); return; }
                    if (Math.abs(img.width - img.height) > img.width*0.02){ wzShow('A capa tem de ser quadrada (1:1).'); return; }
                    // upload
                    cPrev.style.display='block'; cPrev.innerHTML = '<div style="color:var(--muted);">A enviar capa…</div>';
                    var fd = new FormData(); fd.append('action','rmbz_upload_release_cover'); fd.append('nonce', wzNonce); fd.append('release_id', relIdEl.value); fd.append('cover_art_file', f);
                    wzPost(fd).then(function(j){
                        if (j && j.success){ cPrev.innerHTML = '<img src="'+j.data.url+'"><div>✅ Capa carregada ('+ (j.data.dimensions||'') +')</div>'; finBtn.disabled = false; }
                        else { cPrev.style.display='none'; wzShow(wzErr(j)); }
                    }).catch(function(){ cPrev.style.display='none'; wzShow('Falha ao enviar a capa.'); });
                }; img.onerror = function(){ wzShow('Não foi possível ler a imagem.'); };
                img.src = URL.createObjectURL(f);
            });
            finBtn.addEventListener('click', function(){
                vipConfirm('🚀 Enviar o lançamento para revisão da equipa 1MZ?').then(function(ok){
                if (!ok) return;
                finBtn.disabled = true; finBtn.textContent = 'A enviar…';
                // 1) re-guardar rascunho (edições finais) 2) finalizar
                var fd1 = new FormData();
                fd1.append('action','onemz_save_release_draft'); fd1.append('nonce', wzNonce); fd1.append('release_id', relIdEl.value);
                fd1.append('release_title', document.getElementById('rvw-title').value.trim());
                fd1.append('language', document.getElementById('rvw-language').value);
                fd1.append('primary_genre', document.getElementById('rvw-genre').value);
                fd1.append('release_type', wzType);
                var d2 = wz.querySelector('input[name="release_date"]'), l2 = wz.querySelector('input[name="is_legacy"]');
                fd1.append('release_date', d2 ? d2.value : '');
                fd1.append('is_legacy', (l2 && l2.value === '1') ? '1' : '');
                fd1.append('label_name', document.getElementById('rvw-label').value);
                fd1.append('recording_location', document.getElementById('rvw-recloc').value);
                fd1.append('upc_code', document.getElementById('rvw-upc').value);
                Promise.all(tracks.map(wzSaveTrackMeta)).then(function(results){
                    var failed = results.find(function(result){ return !result || !result.success; });
                    if (failed) throw new Error(wzErr(failed));
                    return wzPost(fd1);
                }).then(function(saved){
                    if (!saved || !saved.success) {
                        finBtn.disabled = false;
                        finBtn.textContent = '🚀 Finalizar e enviar para as lojas';
                        wzShow(wzErr(saved));
                        return null;
                    }
                    var fd2 = new FormData(); fd2.append('action','onemz_finalize_release'); fd2.append('nonce', wzNonce); fd2.append('release_id', relIdEl.value);
                    return wzPost(fd2);
                }).then(function(j){
                    if (!j) return;
                    finBtn.disabled = false; finBtn.textContent = '🚀 Finalizar e enviar para as lojas';
                    if (j && j.success){ vipAlert('✅ Lançamento enviado para revisão!\n\nA equipa 1MZ vai validar tudo e envia para as lojas. Recebes uma notificação quando estiver aprovado.').then(function(){ showSplash(); location.href = <?php echo wp_json_encode( home_url( '/minha-conta/?sect=distro' ) ); ?>; }); }
                    else wzShow(wzErr(j));
                }).catch(function(err){ finBtn.disabled=false; finBtn.textContent='🚀 Finalizar e enviar para as lojas'; wzShow((err && err.message) || 'Falha ao finalizar.'); });
                });
            });

            // [1.5.426] MODO EDIÇÃO — pré-preenche o wizard com o rascunho.
            (function(){
                var raw = wz.getAttribute('data-edit'); if (!raw) return;
                var ed; try { ed = JSON.parse(raw); } catch(e){ return; }
                if (!ed || !ed.id) return;
                relIdEl.value = ed.id;
                document.getElementById('rvw-title').value = ed.title || '';
                if (ed.language) document.getElementById('rvw-language').value = ed.language;
                if (ed.genre) document.getElementById('rvw-genre').value = ed.genre;
                document.getElementById('rvw-label').value = ed.label || '';
                document.getElementById('rvw-recloc').value = ed.recloc || '';
                document.getElementById('rvw-upc').value = ed.upc || '';
                // tipo
                if (ed.type){ wzType = ed.type; wz.querySelectorAll('.rvw-type').forEach(function(o){ var on = o.getAttribute('data-type') === ed.type; o.style.borderColor = on?'var(--brand)':'var(--border)'; o.style.background = on?'var(--brand-soft)':'var(--elev)'; o.querySelector('input').checked = on; }); }
                // data
                var dEl = wz.querySelector('input[name="release_date"]'); if (dEl && ed.date){ dEl.value = ed.date; dEl.dispatchEvent(new Event('change')); }
                var lEl = wz.querySelector('input[name="is_legacy"]'); if (lEl) lEl.value = ed.legacy ? '1' : '';
                // lojas
                if (ed.dsps && ed.dsps.length){ wz.querySelectorAll('.rvw-dsp-cb').forEach(function(cb){ cb.checked = ed.dsps.indexOf(cb.value) > -1; if (typeof terrDsp === 'function') terrDsp(cb); }); if (typeof dspCount === 'function') dspCount(); }
                // territórios
                if (ed.terr_mode && ed.terr_mode !== 'worldwide'){ var tbtn = wz.querySelector('.rvw-terr[data-mode="'+ed.terr_mode+'"]'); if (tbtn) tbtn.click(); (ed.terr||[]).forEach(function(cc){ var el = wz.querySelector('.rvw-terr-cc[value="'+cc+'"]'); if (el) el.checked = true; }); }
                // exclusivos
                if (ed.yt){ var y = wz.querySelector('.rvw-excl[data-field="yt_content_id_optin"]'); if (y) y.checked = true; }
                if (ed.fb){ var fbx = wz.querySelector('.rvw-excl[data-field="fb_monet_optin"]'); if (fbx) fbx.checked = true; }
                if (ed.tt){ var t = wz.querySelector('.rvw-excl[data-field="tt_monet_optin"]'); if (t) t.checked = true; }
                // faixas
                if (ed.tracks && ed.tracks.length){ ed.tracks.forEach(function(t){ tracks.push({ id:t.id, title:t.title||'', songwriter:t.songwriter||'', explicit:!!t.explicit, name:t.name||'faixa', url:t.url||'', loaded:true, meta:t.meta||defMeta() }); }); renderTracks(); }
                // capa
                if (ed.cover){ cPrev.style.display='block'; cPrev.innerHTML = '<img src="'+ed.cover+'"><div>✅ Capa atual</div>'; finBtn.disabled = false; }
                // abre a secção e a vista de criação
                rvdView('create'); wzStep(1);
            })();
        }

        // Deep-link: ?sect=projetos abre logo essa secção. E ?dview= abre a
        // sub-vista certa da Distribuição.
        try {
            var qs = new URLSearchParams(location.search);
            var q = qs.get('sect'); if (q && titles[q]) go(q);
            var dv = qs.get('dview'); if (dv) rvdView(dv);
        } catch (e) {}

        // ═══ [1.5.437] CONTENT ID nativo — mesmo fluxo do módulo antigo ═══
        var cidScrim = document.getElementById('rvd-cid-scrim');
        if (cidScrim){
            var cidNonce = cidScrim.getAttribute('data-nonce'), cidRid = cidScrim.getAttribute('data-rid');
            var cidUrl = document.getElementById('rvd-cid-url'), cidReason = document.getElementById('rvd-cid-reason');
            var cidFb = document.getElementById('rvd-cid-fb'), cidWarn = document.getElementById('rvd-cid-warn');
            var cidSend = document.getElementById('rvd-cid-send'), cidAll = document.getElementById('rvd-cid-all');
            var cidOpenBtn = document.getElementById('rvd-cid-open');
            if (cidOpenBtn) cidOpenBtn.addEventListener('click', function(){
                cidUrl.value=''; cidReason.value=''; cidFb.textContent=''; cidFb.style.color='var(--danger)'; cidWarn.hidden=true;
                if (cidAll){ cidAll.checked=false; cidScrim.querySelectorAll('.rvd-cid-cb').forEach(function(c){ c.checked=false; }); }
                cidScrim.classList.add('open');
                setTimeout(function(){ cidUrl.focus(); }, 100);
            });
            cidScrim.querySelectorAll('.rvd-cid-x').forEach(function(b){ b.addEventListener('click', function(){ cidScrim.classList.remove('open'); }); });
            cidScrim.addEventListener('click', function(e){ if (e.target === cidScrim) cidScrim.classList.remove('open'); });
            if (cidAll) cidAll.addEventListener('change', function(){ cidScrim.querySelectorAll('.rvd-cid-cb').forEach(function(c){ c.checked = cidAll.checked; }); });
            // Aviso de pedido pendente para o mesmo vídeo (igual ao antigo)
            var cidDeb;
            cidUrl.addEventListener('input', function(){
                clearTimeout(cidDeb);
                var v = cidUrl.value.trim();
                cidDeb = setTimeout(function(){
                    if (!v || !/youtube\.com|youtu\.be/i.test(v)){ cidWarn.hidden = true; return; }
                    var fd = new FormData(); fd.append('action','rmbz_contentid_check_pending'); fd.append('_nonce', cidNonce); fd.append('video_url', v);
                    fetch(ajaxUrl, { method:'POST', body:fd, credentials:'same-origin' }).then(function(r){ return r.json(); }).then(function(j){ cidWarn.hidden = !(j && j.success && j.data && j.data.has_pending); }).catch(function(){});
                }, 500);
            });
            cidSend.addEventListener('click', function(){
                var url = cidUrl.value.trim();
                cidFb.style.color = 'var(--danger)'; cidFb.textContent = '';
                if (!url){ cidFb.textContent = 'A URL do vídeo é obrigatória.'; return; }
                if (!/youtube\.com|youtu\.be/i.test(url)){ cidFb.textContent = 'A URL tem que ser de YouTube.'; return; }
                var trackIds;
                if (cidAll){ // álbum
                    if (cidAll.checked){ trackIds = ['all']; }
                    else {
                        trackIds = [];
                        cidScrim.querySelectorAll('.rvd-cid-cb:checked').forEach(function(c){ trackIds.push(parseInt(c.getAttribute('data-track-id'),10)); });
                        if (!trackIds.length){ cidFb.textContent = 'Seleciona pelo menos uma faixa.'; return; }
                    }
                } else {
                    var sid = parseInt((document.getElementById('rvd-cid-single')||{value:'0'}).value, 10);
                    trackIds = sid > 0 ? [sid] : ['all'];
                }
                cidSend.disabled = true; cidSend.textContent = 'A enviar…';
                var fd = new FormData();
                fd.append('action','rmbz_contentid_submit'); fd.append('_nonce', cidNonce);
                fd.append('release_id', cidRid); fd.append('video_url', url);
                fd.append('reason', cidReason.value.trim()); fd.append('tracks', JSON.stringify(trackIds));
                fetch(ajaxUrl, { method:'POST', body:fd, credentials:'same-origin' }).then(function(r){ return r.json(); }).then(function(j){
                    cidSend.disabled = false; cidSend.textContent = '📨 Enviar pedido';
                    if (j && j.success){
                        cidFb.style.color = 'var(--success)';
                        cidFb.textContent = '✓ Pedido enviado. A equipa será notificada e vai analisar.';
                        setTimeout(function(){ showSplash(); location.reload(); }, 1500);
                    } else {
                        cidFb.textContent = '✗ ' + ((j && j.data && j.data.message) || 'Erro ao enviar pedido.');
                    }
                }).catch(function(){ cidSend.disabled = false; cidSend.textContent = '📨 Enviar pedido'; cidFb.textContent = '✗ Erro de rede. Tenta de novo.'; });
            });
            var cidHt = document.getElementById('rvd-cid-htoggle'), cidHl = document.getElementById('rvd-cid-history');
            if (cidHt && cidHl) cidHt.addEventListener('click', function(){
                cidHl.hidden = !cidHl.hidden;
                cidHt.textContent = cidHt.textContent.replace(cidHl.hidden ? '▴' : '▾', cidHl.hidden ? '▾' : '▴');
            });
        }

        // Chat live do artista: REST + envio otimista + polling incremental.
        var chatOriginalTitle = document.title.replace(/^\d+\s+-\s+Tem (?:uma mensagem|novas mensagens)\s+\|\s+/i, '');
        var chatUnreadByProject = Object.create(null);
        var chatAudioContext = null;

        function chatUnreadTotal(){
            return Object.keys(chatUnreadByProject).reduce(function(total, projectId){
                return total + (parseInt(chatUnreadByProject[projectId], 10) || 0);
            }, 0);
        }
        function renderChatUnread(){
            var total = chatUnreadTotal();
            document.title = total > 0
                ? total + ' - ' + (total === 1 ? 'Tem uma mensagem' : 'Tem novas mensagens') + ' | ' + chatOriginalTitle
                : chatOriginalTitle;
            root.querySelectorAll('.project-live-chat').forEach(function(chat){
                var projectId = chat.getAttribute('data-project-id') || '0';
                var badge = chat.querySelector('[data-chat-unread]');
                var count = parseInt(chatUnreadByProject[projectId], 10) || 0;
                if (!badge) return;
                badge.hidden = count < 1;
                badge.textContent = count > 99 ? '99+' : String(count);
                badge.setAttribute('aria-label', count === 1 ? '1 mensagem nova' : count + ' mensagens novas');
            });
        }
        function changeChatUnread(projectId, amount){
            var current = parseInt(chatUnreadByProject[projectId], 10) || 0;
            var next = Math.max(0, current + amount);
            if (next > 0) chatUnreadByProject[projectId] = next;
            else delete chatUnreadByProject[projectId];
            renderChatUnread();
        }
        function armChatAudio(){
            var AudioEngine = window.AudioContext || window.webkitAudioContext;
            if (!AudioEngine) return;
            try {
                if (!chatAudioContext) chatAudioContext = new AudioEngine();
                if (chatAudioContext.state === 'suspended') chatAudioContext.resume().catch(function(){});
            } catch (error) {}
        }
        function playChatSound(){
            armChatAudio();
            if (!chatAudioContext || chatAudioContext.state !== 'running') return;
            var start = chatAudioContext.currentTime;
            [ [660, 0], [880, 0.11] ].forEach(function(note){
                var oscillator = chatAudioContext.createOscillator();
                var gain = chatAudioContext.createGain();
                oscillator.type = 'sine';
                oscillator.frequency.setValueAtTime(note[0], start + note[1]);
                gain.gain.setValueAtTime(0.0001, start + note[1]);
                gain.gain.exponentialRampToValueAtTime(0.075, start + note[1] + 0.018);
                gain.gain.exponentialRampToValueAtTime(0.0001, start + note[1] + 0.16);
                oscillator.connect(gain);
                gain.connect(chatAudioContext.destination);
                oscillator.start(start + note[1]);
                oscillator.stop(start + note[1] + 0.17);
            });
        }
        document.addEventListener('pointerdown', armChatAudio, { passive:true });
        document.addEventListener('keydown', armChatAudio);

        var chatImageScrim = document.getElementById('rmbz-vip-chat-image');
        var chatImageFull = chatImageScrim ? chatImageScrim.querySelector('[data-chat-image-full]') : null;
        var chatImageTitle = chatImageScrim ? chatImageScrim.querySelector('[data-chat-image-title]') : null;
        var chatImageOriginal = chatImageScrim ? chatImageScrim.querySelector('[data-chat-image-original]') : null;
        var chatImageLoading = chatImageScrim ? chatImageScrim.querySelector('[data-chat-image-loading]') : null;
        var chatImageError = chatImageScrim ? chatImageScrim.querySelector('[data-chat-image-error]') : null;
        if (chatImageFull) {
            chatImageFull.addEventListener('load', function(){
                chatImageFull.hidden = false;
                if (chatImageLoading) chatImageLoading.hidden = true;
                if (chatImageError) chatImageError.hidden = true;
            });
            chatImageFull.addEventListener('error', function(){
                chatImageFull.hidden = true;
                if (chatImageLoading) chatImageLoading.hidden = true;
                if (chatImageError) chatImageError.hidden = false;
            });
        }
        function openChatImage(url, name, trigger){
            if (!chatImageScrim || !chatImageFull || !url) return;
            chatImageScrim._vipReturnFocus = trigger || document.activeElement;
            if (chatImageTitle) chatImageTitle.textContent = name || 'Imagem do chat';
            if (chatImageOriginal) chatImageOriginal.href = url;
            if (chatImageLoading) chatImageLoading.hidden = false;
            if (chatImageError) chatImageError.hidden = true;
            chatImageFull.hidden = true;
            chatImageFull.alt = name || 'Imagem anexada no chat';
            chatImageFull.removeAttribute('src');
            chatImageScrim.classList.add('open');
            requestAnimationFrame(function(){ chatImageFull.src = url; });
        }

        root.querySelectorAll('.project-live-chat').forEach(function(chat){
            var projectId = chat.getAttribute('data-project-id') || '0';
            var getUrl = chat.getAttribute('data-get-url') || '';
            var sendUrl = chat.getAttribute('data-send-url') || '';
            var uploadUrl = chat.getAttribute('data-upload-url') || '';
            var deleteUrl = chat.getAttribute('data-delete-url') || '';
            var list = chat.querySelector('[data-chat-list]');
            var form = chat.querySelector('.project-live-chat-form');
            var input = chat.querySelector('[data-chat-input]');
            var sendBtn = chat.querySelector('[data-chat-send]');
            var attachBtn = chat.querySelector('[data-chat-attach]');
            var fileInput = chat.querySelector('[data-chat-file]');
            var uploadPreview = chat.querySelector('[data-chat-upload-preview]');
            var uploadIcon = chat.querySelector('[data-chat-upload-icon]');
            var uploadName = chat.querySelector('[data-chat-upload-name]');
            var uploadMeta = chat.querySelector('[data-chat-upload-meta]');
            var uploadRemove = chat.querySelector('[data-chat-upload-remove]');
            var feedback = chat.querySelector('[data-chat-feedback]');
            var liveBadge = chat.querySelector('[data-chat-live]');
            var toggle = chat.querySelector('.rmbz-vip-toggle');
            var panel = toggle ? document.getElementById(toggle.getAttribute('data-target')) : null;
            if (!getUrl || !sendUrl || !uploadUrl || !deleteUrl || !list || !form || !input || !sendBtn || !attachBtn || !fileInput || !uploadPreview || !uploadRemove) return;

            var lastId = 0, loading = false, sending = false, loaded = false, uploading = false;
            var chatLocked = false, canAttach = false, pendingAttachment = null, uploadSerial = 0, serverClockOffset = 0;
            var known = Object.create(null);

            function node(tag, cls, textValue){
                var el = document.createElement(tag);
                if (cls) el.className = cls;
                if (typeof textValue !== 'undefined') el.textContent = textValue;
                return el;
            }
            function serverNowMs(){
                return Date.now() + serverClockOffset;
            }
            function stripLeadingSymbols(value){
                var valueText = String(value || '').trim();
                while (valueText) {
                    var cp = valueText.codePointAt(0);
                    var blank = cp <= 32 || cp === 0x00a0;
                    var symbol = cp === 0xfe0f || cp === 0x200d || (cp >= 0x2600 && cp <= 0x27ff) || (cp >= 0x1f300 && cp <= 0x1faff);
                    if (!blank && !symbol) break;
                    valueText = valueText.slice(cp > 0xffff ? 2 : 1).trimStart();
                }
                return valueText;
            }
            function messageKind(message){
                var body = stripLeadingSymbols(message && message.body);
                var lower = body.toLocaleLowerCase('pt');
                if (lower.indexOf('confirmou as datas de gravação') !== -1 || lower.indexOf('datas de gravação confirmadas') !== -1) return 'confirm';
                if (lower.indexOf('propôs novas datas de gravação') !== -1 || lower.indexOf('nova proposta de gravação') !== -1) return 'proposal';
                return message && message.author_type === 'system' ? 'system' : 'message';
            }
            function setFeedback(textValue, isError){
                if (!feedback) return;
                feedback.textContent = textValue || '';
                feedback.classList.toggle('show', !!textValue);
                feedback.classList.toggle('error', !!isError);
            }
            function setLive(isLive){
                if (!liveBadge) return;
                liveBadge.classList.toggle('offline', !isLive);
                liveBadge.textContent = isLive ? 'Live' : 'Offline';
            }
            function formatFileSize(bytes){
                var size = parseInt(bytes, 10) || 0;
                if (size < 1024) return size + ' B';
                if (size < 1024 * 1024) return (size / 1024).toFixed(1).replace('.0', '') + ' KB';
                return (size / (1024 * 1024)).toFixed(1).replace('.0', '') + ' MB';
            }
            function attachmentMaterialIcon(file){
                var type = String(file && file.type || '').toLowerCase();
                if (type === 'image' || type.indexOf('image/') === 0) return 'image';
                if (type === 'audio' || type.indexOf('audio/') === 0) return 'headphones';
                if (type === 'video' || type.indexOf('video/') === 0) return 'movie';
                if (type === 'pdf' || type === 'application/pdf') return 'picture_as_pdf';
                return 'draft';
            }
            function showUploadPreview(file, isUploading){
                uploadPreview.hidden = false;
                uploadPreview.classList.toggle('uploading', !!isUploading);
                if (uploadIcon) uploadIcon.textContent = attachmentMaterialIcon(file);
                if (uploadName) uploadName.textContent = file && file.name ? file.name : 'Ficheiro';
                if (uploadMeta) uploadMeta.textContent = isUploading
                    ? 'A carregar ' + formatFileSize(file && file.size) + '…'
                    : formatFileSize(file && file.size) + ' · Pronto para enviar';
                uploadRemove.disabled = !!isUploading;
            }
            function clearAttachment(){
                uploadSerial++;
                uploading = false;
                pendingAttachment = null;
                fileInput.value = '';
                uploadPreview.hidden = true;
                uploadPreview.classList.remove('uploading');
                uploadRemove.disabled = false;
                syncComposer();
            }
            function syncComposer(){
                var hasContent = input.value.trim() !== '' || !!pendingAttachment;
                input.disabled = chatLocked || sending;
                fileInput.disabled = chatLocked || sending || uploading || !canAttach;
                attachBtn.hidden = !canAttach || chatLocked;
                attachBtn.disabled = chatLocked || sending || uploading;
                sendBtn.disabled = chatLocked || sending || uploading || !hasContent;
            }
            function setCanAttach(allowed){
                var wasAllowed = canAttach;
                canAttach = !!allowed;
                if (!canAttach && (pendingAttachment || uploading)) {
                    clearAttachment();
                    if (wasAllowed) setFeedback('A permissão para anexar ficheiros foi desativada.', true);
                }
                syncComposer();
            }
            function setLocked(locked){
                chatLocked = !!locked;
                input.placeholder = chatLocked ? 'Chat desativado para este projeto' : 'Escreve à equipa…';
                if (chatLocked) {
                    setFeedback('Este chat está disponível apenas enquanto o projeto estiver ativo.', true);
                }
                syncComposer();
            }
            function chatIsActive(){
                var section = chat.closest('[data-sect]');
                var panelOpen = panel && panel.style.display !== 'none' && window.getComputedStyle(panel).display !== 'none';
                var sectionOpen = !section || section.classList.contains('on');
                return panelOpen && sectionOpen && !document.hidden && document.hasFocus();
            }
            function markChatRead(){
                var unread = parseInt(chatUnreadByProject[projectId], 10) || 0;
                if (chatIsActive() && unread > 0) changeChatUnread(projectId, -unread);
            }
            function renderAttachment(message, parent){
                var attachment = message && message.attachment;
                if (!attachment || !attachment.url) return;
                var attachmentType = String(attachment.type || '').toLowerCase();
                var isImage = attachmentType === 'image' || /\.(?:jpe?g|png|webp|gif)(?:[?#].*)?$/i.test(attachment.url);
                if (isImage) {
                    var preview = node('button', 'project-chat-image-preview');
                    preview.type = 'button';
                    preview.setAttribute('aria-label', 'Abrir imagem ' + (attachment.name || 'anexada'));
                    var frame = node('span', 'project-chat-image-frame');
                    var image = node('img');
                    image.src = attachment.url;
                    image.alt = attachment.name || 'Imagem anexada no chat';
                    image.loading = 'lazy';
                    image.decoding = 'async';
                    image.addEventListener('error', function(){
                        preview.classList.add('broken');
                        frame.innerHTML = '';
                        frame.appendChild(node('span', 'ms', 'broken_image'));
                        frame.appendChild(node('span', '', 'Pré-visualização indisponível'));
                    });
                    frame.appendChild(image);
                    frame.appendChild(node('span', 'ms project-chat-image-zoom', 'zoom_in'));
                    preview.appendChild(frame);
                    var caption = node('span', 'project-chat-image-caption');
                    caption.appendChild(node('span', 'ms', 'image'));
                    caption.appendChild(node('span', '', attachment.name || 'Imagem anexada'));
                    preview.appendChild(caption);
                    preview.addEventListener('click', function(){ openChatImage(attachment.url, attachment.name, preview); });
                    parent.appendChild(preview);
                    return;
                }
                var link = node('a', 'project-chat-attachment');
                link.href = attachment.url;
                link.target = '_blank';
                link.rel = 'noopener';
                var iconMap = { image:'image', audio:'headphones', video:'movie', pdf:'picture_as_pdf', file:'attach_file' };
                link.appendChild(node('span', 'ms', iconMap[attachment.type] || 'attach_file'));
                link.appendChild(node('span', '', attachment.name || 'Abrir anexo'));
                parent.appendChild(link);
            }
            function renderMessage(message, optimistic){
                var kind = messageKind(message);
                var body = stripLeadingSymbols(message && message.body);
                var dateLabel = (message && message.created_at_label) || (optimistic ? 'Agora' : '');

                if (kind !== 'message') {
                    var event = node('div', 'project-chat-event' + (kind === 'proposal' ? ' proposal' : ''));
                    var icon = 'info', title = 'Atualização do projeto', detail = body;
                    if (kind === 'confirm') {
                        icon = 'event_available'; title = 'Datas de gravação confirmadas'; detail = 'O período definido foi aceite pelo artista.';
                    } else if (kind === 'proposal') {
                        icon = 'edit_calendar'; title = 'Nova proposta de datas';
                        detail = body.replace(/^Propôs novas datas de gravação:\s*/i, 'Período proposto: ').replace(/^Nova proposta de gravação:\s*/i, 'Período proposto: ');
                    }
                    event.appendChild(node('span', 'ms', icon));
                    var eventCopy = node('div');
                    eventCopy.appendChild(node('div', 'project-chat-event-title', title));
                    eventCopy.appendChild(node('div', 'project-chat-event-meta', detail + (dateLabel ? ' · ' + dateLabel : '')));
                    event.appendChild(eventCopy);
                    return event;
                }

                var authorType = message && message.author_type === 'admin' ? 'team' : 'artist';
                var bubble = node('div', 'project-chat-message ' + authorType + (optimistic ? ' sending' : ''));
                bubble.appendChild(node('div', 'project-chat-sender', (authorType === 'team' ? 'Equipa 1MZ' : 'Tu') + (dateLabel ? ' · ' + dateLabel : '')));
                if (message && message.is_deleted) {
                    bubble.appendChild(node('div', 'project-chat-text', 'Mensagem removida'));
                } else if (body) {
                    bubble.appendChild(node('div', 'project-chat-text', body));
                }
                renderAttachment(message, bubble);
                if (message && message.is_edited) bubble.appendChild(node('div', 'project-chat-event-meta', 'Editado'));
                var messageId = parseInt(message && message.id, 10) || 0;
                var deleteUntil = Number(message && message.artist_delete_until_ms) || 0;
                if (authorType === 'artist' && messageId > 0 && !optimistic && message && message.artist_can_delete && deleteUntil > serverNowMs() && !message.is_legacy && !message.is_deleted) {
                    var actions = node('div', 'project-chat-message-actions');
                    var deleteButton = node('button', 'project-chat-delete');
                    deleteButton.type = 'button';
                    deleteButton.setAttribute('data-chat-delete-message', String(messageId));
                    deleteButton.setAttribute('data-chat-delete-until', String(deleteUntil));
                    deleteButton.setAttribute('aria-label', 'Apagar esta mensagem');
                    deleteButton.appendChild(node('span', 'ms', 'delete_outline'));
                    deleteButton.appendChild(node('span', '', 'Apagar'));
                    actions.appendChild(deleteButton);
                    bubble.appendChild(actions);
                }
                return bubble;
            }
            function refreshDeleteWindows(){
                list.querySelectorAll('[data-chat-delete-until]').forEach(function(button){
                    var until = Number(button.getAttribute('data-chat-delete-until')) || 0;
                    var seconds = Math.max(0, Math.ceil((until - serverNowMs()) / 1000));
                    if (seconds <= 0) {
                        var actions = button.closest('.project-chat-message-actions');
                        if (actions) actions.remove(); else button.remove();
                        return;
                    }
                    var label = button.querySelector('span:last-child');
                    if (label) label.textContent = 'Apagar · ' + Math.floor(seconds / 60) + ':' + String(seconds % 60).padStart(2, '0');
                    button.setAttribute('aria-label', 'Apagar esta mensagem. Restam ' + seconds + ' segundos');
                });
            }
            function reconcileDeletedMessages(ids){
                (Array.isArray(ids) ? ids : []).forEach(function(id){
                    var numericId = parseInt(id, 10) || 0;
                    var messageNode = numericId > 0 ? list.querySelector('[data-chat-message-id="' + String(numericId) + '"]') : null;
                    if (messageNode) messageNode.remove();
                });
                if (!list.children.length) list.appendChild(node('div', 'project-chat-empty', 'Ainda não existem mensagens neste projeto.'));
            }
            function appendMessages(messages, replace, forceScroll){
                messages = Array.isArray(messages) ? messages : [];
                var nearBottom = list.scrollHeight - list.scrollTop - list.clientHeight < 90;
                var newTeamMessages = 0;
                if (replace) { list.innerHTML = ''; known = Object.create(null); }

                var lastConfirmIndex = -1;
                if (replace) messages.forEach(function(message, index){ if (messageKind(message) === 'confirm') lastConfirmIndex = index; });
                messages.forEach(function(message, index){
                    if (!message) return;
                    if (replace && messageKind(message) === 'confirm' && index !== lastConfirmIndex) return;
                    var key = String(message.id);
                    if (known[key]) return;
                    known[key] = true;
                    if (!replace && message.author_type === 'admin') newTeamMessages++;
                    var numericId = parseInt(message.id, 10) || 0;
                    if (numericId > lastId) lastId = numericId;
                    var messageNode = renderMessage(message, false);
                    if (numericId !== 0) messageNode.setAttribute('data-chat-message-id', String(numericId));
                    list.appendChild(messageNode);
                });
                if (!list.children.length) list.appendChild(node('div', 'project-chat-empty', 'Ainda não existem mensagens neste projeto.'));
                if (replace || forceScroll || nearBottom) list.scrollTop = list.scrollHeight;
                refreshDeleteWindows();
                if (newTeamMessages > 0) {
                    playChatSound();
                    if (chatIsActive()) markChatRead();
                    else changeChatUnread(projectId, newTeamMessages);
                }
            }
            function responseData(response){
                if (!response || !response.success) {
                    throw new Error(response && response.error && response.error.message ? response.error.message : 'Não foi possível atualizar o chat.');
                }
                return response.data || {};
            }
            function loadMessages(initial){
                if (loading) return;
                loading = true;
                var cursor = initial ? 0 : (lastId > 0 ? lastId : -1);
                var url = getUrl + (getUrl.indexOf('?') === -1 ? '?' : '&') + 'since=' + encodeURIComponent(cursor);
                fetch(url, { credentials:'same-origin', cache:'no-store', headers:{ 'Accept':'application/json' } })
                    .then(function(result){ return result.json(); })
                    .then(responseData)
                    .then(function(data){
                        if (Number(data.server_timestamp_ms) > 0) serverClockOffset = Number(data.server_timestamp_ms) - Date.now();
                        appendMessages(data.messages, initial, initial);
                        reconcileDeletedMessages(data.deleted_message_ids);
                        setCanAttach(!!data.artist_can_attach);
                        setLocked(!!data.chat_locked);
                        setLive(true);
                        loaded = true;
                        if (!data.chat_locked) setFeedback('', false);
                    })
                    .catch(function(error){
                        setLive(false);
                        if (!loaded) setFeedback(error.message || 'Ligação indisponível.', true);
                    })
                    .then(function(){ loading = false; });
            }

            input.addEventListener('input', syncComposer);
            list.addEventListener('click', function(event){
                var deleteButton = event.target && event.target.closest ? event.target.closest('[data-chat-delete-message]') : null;
                if (!deleteButton || !list.contains(deleteButton)) return;
                var messageId = parseInt(deleteButton.getAttribute('data-chat-delete-message'), 10) || 0;
                if (messageId <= 0 || deleteButton.disabled) return;
                vipConfirm('Apagar esta mensagem? A equipa verá apenas “Mensagem apagada”.').then(function(confirmed){
                    if (!confirmed) return;
                    deleteButton.disabled = true;
                    fetch(deleteUrl, {
                        method:'POST', credentials:'same-origin', cache:'no-store',
                        headers:{ 'Accept':'application/json', 'Content-Type':'application/json' },
                        body:JSON.stringify({ message_id:messageId })
                    }).then(function(result){ return result.json(); }).then(responseData).then(function(){
                        reconcileDeletedMessages([ messageId ]);
                        setFeedback('Mensagem apagada.', false);
                    }).catch(function(error){
                        if (String(error && error.message || '').indexOf('2 minutos') !== -1) {
                            var actions = deleteButton.closest('.project-chat-message-actions');
                            if (actions) actions.remove();
                        } else {
                            deleteButton.disabled = false;
                            refreshDeleteWindows();
                        }
                        setFeedback(error.message || 'Não foi possível apagar a mensagem.', true);
                    });
                });
            });
            attachBtn.addEventListener('click', function(){
                if (!attachBtn.disabled && canAttach) fileInput.click();
            });
            uploadRemove.addEventListener('click', clearAttachment);
            fileInput.addEventListener('change', function(){
                var file = fileInput.files && fileInput.files[0];
                if (!file) return;
                if (!canAttach) {
                    clearAttachment();
                    setFeedback('A equipa ainda não permitiu anexos neste projeto.', true);
                    return;
                }
                if (file.size <= 0 || file.size > 15 * 1024 * 1024) {
                    clearAttachment();
                    setFeedback('O ficheiro deve ter no máximo 15 MB.', true);
                    return;
                }

                var serial = ++uploadSerial;
                uploading = true;
                pendingAttachment = null;
                showUploadPreview(file, true);
                syncComposer();
                setFeedback('', false);

                var uploadBody = new FormData();
                uploadBody.append('file', file);
                fetch(uploadUrl, {
                    method:'POST', credentials:'same-origin', cache:'no-store',
                    headers:{ 'Accept':'application/json' }, body:uploadBody
                }).then(function(result){ return result.json(); }).then(responseData).then(function(attachment){
                    if (serial !== uploadSerial) return;
                    uploading = false;
                    pendingAttachment = attachment;
                    showUploadPreview(attachment, false);
                    syncComposer();
                }).catch(function(error){
                    if (serial !== uploadSerial) return;
                    clearAttachment();
                    setFeedback(error.message || 'Não foi possível carregar o ficheiro.', true);
                });
            });

            form.addEventListener('submit', function(event){
                event.preventDefault();
                if (sending || uploading || chatLocked) return;
                var body = input.value.trim();
                var attachment = pendingAttachment;
                if (!body && !attachment) { input.focus(); return; }

                sending = true;
                input.value = '';
                syncComposer();
                setFeedback('A enviar…', false);
                var empty = list.querySelector('.project-chat-empty'); if (empty) empty.remove();
                var temporary = renderMessage({ author_type:'artist', body:body, attachment:attachment, created_at_label:'Agora' }, true);
                list.appendChild(temporary);
                list.scrollTop = list.scrollHeight;

                fetch(sendUrl, {
                    method:'POST', credentials:'same-origin', cache:'no-store',
                    headers:{ 'Accept':'application/json', 'Content-Type':'application/json' },
                    body:JSON.stringify({ body:body, attachment:attachment })
                }).then(function(result){ return result.json(); }).then(responseData).then(function(data){
                    if (temporary.parentNode) temporary.parentNode.removeChild(temporary);
                    clearAttachment();
                    if (Number(data.server_timestamp_ms) > 0) serverClockOffset = Number(data.server_timestamp_ms) - Date.now();
                    appendMessages(data.messages, false, true);
                    setFeedback('', false);
                    setLive(true);
                }).catch(function(error){
                    if (temporary.parentNode) temporary.parentNode.removeChild(temporary);
                    input.value = body;
                    setFeedback(error.message || 'Não foi possível enviar. Tenta novamente.', true);
                    setLive(false);
                }).then(function(){
                    sending = false;
                    syncComposer();
                    if (!chatLocked) input.focus();
                });
            });

            if (toggle) toggle.addEventListener('click', function(){ setTimeout(markChatRead, 0); });
            document.addEventListener('visibilitychange', markChatRead);
            window.addEventListener('focus', markChatRead);

            syncComposer();
            loadMessages(true);
            setInterval(refreshDeleteWindows, 1000);
            setInterval(function(){ loadMessages(false); }, 2500);
        });

        // [1.5.433] SPLASH DE NAVEGAÇÃO — ao clicar num link/form que
        // recarrega a página, mostra já o logo a flutuar (fundo do tema).
        var splash = document.getElementById('rmbz-vip-splash');
        function showSplash(){ if (splash) splash.classList.add('open'); }
        // Links: só navegação real (ignora âncoras, nova aba, downloads,
        // cliques com modificador e cliques já tratados por outros handlers).
        root.addEventListener('click', function (e) {
            if (e.defaultPrevented || e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;
            var a = e.target && e.target.closest ? e.target.closest('a[href]') : null;
            if (!a || a.target === '_blank' || a.hasAttribute('download')) return;
            var href = a.getAttribute('href') || '';
            if (href.charAt(0) === '#' || href.indexOf('javascript:') === 0 || href.indexOf('mailto:') === 0 || href.indexOf('tel:') === 0) return;
            showSplash();
        });
        // Forms nativos (envios, logout, multa…): mostra depois de os outros
        // handlers correrem — se algum fez preventDefault (fluxo AJAX), não.
        root.addEventListener('submit', function (e) {
            setTimeout(function(){ if (!e.defaultPrevented) showSplash(); }, 0);
        });
        // Voltar via bfcache (botão "anterior"): a página volta viva com o
        // splash aberto — fecha-o.
        window.addEventListener('pageshow', function (e) {
            if (e.persisted && splash) splash.classList.remove('open');
        });

        // [1.5.433] Painel pronto → despede o splash do <head> (página nova)
        // com fade suave. O estilo é removido de vez logo a seguir.
        try {
            document.documentElement.classList.add('rmbz-vip-ready');
            setTimeout(function(){
                var s = document.getElementById('rmbz-vip-preload');
                if (s && s.parentNode) s.parentNode.removeChild(s);
                document.documentElement.classList.remove('rmbz-vip-loading', 'rmbz-vip-ready');
            }, 380);
        } catch (e) {}
    })();
    </script>
    <?php
}
