<?php

namespace VulnTitan\Admin;

use VulnTitan\Admin\Pages\Dashboard;
use VulnTitan\Admin\Pages\Firewall;
use VulnTitan\Admin\Pages\LiveFeed;
use VulnTitan\Services\FirewallService;

class Admin 
{
    protected function assetVersion(string $relativePath): string
    {
        $file = VULNTITAN_PLUGIN_DIR . '/' . ltrim($relativePath, '/');

        if (!file_exists($file)) {
            return (string) VULNTITAN_PLUGIN_VERSION;
        }

        $mtime = filemtime($file);
        return $mtime !== false ? (string) $mtime : (string) VULNTITAN_PLUGIN_VERSION;
    }

    public function init(): void
    {
        if (is_admin()) {
            add_action('admin_menu', [$this, 'addAdminMenu']);
            add_action('admin_notices', [$this, 'renderApprovalsNotice']);
        }

        add_action('admin_enqueue_scripts', [$this, 'enqueueAssets']);

        (new Ajax())->register();
    }

    public function enqueueAssets($hook)
    {
        $isDev = defined('VULNTITAN_DEVELOPMENT') && VULNTITAN_DEVELOPMENT === true;

        $cssSuffix = $isDev ? '' : '.min';
        $jsSuffix  = $isDev ? '' : '.min';

        wp_enqueue_style(
            'vulntitan-admin-global',
            VULNTITAN_PLUGIN_URL . "/assets/css/admin-global{$cssSuffix}.css",
            [],
            $this->assetVersion("assets/css/admin-global{$cssSuffix}.css")
        );

        $isDashboardPage = $hook === 'toplevel_page_vulntitan';
        $isFirewallPage = $hook === 'vulntitan_page_vulntitan-firewall';
        $isLiveFeedPage = $hook === 'vulntitan_page_vulntitan-live-feed';

        if (!$isDashboardPage && !$isFirewallPage && !$isLiveFeedPage) {
            return;
        }

        wp_enqueue_style(
            'vulntitan-admin',
            VULNTITAN_PLUGIN_URL . "/assets/css/admin{$cssSuffix}.css",
            [],
            $this->assetVersion("assets/css/admin{$cssSuffix}.css")
        );

        wp_enqueue_script('updates');

        wp_register_script(
            'vulntitan-core', 
            VULNTITAN_PLUGIN_URL . "/assets/js/core.js", 
            ['jquery'], 
            $this->assetVersion('assets/js/core.js'), 
            true
        );

        wp_register_script(
            'vulntitan-malware-scanner',
            VULNTITAN_PLUGIN_URL . "/assets/js/malware-scanner{$jsSuffix}.js",
            ['jquery'],
            $this->assetVersion("assets/js/malware-scanner{$jsSuffix}.js"),
            true
        );

        wp_register_script(
            'vulntitan-integrity-scanner',
            VULNTITAN_PLUGIN_URL . "/assets/js/integrity-scanner{$jsSuffix}.js",
            ['jquery'],
            $this->assetVersion("assets/js/integrity-scanner{$jsSuffix}.js"),
            true
        );

        wp_register_script(
            'vulntitan-vulnerability-scanner',
            VULNTITAN_PLUGIN_URL . "/assets/js/vulnerability-scanner{$jsSuffix}.js",
            ['jquery'],
            $this->assetVersion("assets/js/vulnerability-scanner{$jsSuffix}.js"),
            true
        );

        wp_register_script(
            'vulntitan-firewall',
            VULNTITAN_PLUGIN_URL . "/assets/js/firewall{$jsSuffix}.js",
            ['jquery'],
            $this->assetVersion("assets/js/firewall{$jsSuffix}.js"),
            true
        );

        if ($isFirewallPage || $isLiveFeedPage) {
            wp_localize_script('vulntitan-firewall', 'VulnTitan', [
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce'   => wp_create_nonce('vulntitan_ajax_scan'),
                'i18n' => [
                    'firewall_loading' => esc_html__('Loading firewall data...', 'vulntitan'),
                    'firewall_load_failed' => esc_html__('Failed to load firewall data.', 'vulntitan'),
                    'firewall_settings_saved' => esc_html__('Firewall settings saved.', 'vulntitan'),
                    'firewall_save_failed' => esc_html__('Failed to save firewall settings.', 'vulntitan'),
                    'firewall_logs_cleared' => esc_html__('Firewall logs cleared.', 'vulntitan'),
                    'firewall_clear_failed' => esc_html__('Failed to clear firewall logs.', 'vulntitan'),
                    'firewall_confirm_clear' => esc_html__('Clear firewall log history?', 'vulntitan'),
                    'firewall_overview_total' => esc_html__('Events (24h)', 'vulntitan'),
                    'firewall_overview_blocked' => esc_html__('Blocked (24h)', 'vulntitan'),
                    'firewall_overview_forms_blocked' => esc_html__('Forms Blocked (24h)', 'vulntitan'),
                    'firewall_overview_login_failed' => esc_html__('Login Failed (24h)', 'vulntitan'),
                    'firewall_overview_lockouts' => esc_html__('Lockouts (24h)', 'vulntitan'),
                    'firewall_overview_spam_blocked' => esc_html__('Spam Blocked (24h)', 'vulntitan'),
                    'firewall_overview_spam_held' => esc_html__('Spam Held (24h)', 'vulntitan'),
                    'firewall_mu_active' => esc_html__('MU loader active', 'vulntitan'),
                    'firewall_mu_inactive' => esc_html__('MU loader inactive', 'vulntitan'),
                    'firewall_no_logs' => esc_html__('No firewall events recorded yet.', 'vulntitan'),
                    'firewall_no_filtered_logs' => esc_html__('No events match the current filters.', 'vulntitan'),
                    'firewall_custom_login_disabled' => esc_html__('Custom login URL is disabled. Leave the slug blank to keep the default WordPress login endpoints.', 'vulntitan'),
                    'firewall_event_unknown' => esc_html__('Unknown event', 'vulntitan'),
                    'firewall_event_login_failed' => esc_html__('Login failed', 'vulntitan'),
                    'firewall_event_login_blocked' => esc_html__('Login blocked', 'vulntitan'),
                    'firewall_event_login_lockout' => esc_html__('IP lockout', 'vulntitan'),
                    'firewall_event_login_recovered' => esc_html__('Login recovered', 'vulntitan'),
                    'firewall_event_request_blocked' => esc_html__('Request blocked', 'vulntitan'),
                    'firewall_event_form_blocked' => esc_html__('Form blocked', 'vulntitan'),
                    'firewall_event_comment_spam_blocked' => esc_html__('Comment spam blocked', 'vulntitan'),
                    'firewall_event_comment_spam_held' => esc_html__('Comment held for review', 'vulntitan'),
                    'firewall_event_comment_pending_review' => esc_html__('Comment entered pending review', 'vulntitan'),
                    'firewall_event_comment_rate_limited' => esc_html__('Comment rate limited', 'vulntitan'),
                    'firewall_feed_live' => esc_html__('Live', 'vulntitan'),
                    'firewall_feed_paused' => esc_html__('Paused', 'vulntitan'),
                    'firewall_feed_updating' => esc_html__('Updating', 'vulntitan'),
                    'firewall_feed_pause' => esc_html__('Pause', 'vulntitan'),
                    'firewall_feed_resume' => esc_html__('Resume', 'vulntitan'),
                    'firewall_feed_meta_live' => esc_html__('Auto-refresh every 5 seconds', 'vulntitan'),
                    'firewall_feed_meta_paused' => esc_html__('Live updates are paused', 'vulntitan'),
                    'firewall_feed_meta_failed' => esc_html__('Refresh failed. Showing last successful snapshot.', 'vulntitan'),
                    'firewall_feed_updated_prefix' => esc_html__('Updated', 'vulntitan'),
                    'firewall_feed_showing_prefix' => esc_html__('Showing', 'vulntitan'),
                    'firewall_feed_of' => esc_html__('of', 'vulntitan'),
                    'firewall_feed_events' => esc_html__('events', 'vulntitan'),
                    'firewall_feed_load_more' => esc_html__('Load more', 'vulntitan'),
                    'firewall_lockout_unblock' => esc_html__('Unblock IP', 'vulntitan'),
                    'firewall_lockout_allowlist' => esc_html__('Add to allowlist', 'vulntitan'),
                    'firewall_confirm_unblock' => esc_html__('Unblock this IP?', 'vulntitan'),
                    'firewall_confirm_allowlist' => esc_html__('Add this IP to the lockout allowlist?', 'vulntitan'),
                    'firewall_unblock_success' => esc_html__('IP unblocked.', 'vulntitan'),
                    'firewall_allowlist_success' => esc_html__('IP added to lockout allowlist.', 'vulntitan'),
                    'firewall_action_in_progress' => esc_html__('Working...', 'vulntitan'),
                    'firewall_action_failed' => esc_html__('Action failed.', 'vulntitan'),
                    'firewall_ip_invalid' => esc_html__('Invalid IP address.', 'vulntitan'),
                    'firewall_feed_close_details' => esc_html__('Close details', 'vulntitan'),
                    'firewall_feed_reason' => esc_html__('Reason', 'vulntitan'),
                    'firewall_feed_request' => esc_html__('Request', 'vulntitan'),
                    'firewall_feed_actor' => esc_html__('Actor', 'vulntitan'),
                    'firewall_feed_detection' => esc_html__('Detection', 'vulntitan'),
                    'firewall_feed_flags' => esc_html__('Flags', 'vulntitan'),
                    'firewall_feed_details' => esc_html__('Details', 'vulntitan'),
                    'firewall_feed_context' => esc_html__('Context', 'vulntitan'),
                    'firewall_feed_none' => esc_html__('n/a', 'vulntitan'),
                    'firewall_feed_yes' => esc_html__('Yes', 'vulntitan'),
                    'firewall_feed_no' => esc_html__('No', 'vulntitan'),
                    'firewall_approval_action' => esc_html__('Action', 'vulntitan'),
                    'firewall_approval_route' => esc_html__('Route', 'vulntitan'),
                    'firewall_approval_pattern' => esc_html__('Whitelist pattern', 'vulntitan'),
                    'firewall_approval_allow' => esc_html__('Approve', 'vulntitan'),
                    'firewall_approval_dismiss' => esc_html__('Dismiss', 'vulntitan'),
                    'firewall_approval_confirm' => esc_html__('Approve this request and whitelist its pattern?', 'vulntitan'),
                    'firewall_approval_confirm_dismiss' => esc_html__('Dismiss this approval request?', 'vulntitan'),
                    'firewall_approval_success' => esc_html__('Whitelist updated.', 'vulntitan'),
                    'firewall_approval_dismissed' => esc_html__('Approval dismissed.', 'vulntitan'),
                    'firewall_approval_no_pattern' => esc_html__('No safe auto-approval pattern available.', 'vulntitan'),
                    'firewall_approval_invalid' => esc_html__('Invalid approval request.', 'vulntitan'),
                    'firewall_learning_loading' => esc_html__('Loading learning suggestions...', 'vulntitan'),
                    'firewall_learning_updated' => esc_html__('Learning suggestions updated.', 'vulntitan'),
                    'firewall_learning_failed' => esc_html__('Failed to load learning suggestions.', 'vulntitan'),
                    'firewall_learning_empty' => esc_html__('No learning suggestions yet.', 'vulntitan'),
                    'firewall_learning_disabled' => esc_html__('Learning suggestions are disabled.', 'vulntitan'),
                    'firewall_learning_suggestion' => esc_html__('Learning suggestion', 'vulntitan'),
                    'firewall_learning_hits' => esc_html__('Hits', 'vulntitan'),
                    'firewall_learning_last_seen' => esc_html__('Last seen', 'vulntitan'),
                    'firewall_learning_allow' => esc_html__('Allow', 'vulntitan'),
                    'firewall_learning_dismiss' => esc_html__('Dismiss', 'vulntitan'),
                    'firewall_learning_dismissed' => esc_html__('Learning suggestion dismissed.', 'vulntitan'),
                    'firewall_learning_confirm_allow' => esc_html__('Allow this suggested pattern and add it to the WAF whitelist?', 'vulntitan'),
                    'firewall_learning_confirm_dismiss' => esc_html__('Dismiss this learning suggestion?', 'vulntitan'),
                    'firewall_learning_refresh' => esc_html__('Refresh suggestions', 'vulntitan'),
                ],
            ]);

            wp_enqueue_script('vulntitan-firewall');
            return;
        }

        // Collect scan items
        $scanItems = [];

        require_once ABSPATH . 'wp-admin/includes/plugin.php';
        if (function_exists('wp_update_plugins')) {
            wp_update_plugins();
        }
        if (function_exists('wp_update_themes')) {
            wp_update_themes();
        }
        if (function_exists('wp_version_check')) {
            wp_version_check();
        }
        $plugins = get_plugins();
        $pluginUpdates = get_site_transient('update_plugins');
        $pluginUpdateResponse = is_object($pluginUpdates) && isset($pluginUpdates->response) && is_array($pluginUpdates->response)
            ? $pluginUpdates->response
            : [];

        $normalizePluginSlug = static function (string $pluginFile, array $pluginData): string {
            $slug = dirname($pluginFile);

            if ($slug === '.' || $slug === '') {
                $textDomain = trim((string) ($pluginData['TextDomain'] ?? ''));
                if ($textDomain !== '') {
                    $slug = $textDomain;
                } else {
                    $slug = basename($pluginFile, '.php');
                }
            }

            return $slug;
        };

        foreach ($plugins as $pluginFile => $pluginData) {
            $slug = $normalizePluginSlug($pluginFile, $pluginData);
            $isActive = is_plugin_active($pluginFile);
            $updateInfo = $pluginUpdateResponse[$pluginFile] ?? null;
            $hasFix = is_object($updateInfo) && !empty($updateInfo->new_version);
            $updateUrl = $hasFix
                ? wp_nonce_url(
                    self_admin_url('update.php?action=upgrade-plugin&plugin=' . rawurlencode($pluginFile)),
                    'upgrade-plugin_' . $pluginFile
                )
                : '';
            $deactivateUrl = $isActive
                ? wp_nonce_url(
                    self_admin_url('plugins.php?action=deactivate&plugin=' . rawurlencode($pluginFile)),
                    'deactivate-plugin_' . $pluginFile
                )
                : '';
            $openUrl = self_admin_url('plugins.php?plugin_status=all&s=' . rawurlencode((string) ($pluginData['Name'] ?? '')));

            $scanItems[] = [
                'type'    => 'plugin',
                'slug'    => $slug,
                'plugin_file' => $pluginFile,
                'version' => $pluginData['Version'],
                'label'   => 'Plugin: ' . $pluginData['Name'],
                'active'  => $isActive,
                'has_fix' => $hasFix,
                'actions' => [
                    'update' => $updateUrl,
                    'deactivate' => $deactivateUrl,
                    'open' => $openUrl,
                ],
            ];
        }

        $themeUpdates = get_site_transient('update_themes');
        $themeUpdateResponse = is_object($themeUpdates) && isset($themeUpdates->response) && is_array($themeUpdates->response)
            ? $themeUpdates->response
            : [];
        $activeTheme = wp_get_theme();
        $activeThemeSlug = $activeTheme instanceof \WP_Theme ? $activeTheme->get_stylesheet() : '';

        $themes = wp_get_themes();
        foreach ($themes as $slug => $theme) {
            $version = $theme->get('Version');
            $name    = $theme->get('Name');

            if (!$slug || !$version) {
                continue;
            }

            $themeUpdate = $themeUpdateResponse[$slug] ?? null;
            $hasFix = is_array($themeUpdate) && !empty($themeUpdate['new_version']);
            $updateUrl = $hasFix
                ? wp_nonce_url(
                    self_admin_url('update.php?action=upgrade-theme&theme=' . rawurlencode($slug)),
                    'upgrade-theme_' . $slug
                )
                : '';
            $openUrl = self_admin_url('themes.php?search=' . rawurlencode($name));

            $scanItems[] = [
                'type'    => 'theme',
                'slug'    => $slug, // or $theme->get_stylesheet()
                'theme_slug' => $slug,
                'version' => $version,
                'label'   => 'Theme: ' . $name,
                'active'  => $slug === $activeThemeSlug,
                'has_fix' => $hasFix,
                'actions' => [
                    'update' => $updateUrl,
                    'open' => $openUrl,
                ],
            ];
        }

        $coreUpdates = get_site_transient('update_core');
        $coreHasFix = false;
        if (is_object($coreUpdates) && !empty($coreUpdates->updates) && is_array($coreUpdates->updates)) {
            foreach ($coreUpdates->updates as $update) {
                if (is_object($update) && ($update->response ?? '') === 'upgrade') {
                    $coreHasFix = true;
                    break;
                }
            }
        }

        $scanItems[] = [
            'type'    => 'core',
            'slug'    => 'wordpress',
            'version' => get_bloginfo('version'),
            'label'   => 'WordPress Core',
            'active'  => true,
            'has_fix' => $coreHasFix,
            'actions' => [
                'update' => $coreHasFix ? self_admin_url('update-core.php') : '',
            ],
        ];

        wp_localize_script('vulntitan-core', 'VulnTitan', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce('vulntitan_ajax_scan'),
            'scanItems' => $scanItems,
            'i18n' => [
                'base' => esc_html__('Base', 'vulntitan'),
                'scanning' => esc_html__('Scanning', 'vulntitan'),
                'scanning_for_malware' => esc_html__('Scanning files for malware', 'vulntitan'),
                'start_scan' => esc_html__('Start Scan', 'vulntitan'),
                'scan_now' => esc_html__('Scan Now', 'vulntitan'),
                'preparing' => esc_html__('Preparing...', 'vulntitan'),
                'scan_finished' => esc_html__('Scan finished.', 'vulntitan'),
                'issues_found' => esc_html__('issue(s) found', 'vulntitan'),
                'no_targets' => esc_html__('No scan targets found.', 'vulntitan'),
                'scan_stopped' => esc_html__('Scan stopped due to error.', 'vulntitan'),
                'scan_init_failed' => esc_html__('Scan initialization failed.', 'vulntitan'),
                'no_files_to_scan' => esc_html__('No matching files to scan.', 'vulntitan'),
                'completed' => esc_html__('Completed.', 'vulntitan'),
                'unknown' => esc_html__('unknown', 'vulntitan'),
                'error' => esc_html__('Error', 'vulntitan'),
                'no_vulns' => esc_html__('No vulnerabilities found.', 'vulntitan'),
                'read_more' => esc_html__('Read More', 'vulntitan'),
                'severity' => esc_html__('Severity', 'vulntitan'),
                'cve' => esc_html__('CVE', 'vulntitan'),
                'no_problematic_files' => esc_html__('No problematic files detected.', 'vulntitan'),
                'problematic_files_detected' => esc_html__('problematic file(s) detected.', 'vulntitan'),
                'integrity_internal_queue_notice' => esc_html__('This is a temporary VulnTitan queue file generated during scanning. It is usually removed automatically and should not be manually deleted while scan tasks are active.', 'vulntitan'),
                'integrity_internal_storage_notice' => esc_html__('This file is inside VulnTitan internal storage. Review carefully before taking action.', 'vulntitan'),
                'integrity_next_step_core_modified' => esc_html__('Core files are modified. Replace them with clean WordPress core files for the same WordPress version.', 'vulntitan'),
                'integrity_next_step_extension_modified' => esc_html__('Plugin/theme files are modified. If changes are not intentional, reinstall affected plugins/themes from trusted sources.', 'vulntitan'),
                'integrity_next_step_missing' => esc_html__('Some expected files are missing. Restore from a trusted package or backup.', 'vulntitan'),
                'integrity_next_step_unexpected' => esc_html__('Unexpected files were detected. Verify file ownership and purpose before deletion.', 'vulntitan'),
                'integrity_next_step_error' => esc_html__('Some files could not be analyzed. Check file permissions and server access, then rerun the scan.', 'vulntitan'),
                'integrity_next_step_finalize' => esc_html__('After fixes, rerun Integrity scan and regenerate baseline only when results are expected.', 'vulntitan'),
                'vuln_overview_title' => esc_html__('Vulnerability Overview', 'vulntitan'),
                'vuln_overview_subtitle' => esc_html__('Live intelligence snapshot across plugins, themes, and WordPress core.', 'vulntitan'),
                'vuln_overview_badge' => esc_html__('Live Intelligence', 'vulntitan'),
                'vuln_scanned_targets' => esc_html__('Scanned Targets', 'vulntitan'),
                'vuln_vulnerable_targets' => esc_html__('Vulnerable Targets', 'vulntitan'),
                'vuln_total_findings' => esc_html__('Total Findings', 'vulntitan'),
                'vuln_errors' => esc_html__('Errors', 'vulntitan'),
                'vuln_last_scan' => esc_html__('Last scan', 'vulntitan'),
                'vuln_data_age' => esc_html__('Data age', 'vulntitan'),
                'vuln_data_age_live' => esc_html__('live', 'vulntitan'),
                'vuln_filters_title' => esc_html__('Filters', 'vulntitan'),
                'vuln_filter_severity' => esc_html__('Severity', 'vulntitan'),
                'vuln_filter_type' => esc_html__('Component', 'vulntitan'),
                'vuln_filter_status' => esc_html__('Status', 'vulntitan'),
                'vuln_filter_fix' => esc_html__('Has fix', 'vulntitan'),
                'vuln_filter_all' => esc_html__('All', 'vulntitan'),
                'vuln_filter_active' => esc_html__('Active', 'vulntitan'),
                'vuln_filter_inactive' => esc_html__('Inactive', 'vulntitan'),
                'vuln_filter_has_fix' => esc_html__('Yes', 'vulntitan'),
                'vuln_filter_no_fix' => esc_html__('No', 'vulntitan'),
                'vuln_sort_label' => esc_html__('Sort', 'vulntitan'),
                'vuln_sort_severity' => esc_html__('Severity (high to low)', 'vulntitan'),
                'vuln_sort_name' => esc_html__('Name (A-Z)', 'vulntitan'),
                'vuln_sort_findings' => esc_html__('Findings (high to low)', 'vulntitan'),
                'vuln_action_update' => esc_html__('Update now', 'vulntitan'),
                'vuln_action_deactivate' => esc_html__('Deactivate', 'vulntitan'),
                'vuln_action_open' => esc_html__('Open plugin page', 'vulntitan'),
                'vuln_action_accept_risk' => esc_html__('Accept risk', 'vulntitan'),
                'vuln_action_ignore' => esc_html__('Ignore', 'vulntitan'),
                'vuln_action_clear_decision' => esc_html__('Clear decision', 'vulntitan'),
                'vuln_risk_expires' => esc_html__('Expires', 'vulntitan'),
                'vuln_risk_score' => esc_html__('Risk score', 'vulntitan'),
                'vuln_risk_status_accepted' => esc_html__('Risk accepted', 'vulntitan'),
                'vuln_risk_status_ignored' => esc_html__('Ignored', 'vulntitan'),
                'vuln_risk_audit' => esc_html__('Audit log', 'vulntitan'),
                'vuln_risk_audit_empty' => esc_html__('No risk decisions logged yet.', 'vulntitan'),
                'vuln_risk_note_prompt' => esc_html__('Add a short note for the audit log (optional):', 'vulntitan'),
                'vuln_fixed_version' => esc_html__('Fixed version', 'vulntitan'),
                'vuln_affected_versions' => esc_html__('Affected versions', 'vulntitan'),
                'vuln_cvss_score' => esc_html__('CVSS score', 'vulntitan'),
                'vuln_cvss_vector' => esc_html__('CVSS vector', 'vulntitan'),
                'vuln_published_at' => esc_html__('Published', 'vulntitan'),
                'vuln_exploit_status' => esc_html__('Exploit status', 'vulntitan'),
                'vuln_exploit_known' => esc_html__('Known exploit', 'vulntitan'),
                'vuln_exploit_unknown' => esc_html__('Unknown', 'vulntitan'),
                'vuln_exploit_none' => esc_html__('No exploit', 'vulntitan'),
                'vuln_expires_in' => esc_html__('Expires in', 'vulntitan'),
                'vuln_expires_7' => esc_html__('7 days', 'vulntitan'),
                'vuln_expires_30' => esc_html__('30 days', 'vulntitan'),
                'vuln_expires_90' => esc_html__('90 days', 'vulntitan'),
                'vuln_expires_365' => esc_html__('1 year', 'vulntitan'),
                'loading' => esc_html__('Loading...', 'vulntitan'),
                'vuln_update_label' => esc_html__('Update', 'vulntitan'),
                'vuln_deactivate_label' => esc_html__('Deactivate', 'vulntitan'),
                'vuln_update_started' => esc_html__('Starting update...', 'vulntitan'),
                'vuln_update_success' => esc_html__('Update completed.', 'vulntitan'),
                'vuln_update_failed' => esc_html__('Update failed.', 'vulntitan'),
                'vuln_deactivate_started' => esc_html__('Deactivating plugin...', 'vulntitan'),
                'vuln_deactivate_success' => esc_html__('Plugin deactivated.', 'vulntitan'),
                'vuln_deactivate_failed' => esc_html__('Deactivate failed.', 'vulntitan'),
                'vuln_core_update_notice' => esc_html__('Open the Updates page to apply the WordPress core update.', 'vulntitan'),
                'vuln_action_stop' => esc_html__('Stop scan', 'vulntitan'),
                'vuln_action_retry_failed' => esc_html__('Retry failed', 'vulntitan'),
                'vuln_scan_stopped' => esc_html__('Scan stopped by user.', 'vulntitan'),
                'vuln_components_title' => esc_html__('Vulnerable Components', 'vulntitan'),
                'vuln_components_subtitle' => esc_html__('Components with one or more known issues discovered during this scan.', 'vulntitan'),
                'vuln_components_empty' => esc_html__('No vulnerable components detected so far.', 'vulntitan'),
                'vuln_details_title' => esc_html__('Component Findings', 'vulntitan'),
                'vuln_details_subtitle' => esc_html__('Each scanned target is summarized here as live results arrive.', 'vulntitan'),
                'vuln_component_clean' => esc_html__('No vulnerabilities found for this component.', 'vulntitan'),
                'vuln_component_clean_prefix' => esc_html__('No vulnerabilities found for', 'vulntitan'),
                'vuln_component_clean_core' => esc_html__('No vulnerabilities found for WordPress core.', 'vulntitan'),
                'vuln_core_name' => esc_html__('WordPress Core', 'vulntitan'),
                'vuln_scanning_status' => esc_html__('Scanning live intelligence...', 'vulntitan'),
                'vuln_issues_found' => esc_html__('issue(s) found', 'vulntitan'),
                'vuln_type_plugin' => esc_html__('Plugin', 'vulntitan'),
                'vuln_type_theme' => esc_html__('Theme', 'vulntitan'),
                'vuln_type_core' => esc_html__('Core', 'vulntitan'),
                'vuln_type_unknown' => esc_html__('Component', 'vulntitan'),
                'vuln_severity_critical' => esc_html__('Critical', 'vulntitan'),
                'vuln_severity_high' => esc_html__('High', 'vulntitan'),
                'vuln_severity_medium' => esc_html__('Medium', 'vulntitan'),
                'vuln_severity_low' => esc_html__('Low', 'vulntitan'),
                'vuln_severity_unknown' => esc_html__('Unknown', 'vulntitan'),
                'data_age_prefix' => esc_html__('Data age', 'vulntitan'),
                'data_age_just_now' => esc_html__('just now', 'vulntitan'),
                'malware_overview_title' => esc_html__('Malware Overview', 'vulntitan'),
                'malware_total_files' => esc_html__('Total Files', 'vulntitan'),
                'malware_processed_files' => esc_html__('Processed', 'vulntitan'),
                'malware_clean_files' => esc_html__('Clean', 'vulntitan'),
                'malware_infected_files' => esc_html__('Infected', 'vulntitan'),
                'malware_problematic_files' => esc_html__('Problematic Files', 'vulntitan'),
                'malware_problematic_none' => esc_html__('No problematic files detected in malware scan.', 'vulntitan'),
                'malware_problematic_detected' => esc_html__('problematic file(s) detected by malware scan.', 'vulntitan'),
                'malware_status_clean' => esc_html__('clean', 'vulntitan'),
                'malware_status_infected' => esc_html__('infected', 'vulntitan'),
                'malware_status_skipped' => esc_html__('skipped', 'vulntitan'),
                'malware_status_error' => esc_html__('error', 'vulntitan'),
                'malware_preview_toggle' => esc_html__('Open code preview', 'vulntitan'),
                'malware_preview_line' => esc_html__('Line', 'vulntitan'),
                'malware_fix_apply' => esc_html__('Apply Fix', 'vulntitan'),
                'malware_fixing' => esc_html__('Fixing...', 'vulntitan'),
                'malware_fixed' => esc_html__('Fixed', 'vulntitan'),
                'malware_fix_confirm' => esc_html__('Apply safe fix for this suspicious line? A backup will be created.', 'vulntitan'),
                'malware_fix_no_line' => esc_html__('This finding has no exact line, so auto-fix is not available.', 'vulntitan'),
                'malware_fix_unavailable' => esc_html__('Auto-fix is disabled for low-risk findings.', 'vulntitan'),
                'malware_fix_success' => esc_html__('Fix applied.', 'vulntitan'),
                'malware_fix_error' => esc_html__('Auto-fix failed.', 'vulntitan'),
                'malware_fix_backup' => esc_html__('Backup', 'vulntitan'),
            ]
        ]);

