<?php
/**
 * includes/notifications/notifications-admin.php
 *
 * ============================================================================
 * UI ADMIN — gerir notificações inline (1.5.183)
 * ============================================================================
 *
 * Página integrada como tab "📢 Comunicação" da Distribuição admin.
 *
 * Funcionalidades:
 *   - Form para criar broadcast (título, body, severity, target, expires, action)
 *   - Lista de notificações activas com:
 *       - severity badge
 *       - tipo (broadcast / specific user)
 *       - contagem de quantos dispensaram
 *       - data criação / expiração
 *       - acções: arquivar, ver dismissed
 *   - Lista de notificações arquivadas (collapsible) — auditoria
 *
 * Filosofia:
 *   - Tudo via POST + nonce
 *   - Cores hardcoded (lição da 1.5.176/177/181)
 *   - Layout coerente com restantes admin pages refactorizadas
 *
 * ============================================================================
 */

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


/* ============================================================================
 * 1. HANDLERS — POST actions (criar, arquivar)
 * ============================================================================ */

/**
 * Cria nova notificação a partir do form.
 */
function rmbz_notif_admin_handle_create() {
    if ( ! current_user_can('manage_options') ) {
        wp_die( __( 'Sem permissão.' ) );
    }
    check_admin_referer( 'rmbz_notif_admin_create' );

    $title       = isset($_POST['title']) ? wp_strip_all_tags( wp_unslash( $_POST['title'] ) ) : '';
    $body        = isset($_POST['body']) ? wp_kses_post( wp_unslash( $_POST['body'] ) ) : '';
    $severity    = isset($_POST['severity']) ? sanitize_text_field( $_POST['severity'] ) : 'info';
    $target_mode = isset($_POST['target_mode']) ? sanitize_key( $_POST['target_mode'] ) : 'broadcast';
    $target_tel  = isset($_POST['target_telemovel']) ? preg_replace('/[^0-9+]/', '', wp_unslash( $_POST['target_telemovel'] )) : '';
    $action_url  = isset($_POST['action_url']) ? esc_url_raw( wp_unslash( $_POST['action_url'] ) ) : '';
    $action_lbl  = isset($_POST['action_label']) ? sanitize_text_field( wp_unslash( $_POST['action_label'] ) ) : '';
    $expires_in  = isset($_POST['expires_in_days']) ? (int) $_POST['expires_in_days'] : 0;
    $type        = isset($_POST['type']) ? sanitize_key( $_POST['type'] ) : 'admin_broadcast';

    if ( empty( $title ) ) {
        wp_safe_redirect( add_query_arg( ['msg' => 'empty_title'], wp_get_referer() ) );
        exit;
    }

    if ( $target_mode === 'user' && empty( $target_tel ) ) {
        wp_safe_redirect( add_query_arg( ['msg' => 'no_target'], wp_get_referer() ) );
        exit;
    }

    $expires_at = null;
    if ( $expires_in > 0 ) {
        $expires_at = gmdate( 'Y-m-d H:i:s', time() + ($expires_in * 86400) );
    }

    $created_by = wp_get_current_user()->user_login ?: 'admin';

    $result = rmbz_notify_create([
        'type'             => $type,
        'severity'         => $severity,
        'title'            => $title,
        'body'             => $body,
        'action_url'       => $action_url ?: null,
        'action_label'     => $action_lbl ?: null,
        'target_telemovel' => $target_mode === 'user' ? $target_tel : null,
        'target_role'      => null,
        'expires_at'       => $expires_at,
        'created_by'       => $created_by,
    ]);

    $msg = $result ? 'created' : 'error';
    wp_safe_redirect( add_query_arg(
        [ 'page' => 'rmbz-admin-distribution', 'tab' => 'notifications', 'msg' => $msg, 'nid' => $result ?: 0 ],
        admin_url( 'admin.php' )
    ));
    exit;
}
add_action( 'admin_post_rmbz_notif_admin_create', 'rmbz_notif_admin_handle_create' );


