<?php
/**
 * Wally Monitor - Admin UI
 *
 * Renderização de páginas admin, menu, enqueue de assets e meta boxes.
 *
 * @package    WallyMonitor
 * @subpackage Includes
 * @since      1.1.0
 */

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

class Wally_Admin {

    /**
     * Inicializa hooks do admin
     */
    public static function init() {
        $instance = new self();
        add_action( 'admin_menu', array( $instance, 'register_menu' ) );
        add_action( 'admin_enqueue_scripts', array( $instance, 'enqueue_assets' ) );
        add_action( 'add_meta_boxes', array( $instance, 'add_meta_box' ) );
        add_action( 'save_post', array( $instance, 'analyze_on_save' ) );
    }

    /**
     * Registra menu e submenus no admin
     */
    public function register_menu() {
        add_menu_page(
            'Wally Monitor',
            'Wally Monitor',
            'manage_options',
            'wally-monitor',
            array( $this, 'report_page' ),
            'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAiIGhlaWdodD0iMjAiIHZpZXdCb3g9IjAgMCAyMCAyMCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48Y2lyY2xlIGN4PSIxMCIgY3k9IjEwIiByPSI4IiBmaWxsPSIjOWVhM2E4Ii8+PHBhdGggZD0iTTYgMTBoOCIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIyIi8+PC9zdmc+',
            20
        );

        add_submenu_page( 'wally-monitor', __( 'Relatórios', 'wally-monitor' ), __( 'Relatórios', 'wally-monitor' ), 'manage_options', 'wally-monitor', array( $this, 'report_page' ) );
        add_submenu_page( 'wally-monitor', __( 'Histórico', 'wally-monitor' ), __( 'Histórico', 'wally-monitor' ), 'manage_options', 'wally-monitor-history', array( $this, 'history_page' ) );
        add_submenu_page( 'wally-monitor', __( 'Configurações', 'wally-monitor' ), __( 'Configurações', 'wally-monitor' ), 'manage_options', 'wally-monitor-settings', array( $this, 'settings_page' ) );
    }

    /**
     * Página de relatórios
     */
    public function report_page() {
        $nonce = wp_create_nonce( 'wally_export' );
        $settings_data = get_option( 'wally_monitor_settings', array(
            'analysis_mode' => 'wcag',
        ) );
        ?>
        <div class="wrap wally-monitor-wrap">
            <div class="wally-page-header">
                <img src="<?php echo esc_url( WALLY_MONITOR_PLUGIN_URL . 'assets/images/logo.png' ); ?>" alt="Wally Monitor" class="wally-logo">
                <div class="wally-page-header-text">
                    <h1 class="wally-page-title"><?php esc_html_e( 'Relatório de Acessibilidade', 'wally-monitor' ); ?></h1>
                    <p class="wally-page-subtitle"><?php esc_html_e( 'Analise todo o seu site para encontrar e corrigir problemas de acessibilidade.', 'wally-monitor' ); ?></p>
                </div>
                <span class="wally-badge">v<?php echo esc_html( WALLY_MONITOR_VERSION ); ?></span>
            </div>

            <button id="wally-run-full-scan" class="wally-btn-primary">
                <span class="wally-btn-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg></span>
                <?php esc_html_e( 'Analisar Site Completo', 'wally-monitor' ); ?>
            </button>

            <div id="wally-analysis-mode-selector" class="wally-scanner-mode-toggle-wrap" style="margin-top: 12px;">
                <?php
                $current_analysis_mode = isset( $settings_data['analysis_mode'] ) ? $settings_data['analysis_mode'] : 'wcag';
                ?>
                <span class="wally-mode-label"><?php esc_html_e( 'Modo de análise:', 'wally-monitor' ); ?></span>
                <div class="wally-scanner-mode-toggle" role="radiogroup" aria-label="<?php esc_attr_e( 'Modo de análise', 'wally-monitor' ); ?>">
                    <button type="button" class="wally-scanner-mode-btn<?php echo 'wcag' === $current_analysis_mode ? ' active' : ''; ?>" data-mode="wcag" role="radio" aria-checked="<?php echo 'wcag' === $current_analysis_mode ? 'true' : 'false'; ?>">
                        <svg class="wally-mode-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
                        <span>WCAG 2.2</span>
                    </button>
                    <button type="button" class="wally-scanner-mode-btn<?php echo 'nbr' === $current_analysis_mode ? ' active' : ''; ?>" data-mode="nbr" role="radio" aria-checked="<?php echo 'nbr' === $current_analysis_mode ? 'true' : 'false'; ?>">
                        <svg class="wally-mode-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/></svg>
                        <span>NBR 17.225</span>
                    </button>
                </div>
                <span id="wally-mode-info" class="wally-mode-info"></span>
            </div>

            <div id="wally-full-scan-progress"></div>

            <div id="wally-report-container" style="display:none; margin-top: 24px;">
                <div class="report-header">
                    <h2><?php esc_html_e( 'Resultados da Análise', 'wally-monitor' ); ?></h2>
                    <div class="wally-export-actions">
                        <a href="<?php echo esc_url( admin_url( 'admin.php?page=wally-monitor&export=pdf&_wpnonce=' . $nonce ) ); ?>" class="button wally-export-btn" aria-label="<?php esc_attr_e( 'Exportar relatório em PDF', 'wally-monitor' ); ?>" title="<?php esc_attr_e( 'Exportar PDF', 'wally-monitor' ); ?>">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                            PDF
                        </a>
                        <a href="<?php echo esc_url( admin_url( 'admin.php?page=wally-monitor&export=csv&_wpnonce=' . $nonce ) ); ?>" class="button wally-export-btn" aria-label="<?php esc_attr_e( 'Exportar relatório em CSV', 'wally-monitor' ); ?>" title="<?php esc_attr_e( 'Exportar CSV', 'wally-monitor' ); ?>">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="9" y1="3" x2="9" y2="21"/></svg>
                            CSV
                        </a>
                        <a href="<?php echo esc_url( admin_url( 'admin.php?page=wally-monitor&export=json&_wpnonce=' . $nonce ) ); ?>" class="button wally-export-btn" aria-label="<?php esc_attr_e( 'Exportar relatório em JSON', 'wally-monitor' ); ?>" title="<?php esc_attr_e( 'Exportar JSON', 'wally-monitor' ); ?>">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
                            JSON
                        </a>
                    </div>
                </div>
                <div id="wally-summary"></div>
                <div id="wally-results"></div>
            </div>
        </div>
        <?php
    }