        wp_enqueue_script('vulntitan-core');
        wp_enqueue_script('vulntitan-malware-scanner');
        wp_enqueue_script('vulntitan-integrity-scanner');
        wp_enqueue_script('vulntitan-vulnerability-scanner');
    }

    public function addAdminMenu(): void
    {
        $approvalCount = FirewallService::getPendingApprovalCount();
        $approvalBadge = '';
        if ($approvalCount > 0) {
            $approvalBadge = sprintf(
                ' <span class="update-plugins count-%1$d"><span class="plugin-count">%2$s</span></span>',
                absint($approvalCount),
                esc_html(number_format_i18n($approvalCount))
            );
        }

        add_menu_page(
            esc_html__('VulnTitan', 'vulntitan'),
            esc_html__('VulnTitan', 'vulntitan'),
            'manage_options',
            'vulntitan',
            [Dashboard::class, 'render'],
            VULNTITAN_PLUGIN_URL . '/assets/img/vulntitan-32x32.png?ver=2.0',
            74
        );

        add_submenu_page(
            'vulntitan',
            esc_html__('Dashboard', 'vulntitan'),
            esc_html__('Dashboard', 'vulntitan'),
            'manage_options',
            'vulntitan',
        );

        add_submenu_page(
            'vulntitan',
            esc_html__('Firewall', 'vulntitan'),
            esc_html__('Firewall', 'vulntitan') . $approvalBadge,
            'manage_options',
            'vulntitan-firewall',
            [Firewall::class, 'render'],
        );

        add_submenu_page(
            'vulntitan',
            esc_html__('Live Security Feed', 'vulntitan'),
            esc_html__('Live Feed', 'vulntitan'),
            'manage_options',
            'vulntitan-live-feed',
            [LiveFeed::class, 'render'],
        );

    }

    public function renderApprovalsNotice(): void
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        $approvalCount = FirewallService::getPendingApprovalCount();
        if ($approvalCount <= 0) {
            return;
        }

        $message = sprintf(
            _n(
                'VulnTitan has %s pending approval that needs your review.',
                'VulnTitan has %s pending approvals that need your review.',
                $approvalCount,
                'vulntitan'
            ),
            number_format_i18n($approvalCount)
        );
        $reviewUrl = admin_url('admin.php?page=vulntitan-firewall#approvals');

        echo '<div class="notice notice-warning"><p>' . esc_html($message) . ' ';
        echo '<a href="' . esc_url($reviewUrl) . '" class="button button-primary">';
        echo esc_html__('Review approvals', 'vulntitan') . '</a></p></div>';
    }
}