/**
 * Arquiva uma notificação (esconde antes de expirar).
 */
function rmbz_notif_admin_handle_archive() {
    if ( ! current_user_can('manage_options') ) {
        wp_die( __( 'Sem permissão.' ) );
    }
    check_admin_referer( 'rmbz_notif_admin_archive' );

    global $wpdb;
    $id = isset($_POST['notification_id']) ? (int) $_POST['notification_id'] : 0;
    if ( $id <= 0 ) {
        wp_safe_redirect( add_query_arg( ['msg' => 'invalid_id'], wp_get_referer() ) );
        exit;
    }

    $wpdb->update(
        "{$wpdb->prefix}rmbz_notifications",
        [ 'is_archived' => 1 ],
        [ 'id' => $id ],
        [ '%d' ],
        [ '%d' ]
    );

    wp_safe_redirect( add_query_arg(
        [ 'page' => 'rmbz-admin-distribution', 'tab' => 'notifications', 'msg' => 'archived' ],
        admin_url( 'admin.php' )
    ));
    exit;
}
add_action( 'admin_post_rmbz_notif_admin_archive', 'rmbz_notif_admin_handle_archive' );


/**
 * Apaga TODAS as dismissals de uma notificação (faz reaparecer para todos).
 * Útil se admin precisa de re-broadcast.
 */
function rmbz_notif_admin_handle_reset_dismissed() {
    if ( ! current_user_can('manage_options') ) {
        wp_die( __( 'Sem permissão.' ) );
    }
    check_admin_referer( 'rmbz_notif_admin_reset' );

    global $wpdb;
    $id = isset($_POST['notification_id']) ? (int) $_POST['notification_id'] : 0;
    if ( $id <= 0 ) {
        wp_safe_redirect( add_query_arg( ['msg' => 'invalid_id'], wp_get_referer() ) );
        exit;
    }

    $wpdb->delete(
        "{$wpdb->prefix}rmbz_notifications_dismissed",
        [ 'notification_id' => $id ]
    );

    wp_safe_redirect( add_query_arg(
        [ 'page' => 'rmbz-admin-distribution', 'tab' => 'notifications', 'msg' => 'reset_dismissed' ],
        admin_url( 'admin.php' )
    ));
    exit;
}
add_action( 'admin_post_rmbz_notif_admin_reset', 'rmbz_notif_admin_handle_reset_dismissed' );


/* ============================================================================
 * 2. RENDER — página principal
 * ============================================================================ */