    /**
     * Página de histórico
     */
    public function history_page() {
        ?>
        <div class="wrap wally-monitor-wrap">
            <div class="wally-page-header">
                <img src="<?php echo esc_url( WALLY_MONITOR_PLUGIN_URL . 'assets/images/logo.png' ); ?>" alt="Wally Monitor" class="wally-logo">
                <div class="wally-page-header-text">
                    <h1 class="wally-page-title"><?php esc_html_e( 'Histórico de Análises', 'wally-monitor' ); ?></h1>
                    <p class="wally-page-subtitle"><?php esc_html_e( 'Acompanhe a evolução da acessibilidade do seu site ao longo do tempo.', 'wally-monitor' ); ?></p>
                </div>
                <span class="wally-badge">v<?php echo esc_html( WALLY_MONITOR_VERSION ); ?></span>
            </div>

            <!-- Gráfico de evolução temporal -->
            <div class="wally-card wally-history-chart-wrap wally-fade-in wally-stagger-1">
                <div class="wally-history-chart-header">
                    <h2 class="wally-card-title"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -2px; margin-right: 4px;"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg> <?php esc_html_e( 'Evolução do Score de Acessibilidade', 'wally-monitor' ); ?></h2>
                    <label class="wally-history-toggle" for="wally-toggle-problems">
                        <input type="checkbox" id="wally-toggle-problems">
                        <span><?php esc_html_e( 'Mostrar quantidade de erros', 'wally-monitor' ); ?></span>
                    </label>
                </div>
                <canvas id="wally-history-chart" style="max-height: 400px;"></canvas>
            </div>

            <!-- Tabela de histórico -->
            <div class="wally-card wally-fade-in wally-stagger-2">
                <h2 class="wally-card-title"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -2px; margin-right: 4px;"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg> <?php esc_html_e( 'Histórico Detalhado', 'wally-monitor' ); ?></h2>
                <?php
                $history = get_option( 'wally_monitor_history', array() );
                if ( empty( $history ) ) {
                    ?>
                    <div class="wally-empty-state">
                        <span class="wally-empty-state-icon"><svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg></span>
                        <p><?php esc_html_e( 'Nenhuma análise realizada ainda.', 'wally-monitor' ); ?></p>
                        <a href="<?php echo esc_url( admin_url( 'admin.php?page=wally-monitor' ) ); ?>" class="wally-btn-primary"><?php esc_html_e( 'Execute uma análise agora', 'wally-monitor' ); ?></a>
                    </div>
                    <?php
                } else {
                    echo '<div class="wally-table-wrap">';
                    echo '<table class="wally-table">';
                    echo '<thead><tr><th>' . esc_html__( 'Data/Hora', 'wally-monitor' ) . '</th><th>' . esc_html__( 'Usuário', 'wally-monitor' ) . '</th><th>' . esc_html__( 'Norma', 'wally-monitor' ) . '</th><th>' . esc_html__( 'Problemas', 'wally-monitor' ) . '</th><th>' . esc_html__( 'Score', 'wally-monitor' ) . '</th></tr></thead>';
                    echo '<tbody>';
                    foreach ( $history as $item ) {
                        $user     = get_userdata( $item['user_id'] );
                        $username = $user ? $user->display_name : __( 'Desconhecido', 'wally-monitor' );
                        if ( $item['score'] >= 90 ) {
                            $pill_class = 'excellent';
                        } elseif ( $item['score'] >= 70 ) {
                            $pill_class = 'good';
                        } else {
                            $pill_class = 'poor';
                        }
                        $mode_key   = isset( $item['analysis_mode'] ) ? $item['analysis_mode'] : 'wcag';
                        $mode_label = 'nbr' === $mode_key ? 'NBR 17.225' : 'WCAG 2.2';
                        $mode_class = 'nbr' === $mode_key ? 'wally-mode-badge--nbr' : 'wally-mode-badge--wcag';
                        echo '<tr>';
                        echo '<td>' . esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $item['timestamp'] ) ) ) . '</td>';
                        echo '<td>' . esc_html( $username ) . '</td>';
                        echo '<td><span class="wally-mode-badge ' . esc_attr( $mode_class ) . '">' . esc_html( $mode_label ) . '</span></td>';
                        echo '<td><strong>' . esc_html( $item['total_problems'] ) . '</strong></td>';
                        echo '<td><span class="wally-score-pill ' . esc_attr( $pill_class ) . '"><span class="wally-score-dot"></span>' . esc_html( $item['score'] ) . '/100</span></td>';
                        echo '</tr>';
                    }
                    echo '</tbody></table>';
                    echo '</div>';
                }
                ?>
            </div>
        </div>
        <?php
    }

    /**
     * Página de configurações
     */
    public function settings_page() {
        // Salva configurações gerais
        if ( isset( $_POST['wally_monitor_save_settings'] ) && check_admin_referer( 'wally_monitor_settings' ) ) {
            $settings = array(
                'post_types'     => isset( $_POST['post_types'] ) ? array_map( 'sanitize_key', wp_unslash( $_POST['post_types'] ) ) : array( 'post', 'page' ),
                'include_home'   => isset( $_POST['include_home'] ),
                'max_urls'       => isset( $_POST['max_urls'] ) ? intval( $_POST['max_urls'] ) : 100,
                'wcag_level'     => isset( $_POST['wcag_level'] ) ? sanitize_text_field( wp_unslash( $_POST['wcag_level'] ) ) : 'AA',
                'analysis_mode'  => isset( $_POST['analysis_mode'] ) ? sanitize_key( wp_unslash( $_POST['analysis_mode'] ) ) : 'wcag',
            );
            update_option( 'wally_monitor_settings', $settings );

            // Salva configurações de cron
            $cron_enabled  = isset( $_POST['cron_enabled'] );
            $cron_freq     = isset( $_POST['cron_frequency'] ) ? sanitize_key( wp_unslash( $_POST['cron_frequency'] ) ) : 'weekly';
            $cron_settings = array(
                'max_urls'     => isset( $_POST['cron_max_urls'] ) ? intval( $_POST['cron_max_urls'] ) : 20,
                'notify_email' => isset( $_POST['cron_notify_email'] ) ? sanitize_email( wp_unslash( $_POST['cron_notify_email'] ) ) : '',
                'notify_on'    => isset( $_POST['cron_notify_on'] ) ? sanitize_key( wp_unslash( $_POST['cron_notify_on'] ) ) : 'threshold',
                'threshold'    => isset( $_POST['cron_threshold'] ) ? intval( $_POST['cron_threshold'] ) : 70,
            );
            update_option( 'wally_monitor_cron_settings', $cron_settings );

            if ( $cron_enabled ) {
                Wally_Cron::enable( $cron_freq );
            } else {
                Wally_Cron::disable();
            }

            // Redirect-after-POST para evitar re-submissão no refresh
            wp_safe_redirect( add_query_arg( 'wally_saved', '1' ) );
            exit;
        }

        // Exibe aviso de sucesso após redirecionamento
        if ( isset( $_GET['wally_saved'] ) ) {
            echo '<div class="notice notice-success"><p>' . esc_html__( 'Configurações salvas com sucesso!', 'wally-monitor' ) . '</p></div>';
        }

        $settings = get_option( 'wally_monitor_settings', array(
            'post_types'     => array( 'post', 'page' ),
            'include_home'   => true,
            'max_urls'       => 100,
            'wcag_level'     => 'AA',
            'analysis_mode'  => 'wcag',
        ) );

        // Ensure analysis_mode key exists for upgrades
        if ( ! isset( $settings['analysis_mode'] ) ) {
            $settings['analysis_mode'] = 'wcag';
        }

        $cron_settings = get_option( 'wally_monitor_cron_settings', array(
            'max_urls'     => 20,
            'notify_email' => '',
            'notify_on'    => 'threshold',
            'threshold'    => 70,
        ) );

        $cron_enabled   = Wally_Cron::is_enabled();
        $cron_frequency = get_option( 'wally_monitor_cron_frequency', 'weekly' );
        $cron_next      = wp_next_scheduled( 'wally_monitor_cron_scan' );

        $all_post_types = get_post_types( array( 'public' => true ), 'objects' );
        ?>
        <div class="wrap wally-settings-wrap">
            <div class="wally-page-header">
                <img src="<?php echo esc_url( WALLY_MONITOR_PLUGIN_URL . 'assets/images/logo.png' ); ?>" alt="Wally Monitor" class="wally-logo" style="width:48px; height:48px;">
                <div class="wally-page-header-text">
                    <h1 class="wally-page-title"><?php esc_html_e( 'Configurações', 'wally-monitor' ); ?></h1>
                    <p class="wally-page-subtitle"><?php esc_html_e( 'Personalize o comportamento do Wally Monitor para o seu site.', 'wally-monitor' ); ?></p>
                </div>
                <span class="wally-badge">v<?php echo esc_html( WALLY_MONITOR_VERSION ); ?></span>
            </div>

            <form method="post" action="">
                <?php wp_nonce_field( 'wally_monitor_settings' ); ?>

                <!-- Configurações Gerais -->
                <div class="wally-settings-section wally-fade-in wally-stagger-1">
                    <h2 class="wally-settings-section-title">⚙️ <?php esc_html_e( 'Configurações Gerais', 'wally-monitor' ); ?></h2>

                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php esc_html_e( 'Tipos de Conteúdo', 'wally-monitor' ); ?></th>
                            <td>
                                <fieldset>
                                    <legend class="screen-reader-text"><?php esc_html_e( 'Tipos de Conteúdo para Analisar', 'wally-monitor' ); ?></legend>
                                    <?php foreach ( $all_post_types as $post_type ) : ?>
                                        <label class="wally-checkbox-label">
                                            <input type="checkbox" name="post_types[]" value="<?php echo esc_attr( $post_type->name ); ?>"
                                                <?php checked( in_array( $post_type->name, $settings['post_types'], true ) ); ?>>
                                            <span><?php echo esc_html( $post_type->label ); ?></span>
                                        </label>
                                    <?php endforeach; ?>
                                </fieldset>
                                <p class="description"><?php esc_html_e( 'Selecione quais tipos de conteúdo devem ser incluídos na análise completa.', 'wally-monitor' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e( 'Página Inicial', 'wally-monitor' ); ?></th>
                            <td>
                                <label class="wally-checkbox-label">
                                    <input type="checkbox" name="include_home" value="1" <?php checked( ! empty( $settings['include_home'] ) ); ?>>
                                    <span><?php esc_html_e( 'Incluir a página inicial (home) na análise', 'wally-monitor' ); ?></span>
                                </label>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="max_urls"><?php esc_html_e( 'Limite de URLs', 'wally-monitor' ); ?></label></th>
                            <td>
                                <input type="number" name="max_urls" id="max_urls" value="<?php echo esc_attr( $settings['max_urls'] ); ?>" min="1" max="500" class="small-text">
                                <p class="description"><?php esc_html_e( 'Número máximo de páginas a analisar (recomendado: 50-100 para melhor performance).', 'wally-monitor' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="wcag_level"><?php esc_html_e( 'Nível WCAG Padrão', 'wally-monitor' ); ?></label></th>
                            <td>
                                <select name="wcag_level" id="wcag_level">
                                    <option value="A" <?php selected( $settings['wcag_level'], 'A' ); ?>><?php esc_html_e( 'Nível A (Básico)', 'wally-monitor' ); ?></option>
                                    <option value="AA" <?php selected( $settings['wcag_level'], 'AA' ); ?>><?php esc_html_e( 'Nível AA (Recomendado)', 'wally-monitor' ); ?></option>
                                    <option value="AAA" <?php selected( $settings['wcag_level'], 'AAA' ); ?>><?php esc_html_e( 'Nível AAA (Avançado)', 'wally-monitor' ); ?></option>
                                </select>
                                <p class="description"><?php esc_html_e( 'Define o nível de conformidade WCAG para as análises.', 'wally-monitor' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="analysis_mode"><?php esc_html_e( 'Modo de Análise', 'wally-monitor' ); ?></label></th>
                            <td>
                                <select name="analysis_mode" id="analysis_mode">
                                    <option value="wcag" <?php selected( $settings['analysis_mode'], 'wcag' ); ?>>🌐 <?php esc_html_e( 'WCAG 2.2 — Padrão internacional', 'wally-monitor' ); ?></option>
                                    <option value="nbr" <?php selected( $settings['analysis_mode'], 'nbr' ); ?>>🇧🇷 <?php esc_html_e( 'NBR 17.225 — Regras brasileiras exclusivas', 'wally-monitor' ); ?></option>
                                </select>
                                <p class="description">
                                    <strong><?php esc_html_e( 'WCAG 2.2:', 'wally-monitor' ); ?></strong> <?php esc_html_e( 'Motor de análise WCAG 2.2 (padrão internacional, ~90 regras).', 'wally-monitor' ); ?><br>
                                    <strong><?php esc_html_e( 'NBR 17.225:', 'wally-monitor' ); ?></strong> <?php esc_html_e( 'Apenas as regras brasileiras exclusivas do Wally (118 regras customizadas).', 'wally-monitor' ); ?>
                                </p>
                            </td>
                        </tr>
                    </table>
                </div>

                <!-- Análise Automatizada -->
                <div class="wally-settings-section wally-fade-in wally-stagger-2">
                    <h2 class="wally-settings-section-title">⏰ <?php esc_html_e( 'Análise Automatizada', 'wally-monitor' ); ?></h2>

                    <?php if ( $cron_enabled && $cron_next ) : ?>
                        <div class="wally-cron-status">
                            <span class="wally-cron-status-dot"></span>
                            📅 <?php esc_html_e( 'Próxima análise agendada:', 'wally-monitor' ); ?> <strong><?php echo esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $cron_next ) ); ?></strong>
                        </div>
                    <?php endif; ?>

                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php esc_html_e( 'Análise Automática', 'wally-monitor' ); ?></th>
                            <td>
                                <label class="wally-checkbox-label">
                                    <input type="checkbox" name="cron_enabled" value="1" <?php checked( $cron_enabled ); ?>>
                                    <span><?php esc_html_e( 'Habilitar análises automatizadas periódicas', 'wally-monitor' ); ?></span>
                                </label>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="cron_frequency"><?php esc_html_e( 'Frequência', 'wally-monitor' ); ?></label></th>
                            <td>
                                <select name="cron_frequency" id="cron_frequency">
                                    <option value="hourly" <?php selected( $cron_frequency, 'hourly' ); ?>><?php esc_html_e( 'A cada hora', 'wally-monitor' ); ?></option>
                                    <option value="daily" <?php selected( $cron_frequency, 'daily' ); ?>><?php esc_html_e( 'Diário', 'wally-monitor' ); ?></option>
                                    <option value="weekly" <?php selected( $cron_frequency, 'weekly' ); ?>><?php esc_html_e( 'Semanal', 'wally-monitor' ); ?></option>
                                    <option value="monthly" <?php selected( $cron_frequency, 'monthly' ); ?>><?php esc_html_e( 'Mensal', 'wally-monitor' ); ?></option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="cron_max_urls"><?php esc_html_e( 'Máximo de URLs', 'wally-monitor' ); ?></label></th>
                            <td>
                                <input type="number" name="cron_max_urls" id="cron_max_urls" value="<?php echo esc_attr( $cron_settings['max_urls'] ); ?>" min="1" max="100" class="small-text">
                                <p class="description"><?php esc_html_e( 'Limite de páginas analisadas a cada execução automática.', 'wally-monitor' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="cron_notify_email"><?php esc_html_e( 'E-mail de Notificação', 'wally-monitor' ); ?></label></th>
                            <td>
                                <input type="email" name="cron_notify_email" id="cron_notify_email" value="<?php echo esc_attr( $cron_settings['notify_email'] ); ?>" class="regular-text" placeholder="<?php echo esc_attr( get_option( 'admin_email' ) ); ?>">
                                <p class="description"><?php esc_html_e( 'Deixe em branco para usar o e-mail do administrador.', 'wally-monitor' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="cron_notify_on"><?php esc_html_e( 'Notificar Quando', 'wally-monitor' ); ?></label></th>
                            <td>
                                <select name="cron_notify_on" id="cron_notify_on">
                                    <option value="always" <?php selected( $cron_settings['notify_on'], 'always' ); ?>><?php esc_html_e( 'Sempre', 'wally-monitor' ); ?></option>
                                    <option value="threshold" <?php selected( $cron_settings['notify_on'], 'threshold' ); ?>><?php esc_html_e( 'Apenas abaixo do limiar', 'wally-monitor' ); ?></option>
                                    <option value="never" <?php selected( $cron_settings['notify_on'], 'never' ); ?>><?php esc_html_e( 'Nunca', 'wally-monitor' ); ?></option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="cron_threshold"><?php esc_html_e( 'Limiar de Score', 'wally-monitor' ); ?></label></th>
                            <td>
                                <input type="number" name="cron_threshold" id="cron_threshold" value="<?php echo esc_attr( $cron_settings['threshold'] ); ?>" min="0" max="100" class="small-text">
                                <p class="description"><?php esc_html_e( 'Notificar apenas quando o score estiver abaixo deste valor.', 'wally-monitor' ); ?></p>
                            </td>
                        </tr>
                    </table>
                </div>

                <div class="wally-settings-submit">
                    <button type="submit" name="wally_monitor_save_settings" class="wally-btn-primary">
                        <span class="wally-btn-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg></span>
                        <?php esc_html_e( 'Salvar Configurações', 'wally-monitor' ); ?>
                    </button>
                </div>
            </form>
        </div>
        <?php
    }

    /**
     * Enfileira scripts e estilos do admin
     *
     * @param string $hook Hook da página atual.
     */
    public function enqueue_assets( $hook ) {
        $allowed_hooks = array(
            'toplevel_page_wally-monitor',
            'wally-monitor_page_wally-monitor-history',
            'wally-monitor_page_wally-monitor-settings',
            'post.php',
            'post-new.php',
        );

        if ( ! in_array( $hook, $allowed_hooks, true ) ) {
            return;
        }

        // Chart.js para histórico
        if ( 'wally-monitor_page_wally-monitor-history' === $hook ) {
            wp_enqueue_script( 'wally-chartjs', plugin_dir_url( WALLY_MONITOR_PLUGIN_DIR . 'wally-monitor.php' ) . 'assets/js/lib/chart.umd.min.js', array(), '4.5.1', true );

            $history = get_option( 'wally_monitor_history', array() );
            wp_add_inline_script( 'wally-chartjs', 'var wallyHistoryData = ' . wp_json_encode( $history ) . ';', 'before' );
        }

        // CSS (always needed on all admin pages)
        wp_enqueue_style( 'wally-monitor-admin-css', WALLY_MONITOR_PLUGIN_URL . 'assets/css/wally-monitor-admin.css', array(), WALLY_MONITOR_VERSION );

        // Determine which pages need the scanner engine (axe-core + rule modules)
        $needs_scanner = in_array( $hook, array(
            'toplevel_page_wally-monitor',
            'post.php',
            'post-new.php',
        ), true );

        // axe-core — only on pages that run scans
        if ( $needs_scanner ) {
            wp_enqueue_script( 'axe-core', WALLY_MONITOR_PLUGIN_URL . 'assets/js/axe.min.js', array(), WALLY_MONITOR_VERSION, true );
        }

        // ── JS Modules ─────────────────────────────────────────────
        // Core utils (always needed)
        $js_modules = array(
            'wally-utils'      => array( 'deps' => array( 'jquery' ), 'file' => 'wally-utils.js' ),
            'wally-onboarding' => array( 'deps' => array( 'jquery', 'wally-utils' ), 'file' => 'wally-onboarding.js' ),
        );

        // Scanner + rules engine modules — only on scan-capable pages
        if ( $needs_scanner ) {
            $js_modules = array_merge( $js_modules, array(
                'wally-rule-helpers'  => array( 'deps' => array( 'jquery' ), 'file' => 'wally-rule-helpers.js' ),
                'wally-custom-rules' => array( 'deps' => array( 'jquery', 'wally-utils' ), 'file' => 'wally-custom-rules.js' ),
                'wally-nbr-rules'    => array( 'deps' => array( 'jquery', 'wally-utils', 'wally-rule-helpers' ), 'file' => 'wally-nbr-rules.js' ),
                'wally-ifthen-rules' => array( 'deps' => array( 'jquery', 'wally-utils', 'wally-rule-helpers' ), 'file' => 'wally-ifthen-rules.js' ),
                'wally-quickfix'     => array( 'deps' => array( 'jquery', 'wally-utils' ), 'file' => 'wally-quickfix.js' ),
                'wally-stats'        => array( 'deps' => array( 'jquery', 'wally-utils' ), 'file' => 'wally-stats.js' ),
                'wally-report'       => array( 'deps' => array( 'jquery', 'wally-utils', 'wally-stats' ), 'file' => 'wally-report.js' ),
                'wally-analysis-modes' => array( 'deps' => array( 'jquery', 'axe-core', 'wally-utils', 'wally-custom-rules', 'wally-nbr-rules', 'wally-ifthen-rules' ), 'file' => 'wally-analysis-modes.js' ),
                'wally-scanner'      => array( 'deps' => array( 'jquery', 'wally-analysis-modes', 'wally-stats', 'wally-report' ), 'file' => 'wally-scanner.js' ),
                'wally-ui'           => array( 'deps' => array( 'jquery', 'wally-utils', 'wally-quickfix' ), 'file' => 'wally-ui.js' ),
                'wally-editor'       => array( 'deps' => array( 'jquery', 'wally-analysis-modes', 'wally-report', 'wally-ui' ), 'file' => 'wally-editor.js' ),
                'wally-admin'        => array( 'deps' => array( 'jquery', 'wally-scanner', 'wally-ui', 'wally-editor', 'wally-chart' ), 'file' => 'wally-admin.js' ),
            ) );
        }

        // Chart module — always (used by history page and dashboard gauge)
        $js_modules['wally-chart'] = array( 'deps' => array( 'jquery' ), 'file' => 'wally-chart.js' );

        foreach ( $js_modules as $handle => $config ) {
            wp_enqueue_script(
                $handle,
                WALLY_MONITOR_PLUGIN_URL . 'assets/js/' . $config['file'],
                $config['deps'],
                WALLY_MONITOR_VERSION,
                true
            );
        }

        // Dados PHP → JavaScript
        $current_settings = get_option( 'wally_monitor_settings', array(
            'wcag_level'    => 'AA',
            'analysis_mode' => 'wcag',
        ) );
        wp_localize_script( 'wally-utils', 'wallyData', array(
            'ajax_url'     => admin_url( 'admin-ajax.php' ),
            'nonce'        => wp_create_nonce( 'wally-monitor-nonce' ),
            'hook'         => $hook,
            'postId'       => get_the_ID(),
            'siteUrl'      => site_url(),
            'wcagLevel'    => isset( $current_settings['wcag_level'] ) ? $current_settings['wcag_level'] : 'AA',
            'analysisMode' => isset( $current_settings['analysis_mode'] ) ? $current_settings['analysis_mode'] : 'wcag',
            'pluginVer'    => WALLY_MONITOR_VERSION,
        ) );

        // i18n — permite uso de wp.i18n.__() nos módulos JS.
        foreach ( array_keys( $js_modules ) as $handle ) {
            wp_set_script_translations( $handle, 'wally-monitor', WALLY_MONITOR_PLUGIN_DIR . 'languages' );
        }
    }

    /**
     * Adiciona meta box no editor de posts
     */
    public function add_meta_box() {
        add_meta_box(
            'wally_monitor_meta_box',
            __( 'Wally Monitor - Acessibilidade', 'wally-monitor' ),
            array( $this, 'meta_box_html' ),
            array( 'post', 'page' ),
            'side',
            'high'
        );
    }

    /**
     * Renderiza conteúdo do meta box
     *
     * @param WP_Post $post Post atual.
     */
    public function meta_box_html( $post ) {
        $settings_data   = get_option( 'wally_monitor_settings', array( 'analysis_mode' => 'wcag' ) );
        $current_mode    = isset( $settings_data['analysis_mode'] ) ? $settings_data['analysis_mode'] : 'wcag';
        ?>
        <div id="wally-editor-report">
            <p class="wally-meta-intro"><?php esc_html_e( 'Analisa a página renderizada completa (header, conteúdo, footer) — mesma análise do scan do site.', 'wally-monitor' ); ?></p>

            <div class="wally-meta-mode-toggle" role="radiogroup" aria-label="<?php esc_attr_e( 'Modo de análise', 'wally-monitor' ); ?>">
                <button type="button" class="wally-meta-mode-btn<?php echo 'wcag' === $current_mode ? ' active' : ''; ?>" data-mode="wcag" data-label="WCAG 2.2" role="radio" aria-checked="<?php echo 'wcag' === $current_mode ? 'true' : 'false'; ?>">
                    <span class="wally-meta-mode-icon">🌐</span>
                    <span class="wally-meta-mode-text">WCAG 2.2</span>
                </button>
                <button type="button" class="wally-meta-mode-btn<?php echo 'nbr' === $current_mode ? ' active' : ''; ?>" data-mode="nbr" data-label="NBR 17.225" role="radio" aria-checked="<?php echo 'nbr' === $current_mode ? 'true' : 'false'; ?>">
                    <span class="wally-meta-mode-icon">🇧🇷</span>
                    <span class="wally-meta-mode-text">NBR 17.225</span>
                </button>
            </div>
            <div id="wally-meta-mode-feedback" class="wally-meta-mode-feedback" aria-live="polite"></div>

            <div id="wally-editor-results">
                <p class="wally-meta-ready">
                    👇 <?php esc_html_e( 'Pronto para analisar', 'wally-monitor' ); ?>
                </p>
            </div>
            <button type="button" id="wally-run-editor-scan" class="wally-meta-scan-btn">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -2px;"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg> <?php esc_html_e( 'Analisar Acessibilidade', 'wally-monitor' ); ?>
            </button>
        </div>
        <script>
        (function() {
            var btns = document.querySelectorAll('.wally-meta-mode-btn');
            var feedback = document.getElementById('wally-meta-mode-feedback');
            var hideTimer = null;

            /* Inicia oculto */
            if (feedback) {
                feedback.style.cssText = 'max-height:0;opacity:0;padding:0;transition:none;';
            }

            function showFeedback(label) {
                if (!feedback) return;
                clearTimeout(hideTimer);
                /* Reset */
                feedback.style.transition = 'none';
                feedback.style.maxHeight = '0';
                feedback.style.opacity = '0';
                feedback.style.padding = '0';
                feedback.textContent = '\u2713 Modo: ' + label;

                /* Força reflow para garantir reset */
                void feedback.offsetHeight;

                /* Anima entrada */
                feedback.style.transition = 'max-height 0.4s ease, opacity 0.4s ease, padding 0.4s ease';
                feedback.style.maxHeight = '28px';
                feedback.style.opacity = '1';
                feedback.style.padding = '5px 0 2px 0';

                /* Auto-hide após 2.5s */
                hideTimer = setTimeout(function() {
                    feedback.style.transition = 'max-height 0.3s ease, opacity 0.3s ease, padding 0.3s ease';
                    feedback.style.maxHeight = '0';
                    feedback.style.opacity = '0';
                    feedback.style.padding = '0';
                }, 2500);
            }

            btns.forEach(function(btn) {
                btn.addEventListener('click', function() {
                    if (this.classList.contains('active')) return;
                    btns.forEach(function(b) {
                        b.classList.remove('active');
                        b.setAttribute('aria-checked', 'false');
                    });
                    this.classList.add('active');
                    this.setAttribute('aria-checked', 'true');
                    if (typeof wallyData !== 'undefined') {
                        wallyData.analysisMode = this.getAttribute('data-mode');
                    }
                    showFeedback(this.getAttribute('data-label'));
                });
            });
        })();
        </script>
        <?php
    }

    /**
     * Marca post para re-análise ao salvar
     *
     * @param int $post_id ID do post.
     */
    public function analyze_on_save( $post_id ) {
        if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
            return;
        }

        // Capability check — only users who can edit the post
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        // Nonce check — verify this is a legitimate WordPress save action
        if ( ! isset( $_POST['_wpnonce'] ) ) {
            return;
        }

        $post_type = get_post_type( $post_id );
        if ( ! $post_type ) {
            return;
        }

        // Verify the WordPress core nonce for the post type
        $nonce_action = 'update-post_' . $post_id;
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        if ( ! wp_verify_nonce( wp_unslash( $_POST['_wpnonce'] ), $nonce_action ) ) {
            return;
        }

        update_post_meta( $post_id, '_wally_needs_reanalysis', 'true' );
    }
}