function rmbz_notif_render_admin_page() {
    global $wpdb;
    $now = current_time( 'mysql' );

    // Notificações activas
    $active = $wpdb->get_results( $wpdb->prepare(
        "SELECT n.*,
                (SELECT COUNT(*) FROM {$wpdb->prefix}rmbz_notifications_dismissed d WHERE d.notification_id = n.id) AS dismissed_count
         FROM {$wpdb->prefix}rmbz_notifications n
         WHERE n.is_archived = 0
           AND (n.expires_at IS NULL OR n.expires_at > %s)
         ORDER BY n.created_at DESC
         LIMIT 50",
        $now
    ));

    // Arquivadas/expiradas (histórico)
    $archived = $wpdb->get_results( $wpdb->prepare(
        "SELECT n.*,
                (SELECT COUNT(*) FROM {$wpdb->prefix}rmbz_notifications_dismissed d WHERE d.notification_id = n.id) AS dismissed_count
         FROM {$wpdb->prefix}rmbz_notifications n
         WHERE n.is_archived = 1 OR (n.expires_at IS NOT NULL AND n.expires_at <= %s)
         ORDER BY n.created_at DESC
         LIMIT 50",
        $now
    ));

    // Mensagens de feedback
    $msg = isset($_GET['msg']) ? sanitize_key($_GET['msg']) : '';
    ?>
    <div class="rmbz-na-wrap">
        <?php if ( $msg ): ?>
            <?php
            $msg_map = [
                'created'         => ['success', '✓ Notificação criada com sucesso e já visível para os artistas.'],
                'archived'        => ['success', '✓ Notificação arquivada — já não aparece para ninguém.'],
                'reset_dismissed' => ['success', '✓ Dismissals limpas — a notificação volta a aparecer para todos os artistas.'],
                'empty_title'     => ['danger', '✗ O título é obrigatório.'],
                'no_target'       => ['danger', '✗ Para notificação específica tens de indicar o telemóvel do destinatário.'],
                'invalid_id'      => ['danger', '✗ ID inválido.'],
                'error'           => ['danger', '✗ Erro ao criar notificação. Verifica os logs.'],
            ];
            if ( isset($msg_map[$msg]) ):
                $sev = $msg_map[$msg][0]; $txt = $msg_map[$msg][1];
            ?>
                <div class="rmbz-na-flash rmbz-na-flash--<?php echo esc_attr($sev); ?>">
                    <?php echo esc_html($txt); ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>

        <div class="rmbz-na-header">
            <div class="rmbz-na-kicker">DISTRIBUIÇÃO · COMUNICAÇÃO</div>
            <h1 class="rmbz-na-title">📢 Notificações Inline</h1>
            <p class="rmbz-na-subtitle">
                Cria avisos visuais que aparecem como banners no topo da Distribuição
                dos artistas. Útil para anúncios de manutenção, novas features, ou
                alertas específicos a um artista. Diferente do sistema de email/sino
                — aqui mostra <strong>banners proeminentes</strong> dentro da plataforma.
            </p>
        </div>

        <div class="rmbz-na-grid">
            <!-- COLUNA ESQUERDA: FORM CRIAR -->
            <div class="rmbz-na-col-form">
                <div class="rmbz-na-card">
                    <div class="rmbz-na-card-head">
                        <strong>➕ Criar nova notificação</strong>
                    </div>

                    <form method="post" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" class="rmbz-na-form">
                        <?php wp_nonce_field('rmbz_notif_admin_create'); ?>
                        <input type="hidden" name="action" value="rmbz_notif_admin_create">

                        <label class="rmbz-na-field">
                            <span class="rmbz-na-label">Título *</span>
                            <input type="text" name="title" required maxlength="200" placeholder='Ex: Manutenção programada Sábado 10/05'>
                            <span class="rmbz-na-hint">Máx 200 caracteres. Curto e claro.</span>
                        </label>

                        <label class="rmbz-na-field">
                            <span class="rmbz-na-label">Mensagem (opcional)</span>
                            <textarea name="body" rows="3" placeholder='Detalhes adicionais...'></textarea>
                            <span class="rmbz-na-hint">HTML básico permitido (&lt;strong&gt;, &lt;a&gt;, &lt;br&gt;).</span>
                        </label>

                        <div class="rmbz-na-row-2">
                            <label class="rmbz-na-field">
                                <span class="rmbz-na-label">Severidade</span>
                                <select name="severity">
                                    <option value="info">ℹ Info (azul) — neutro</option>
                                    <option value="success">✓ Success (verde) — boa notícia</option>
                                    <option value="warning">! Warning (amarelo) — atenção</option>
                                    <option value="danger">⚠ Danger (vermelho) — urgente</option>
                                </select>
                            </label>

                            <label class="rmbz-na-field">
                                <span class="rmbz-na-label">Expira em</span>
                                <select name="expires_in_days">
                                    <option value="0">Não expira</option>
                                    <option value="1">1 dia</option>
                                    <option value="3">3 dias</option>
                                    <option value="7" selected>7 dias</option>
                                    <option value="14">14 dias</option>
                                    <option value="30">30 dias</option>
                                </select>
                            </label>
                        </div>

                        <div class="rmbz-na-field">
                            <span class="rmbz-na-label">Destinatário</span>
                            <div class="rmbz-na-radio-group">
                                <label>
                                    <input type="radio" name="target_mode" value="broadcast" checked
                                           onchange="document.getElementById('rmbz-na-target-tel').style.display='none'; document.getElementById('rmbz-na-target-tel').querySelector('input').required=false;">
                                    <strong>Broadcast</strong> — todos os artistas
                                </label>
                                <label>
                                    <input type="radio" name="target_mode" value="user"
                                           onchange="document.getElementById('rmbz-na-target-tel').style.display='block'; document.getElementById('rmbz-na-target-tel').querySelector('input').required=true;">
                                    <strong>Específico</strong> — só um artista (por telemovel)
                                </label>
                            </div>
                            <div id="rmbz-na-target-tel" style="display:none; margin-top:8px;">
                                <input type="text" name="target_telemovel" placeholder="258861640807" pattern="[0-9+]+">
                                <span class="rmbz-na-hint">Telemovel completo (com prefixo 258).</span>
                            </div>
                        </div>

                        <div class="rmbz-na-row-2">
                            <label class="rmbz-na-field">
                                <span class="rmbz-na-label">Botão CTA — URL (opcional)</span>
                                <input type="url" name="action_url" placeholder="?distro_action=edit_release&id=42">
                            </label>

                            <label class="rmbz-na-field">
                                <span class="rmbz-na-label">Botão CTA — Texto</span>
                                <input type="text" name="action_label" placeholder="Ver detalhes" maxlength="80">
                            </label>
                        </div>

                        <input type="hidden" name="type" value="admin_broadcast">

                        <button type="submit" class="rmbz-na-btn rmbz-na-btn-primary">
                            📢 Criar e enviar notificação
                        </button>
                    </form>
                </div>
            </div>

            <!-- COLUNA DIREITA: LISTA -->
            <div class="rmbz-na-col-list">
                <div class="rmbz-na-card">
                    <div class="rmbz-na-card-head">
                        <strong>📋 Notificações activas (<?php echo count($active); ?>)</strong>
                        <span class="rmbz-na-card-hint">Visíveis aos artistas neste momento</span>
                    </div>

                    <?php if ( empty($active) ): ?>
                        <div class="rmbz-na-empty">
                            <div class="rmbz-na-empty-icon">📭</div>
                            <p>Sem notificações activas. Cria uma à esquerda para começar.</p>
                        </div>
                    <?php else: ?>
                        <div class="rmbz-na-list">
                            <?php foreach ( $active as $n ): ?>
                                <?php rmbz_notif_render_admin_row( $n, false ); ?>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <?php if ( ! empty($archived) ): ?>
                    <details class="rmbz-na-archived">
                        <summary>
                            <span>📦 Histórico — arquivadas/expiradas (<?php echo count($archived); ?>)</span>
                            <small>clica para ver</small>
                        </summary>
                        <div class="rmbz-na-list">
                            <?php foreach ( $archived as $n ): ?>
                                <?php rmbz_notif_render_admin_row( $n, true ); ?>
                            <?php endforeach; ?>
                        </div>
                    </details>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <?php rmbz_notif_render_admin_styles(); ?>
    <?php
}


/**
 * Renderiza uma linha (notificação) na lista admin.
 */
function rmbz_notif_render_admin_row( $n, $is_archived = false ) {
    $sev_meta = [
        'info'    => ['#e8f3fc', '#1e3a8a', 'ℹ', 'Info'],
        'success' => ['#d4edda', '#14532d', '✓', 'Success'],
        'warning' => ['#fff3cd', '#78350f', '!', 'Warning'],
        'danger'  => ['#fde4e2', '#7f1d1d', '⚠', 'Danger'],
    ];
    $meta = $sev_meta[ $n->severity ] ?? $sev_meta['info'];

    $is_user = ! empty( $n->target_telemovel );
    $type_label = $is_user
        ? 'Para: ' . esc_html( $n->target_telemovel )
        : 'Broadcast (todos)';

    $created = mysql2date( 'd/m/Y H:i', $n->created_at );
    $expires = $n->expires_at
        ? mysql2date( 'd/m/Y H:i', $n->expires_at )
        : '—';
    ?>
    <div class="rmbz-na-row">
        <div class="rmbz-na-row-head">
            <span class="rmbz-na-sev-pill" style="background:<?php echo $meta[0]; ?>; color:<?php echo $meta[1]; ?>;">
                <?php echo esc_html($meta[2]); ?> <?php echo esc_html($meta[3]); ?>
            </span>
            <strong class="rmbz-na-row-title"><?php echo esc_html( $n->title ); ?></strong>
        </div>

        <?php if ( ! empty( $n->body ) ): ?>
            <div class="rmbz-na-row-body"><?php echo wp_kses_post( $n->body ); ?></div>
        <?php endif; ?>

        <?php if ( ! empty( $n->action_url ) ): ?>
            <div class="rmbz-na-row-action">
                CTA: <code><?php echo esc_html( $n->action_label ?: 'Ver detalhes' ); ?></code>
                → <a href="<?php echo esc_url( $n->action_url ); ?>" target="_blank"><?php echo esc_html( $n->action_url ); ?></a>
            </div>
        <?php endif; ?>

        <div class="rmbz-na-row-meta">
            <span><strong><?php echo esc_html( $type_label ); ?></strong></span>
            <span>· criada: <?php echo esc_html( $created ); ?></span>
            <span>· expira: <?php echo esc_html( $expires ); ?></span>
            <span>· dispensada por: <strong><?php echo (int) $n->dismissed_count; ?></strong> artista(s)</span>
            <?php if ( ! empty( $n->created_by ) ): ?>
                <span>· por <code><?php echo esc_html( $n->created_by ); ?></code></span>
            <?php endif; ?>
            <?php if ( $is_archived ): ?>
                <span class="rmbz-na-archived-tag">ARQUIVADA</span>
            <?php endif; ?>
        </div>

        <?php if ( ! $is_archived ): ?>
            <div class="rmbz-na-row-actions">
                <form method="post" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" style="display:inline;"
                      onsubmit="return confirm('Arquivar esta notificação? Vai deixar de aparecer para todos os artistas (mas fica no histórico).');">
                    <?php wp_nonce_field('rmbz_notif_admin_archive'); ?>
                    <input type="hidden" name="action" value="rmbz_notif_admin_archive">
                    <input type="hidden" name="notification_id" value="<?php echo (int) $n->id; ?>">
                    <button type="submit" class="rmbz-na-btn rmbz-na-btn-small">📦 Arquivar</button>
                </form>

                <?php if ( $n->dismissed_count > 0 ): ?>
                    <form method="post" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" style="display:inline;"
                          onsubmit="return confirm('Limpar TODAS as <?php echo (int) $n->dismissed_count; ?> dismissals? A notificação vai voltar a aparecer para os artistas que a tinham fechado.');">
                        <?php wp_nonce_field('rmbz_notif_admin_reset'); ?>
                        <input type="hidden" name="action" value="rmbz_notif_admin_reset">
                        <input type="hidden" name="notification_id" value="<?php echo (int) $n->id; ?>">
                        <button type="submit" class="rmbz-na-btn rmbz-na-btn-small">🔄 Repor visibilidade</button>
                    </form>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
    <?php
}


/* ============================================================================
 * 3. CSS da página admin (cores hardcoded, light theme)
 * ============================================================================ */

function rmbz_notif_render_admin_styles() {
    static $printed = false;
    if ( $printed ) return;
    $printed = true;
    ?>
    <style>
    /* [1.5.183] CSS hardcoded para light theme — wp-admin é nativo light. */
    .rmbz-na-wrap {
        width: 100%;
        max-width: 100%;
        font-family: var(--rmbz-font-body, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif);
    }
    .rmbz-na-header { margin: 16px 0 24px 0; }
    .rmbz-na-kicker {
        font-size: 10px;
        color: #888;
        text-transform: uppercase;
        letter-spacing: 1.2px;
        font-weight: 600;
        margin-bottom: 4px;
    }
    .rmbz-na-title {
        font-size: 24px;
        font-weight: 600;
        color: #1a1a1a;
        margin: 0 0 8px 0;
        font-family: var(--rmbz-font-display, inherit);
    }
    .rmbz-na-subtitle {
        font-size: 14px;
        color: #666;
        margin: 0;
        max-width: 900px;
        line-height: 1.5;
    }

    /* Flash messages */
    .rmbz-na-flash {
        padding: 12px 16px;
        border-radius: 8px;
        margin-bottom: 16px;
        font-size: 14px;
        font-weight: 500;
    }
    .rmbz-na-flash--success { background:#d4edda; color:#14532d; border-left: 3px solid #059669; }
    .rmbz-na-flash--danger  { background:#fde4e2; color:#7f1d1d; border-left: 3px solid #dc2626; }

    /* Layout 2 colunas — só em ecrãs realmente largos */
    .rmbz-na-grid {
        display: grid;
        /* [1.5.185] Antes era `420px 1fr`. Em containers com padding ou
           overflow restrito, a coluna direita extravasava (bug reportado
           pelo Jaime). Agora:
             - Coluna esquerda usa minmax(min-content, 420px) — encolhe
               se preciso, nunca passa de 420px
             - Coluna direita usa minmax(0, 1fr) — pode encolher até zero,
               nunca extravasa o container pai
           E o breakpoint mobile sobe para 1300px (antes 1100) porque
           a forma 2-cols só faz sentido em ecrãs realmente largos.
        */
        grid-template-columns: minmax(min-content, 420px) minmax(0, 1fr);
        gap: 20px;
        align-items: start;
    }
    @media (max-width: 1300px) {
        .rmbz-na-grid { grid-template-columns: minmax(0, 1fr); }
    }
    /* Garantir que children dos columns não puxam o grid acima do container */
    .rmbz-na-col-form,
    .rmbz-na-col-list { min-width: 0; }

    /* Cards */
    .rmbz-na-card {
        background: #fff;
        border: 1px solid #e5e5e5;
        border-radius: 10px;
        padding: 16px 20px;
        margin-bottom: 16px;
    }
    .rmbz-na-card-head {
        display: flex;
        justify-content: space-between;
        align-items: baseline;
        gap: 12px;
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 1px solid #f0f0f0;
        flex-wrap: wrap;
    }
    .rmbz-na-card-head strong {
        font-size: 14px;
        color: #1a1a1a;
        font-weight: 600;
    }
    .rmbz-na-card-hint {
        font-size: 11px;
        color: #888;
    }

    /* Form */
    .rmbz-na-form { display: flex; flex-direction: column; gap: 14px; }
    .rmbz-na-field { display: flex; flex-direction: column; gap: 4px; }
    .rmbz-na-label {
        font-size: 12px;
        color: #444;
        font-weight: 600;
    }
    .rmbz-na-form input[type="text"],
    .rmbz-na-form input[type="url"],
    .rmbz-na-form select,
    .rmbz-na-form textarea {
        padding: 8px 10px;
        font-size: 13px;
        border: 1px solid #d8dade;
        border-radius: 6px;
        font-family: inherit;
        color: #1a1a1a;
        background: #fff;
    }
    .rmbz-na-form select { padding-right: 28px; }
    .rmbz-na-form input:focus,
    .rmbz-na-form select:focus,
    .rmbz-na-form textarea:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59,130,246,0.12);
    }
    .rmbz-na-hint {
        font-size: 11px;
        color: #888;
    }
    .rmbz-na-row-2 {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 12px;
    }
    .rmbz-na-radio-group {
        display: flex;
        flex-direction: column;
        gap: 6px;
        background: #f9f9fb;
        border: 1px solid #e5e5e5;
        border-radius: 6px;
        padding: 10px 12px;
    }
    .rmbz-na-radio-group label {
        font-size: 13px;
        color: #1a1a1a;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    /* Buttons */
    .rmbz-na-btn {
        display: inline-block;
        padding: 8px 16px;
        font-size: 13px;
        font-weight: 500;
        border: 1px solid #d8dade;
        background: #fff;
        color: #1a1a1a;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.15s;
        text-decoration: none;
    }
    .rmbz-na-btn:hover {
        background: #f5f5f7;
        border-color: #b0b3b8;
    }
    .rmbz-na-btn-primary {
        background: #3b82f6;
        border-color: #3b82f6;
        color: #fff;
        font-weight: 600;
        padding: 12px 20px;
        font-size: 14px;
    }
    .rmbz-na-btn-primary:hover {
        background: #2563eb;
        border-color: #2563eb;
        color: #fff;
    }
    .rmbz-na-btn-small {
        padding: 6px 12px;
        font-size: 12px;
    }

    /* Lista de notificações */
    .rmbz-na-list {
        display: flex;
        flex-direction: column;
        gap: 12px;
    }
    .rmbz-na-row {
        background: #fafafa;
        border: 1px solid #e5e5e5;
        border-radius: 8px;
        padding: 12px 14px;
    }
    .rmbz-na-row-head {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 6px;
        flex-wrap: wrap;
    }
    .rmbz-na-sev-pill {
        display: inline-block;
        padding: 2px 8px;
        font-size: 11px;
        font-weight: 600;
        border-radius: 4px;
    }
    .rmbz-na-row-title {
        font-size: 14px;
        color: #1a1a1a;
        flex: 1;
        min-width: 0;
    }
    .rmbz-na-row-body {
        font-size: 13px;
        color: #444;
        line-height: 1.5;
        margin-bottom: 8px;
    }
    .rmbz-na-row-action {
        font-size: 12px;
        color: #666;
        background: #fff;
        padding: 6px 10px;
        border-radius: 4px;
        margin-bottom: 8px;
        border-left: 2px solid #3b82f6;
    }
    .rmbz-na-row-action code { background: #f0f0f0; padding: 1px 4px; border-radius: 3px; }
    .rmbz-na-row-action a { color: #3b82f6; }
    .rmbz-na-row-meta {
        display: flex;
        flex-wrap: wrap;
        gap: 6px;
        font-size: 11px;
        color: #666;
        margin-bottom: 8px;
    }
    .rmbz-na-row-meta code { background: #f0f0f0; padding: 1px 4px; border-radius: 3px; font-size: 10px; }
    .rmbz-na-archived-tag {
        background: #888;
        color: #fff;
        padding: 1px 6px;
        border-radius: 3px;
        font-weight: 600;
    }
    .rmbz-na-row-actions {
        display: flex;
        gap: 6px;
        flex-wrap: wrap;
        padding-top: 8px;
        border-top: 1px solid #ebebeb;
    }

    /* Empty */
    .rmbz-na-empty {
        text-align: center;
        padding: 40px 20px;
        color: #888;
    }
    .rmbz-na-empty-icon { font-size: 40px; margin-bottom: 8px; }
    .rmbz-na-empty p { font-size: 13px; margin: 0; }

    /* Archived collapsible */
    .rmbz-na-archived {
        background: #fff;
        border: 1px solid #e5e5e5;
        border-radius: 10px;
        padding: 0;
        margin-bottom: 16px;
    }
    .rmbz-na-archived summary {
        padding: 12px 18px;
        cursor: pointer;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 13px;
        color: #444;
    }
    .rmbz-na-archived summary span { font-weight: 600; }
    .rmbz-na-archived summary small { color: #888; }
    .rmbz-na-archived[open] summary {
        border-bottom: 1px solid #e5e5e5;
        color: #1a1a1a;
    }
    .rmbz-na-archived .rmbz-na-list {
        padding: 16px;
    }
    </style>
    <?php
}
