<?php

/**
 * Editor Sidebar Handler
 *
 * Handles Block Editor sidebar integration and asset loading.
 *
 * @package ProRank\SEO\Admin
 * @since   1.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Admin;

use ProRank\SEO\Plugin;

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


/**
 * EditorSidebar class
 */


class EditorSidebar {
    
    /**
     * Plugin instance
     *
     * @var Plugin
     */
    private Plugin $plugin;
    
    /**
     * Constructor
     *
     * @param Plugin $plugin Plugin instance.
     */
    public function __construct(Plugin $plugin) {
        $this->plugin = $plugin;
    }
    
    /**
     * Initialize sidebar
     *
     * @return void
     */
    public function init(): void {
        // Enqueue block editor assets
        add_action('enqueue_block_editor_assets', [$this, 'enqueue_sidebar_assets']);
        // Show guidance when the current editor is Classic so users know why the sidebar is missing.
        add_action('admin_notices', [$this, 'maybe_render_block_editor_notice']);
    }
    
    /**
     * Enqueue sidebar assets
     *
     * @return void
     */
    public function enqueue_sidebar_assets(): void {
        // Only load on supported post types
        $current_screen = get_current_screen();
        if (!$current_screen || !$current_screen->is_block_editor()) {
            return;
        }
        
        // Get supported post types (default to post and page)
        $supported_post_types = apply_filters(
            'prorank_seo_sidebar_post_types',
            ['post', 'page']
        );
        
        if (!in_array($current_screen->post_type, $supported_post_types, true)) {
            return;
        }
        
        // Check if script file exists - try build directory first, then legacy path
        $script_path = PRORANK_PLUGIN_DIR . 'build/sidebar.js';
        $asset_path = PRORANK_PLUGIN_DIR . 'build/sidebar.asset.php';
        $script_url = PRORANK_PLUGIN_URL . 'build/sidebar.js';

        // Fallback to legacy path if build doesn't exist
        if (!file_exists($script_path)) {
            $script_path = PRORANK_PLUGIN_DIR . 'admin/assets/js/sidebar.js';
            $asset_path = PRORANK_PLUGIN_DIR . 'admin/assets/js/sidebar.asset.php';
            $script_url = PRORANK_PLUGIN_URL . 'admin/assets/js/sidebar.js';
        }

        if (!file_exists($script_path)) {
            return;
        }

        // Get script dependencies and version
        $script_asset = file_exists($asset_path)
            ? require($asset_path)
            : [
                'dependencies' => ['wp-plugins', 'wp-element', 'wp-components', 'wp-data', 'wp-i18n', 'wp-editor', 'lodash'],
                'version' => PRORANK_VERSION
            ];

        $script_asset['dependencies'] = array_values(array_unique(array_merge(
            $script_asset['dependencies'] ?? [],
            ['wp-plugins', 'wp-editor']
        )));

        // Enqueue sidebar script
        wp_enqueue_script(
            'prorank-seo-sidebar',
            $script_url,
            $script_asset['dependencies'],
            $script_asset['version'],
            true
        );
        
        // Enqueue sidebar CSS if available
        $css_path = PRORANK_PLUGIN_DIR . 'build/sidebar.css';
        if (file_exists($css_path)) {
            wp_enqueue_style(
                'prorank-seo-sidebar',
                PRORANK_PLUGIN_URL . 'build/sidebar.css',
                [],
                $script_asset['version']
            );
        }

        // Localize script
        wp_localize_script('prorank-seo-sidebar', 'proRankSidebar', [
            'apiUrl' => home_url('/wp-json/prorank-seo/v1'),
            'nonce' => wp_create_nonce('wp_rest'),
            'postId' => get_the_ID(),
            'postType' => $current_screen->post_type,
            'licenseTier' => 'free',
            'license' => [
                'status' => 'inactive',
                'tier' => 'free',
            ],
            'isPremiumActive' => false,
            'features' => [
                'enablePremiumPanels' => false,
                'aiAssistant' => false,
                'trafficInsights' => false,
            ],
            'pluginUrl' => PRORANK_PLUGIN_URL,
            'settings' => $this->get_sidebar_settings(),
            'contentAnalysis' => $this->get_content_analysis_settings_for_sidebar(),
        ]);

        // Compatibility: ensure window.prorankSettings exists on editor screens so
        // tier checks don't mis-detect "pro" when the object is missing.
        $license_tier = 'free';

        $inline = 'window.prorankSettings = window.prorankSettings || {};';
        $inline .= 'window.prorankSettings.adminUrl = ' . wp_json_encode(admin_url()) . ';';
        $inline .= 'window.prorankSettings.upgradeUrl = ' . wp_json_encode('https://prorank.io/pricing') . ';';
        $inline .= 'window.prorankSettings.isPremiumActive = false;';
        $inline .= 'window.prorankSettings.license = window.prorankSettings.license || {};';
        $inline .= 'window.prorankSettings.license.tier = ' . wp_json_encode($license_tier) . ';';
        $inline .= 'window.prorankSettings.features = window.prorankSettings.features || {};';
        $inline .= 'window.prorankSettings.features.enablePremiumPanels = false;';
        $inline .= 'window.prorankSettings.features.aiAssistant = false;';
        $inline .= 'window.prorankSettings.features.trafficInsights = false;';
        wp_add_inline_script('prorank-seo-sidebar', $inline, 'before');
        
        // Set script translations
        wp_set_script_translations(
            'prorank-seo-sidebar',
            'prorank-seo',
            PRORANK_PLUGIN_DIR . 'languages'
        );
        
    }

    /**
     * Show a notice on classic editor screens with a quick switch link.
     *
     * @return void
     */
    public function maybe_render_block_editor_notice(): void {
        if (!function_exists('get_current_screen')) {
            return;
        }

        $current_screen = get_current_screen();
        if (!$current_screen || $current_screen->base !== 'post') {
            return;
        }

        $supported_post_types = apply_filters(
            'prorank_seo_sidebar_post_types',
            ['post', 'page']
        );

        if (!in_array($current_screen->post_type, $supported_post_types, true)) {
            return;
        }

        if ($current_screen->is_block_editor()) {
            return;
        }

        $raw_action = isset($_GET['action']) ? wp_unslash((string) $_GET['action']) : '';
        $is_elementor_editor = sanitize_key($raw_action) === 'elementor';

        $switch_url = '';
        $post_id = isset($_GET['post']) ? absint($_GET['post']) : 0;
        if ($post_id > 0) {
            $edit_link = get_edit_post_link($post_id, '');
            if (is_string($edit_link) && $edit_link !== '') {
                $switch_url = remove_query_arg('classic-editor', $edit_link);
                $switch_url = add_query_arg('classic-editor__forget', '', $switch_url);
            }
        }

        echo '<div class="notice notice-info">';
        if ($is_elementor_editor) {
            echo '<p>' . esc_html__('ProRank SEO sidebar does not render inside Elementor editor. Use the ProRank SEO icon in Elementor top bar for SEO controls, or open in Block Editor for full sidebar analysis.', 'prorank-seo') . '</p>';
        } else {
            echo '<p>' . esc_html__('ProRank SEO sidebar is available in the Block Editor. You are currently editing in Classic Editor.', 'prorank-seo') . '</p>';
        }
        if ($switch_url !== '') {
            echo '<p><a class="button button-secondary" href="' . esc_url($switch_url) . '">' . esc_html__('Open in Block Editor', 'prorank-seo') . '</a></p>';
        }
        echo '</div>';
    }
    
    /**
     * Get current license tier
     *
     * @return string License tier.
     */
    private function get_license_tier(): string {
        return 'free';
    }
    
    /**
     * Get sidebar settings
     *
     * @return array Sidebar settings.
     */
    private function get_sidebar_settings(): array {
        $defaults = [
            'defaultPanelState' => [
                'readability' => true,
                'internalLinking' => false,
                'advancedAnalysis' => false,
            ],
            'features' => [
                'readability' => true,
                'internalLinking' => true,
                'advancedAnalysis' => false,
            ],
        ];

        $settings = [];
        try {
            $settings = $this->plugin->settings()->get_settings('editor_sidebar');
        } catch (\Throwable $e) {
            $settings = [];
        }

        if (!is_array($settings)) {
            $settings = [];
        }

        $merged = array_replace_recursive($defaults, $settings);

        $tier = $this->get_license_tier();
        if ($tier === 'core') {
            $tier = 'pro';
        }

        $merged['features']['advancedAnalysis'] = in_array($tier, ['pro', 'business', 'agency'], true);
        $merged = apply_filters('prorank_seo_sidebar_settings', $merged, $tier);

        return is_array($merged) ? $merged : $defaults;
    }

    /**
     * Get normalized content analysis settings for editor sidebar.
     *
     * @return array<string,mixed>
     */
    private function get_content_analysis_settings_for_sidebar(): array {
        $defaults = [
            'enable_realtime' => true,
            'enable_ai_insights' => false,
            'min_content_length' => 300,
            'target_readability_score' => 60,
            'auto_analyze_delay' => 2000,
            'show_keyword_density' => false,
            'show_entity_detection' => false,
            'show_intent_classification' => false,
        ];

        $primary = get_option('prorank_seo_content_analysis', []);
        if (!is_array($primary)) {
            $primary = [];
        }

        // Legacy option/key compatibility from AdvancedAnalysisModule.
        $legacy = get_option('prorank_content_analysis_settings', []);
        if (!is_array($legacy)) {
            $legacy = [];
        }

        $mapped_legacy = [
            'enable_realtime' => isset($legacy['enable_realtime']) ? (bool) $legacy['enable_realtime'] : null,
            'enable_ai_insights' => isset($legacy['enable_ai_suggestions']) ? (bool) $legacy['enable_ai_suggestions'] : null,
            'min_content_length' => isset($legacy['min_content_length']) ? (int) $legacy['min_content_length'] : null,
            'target_readability_score' => isset($legacy['target_readability_score']) ? (int) $legacy['target_readability_score'] : null,
            'show_keyword_density' => isset($legacy['enable_semantic']) ? (bool) $legacy['enable_semantic'] : null,
            'show_entity_detection' => isset($legacy['enable_semantic']) ? (bool) $legacy['enable_semantic'] : null,
            'show_intent_classification' => isset($legacy['enable_intent']) ? (bool) $legacy['enable_intent'] : null,
        ];
        $mapped_legacy = array_filter($mapped_legacy, static function ($value) {
            return $value !== null;
        });

        $merged = array_merge($defaults, $mapped_legacy, $primary);

        // Free build: keep Pro+ AI insights controls disabled in editor sidebar payload.
        $merged['enable_ai_insights'] = false;
        $merged['show_keyword_density'] = false;
        $merged['show_entity_detection'] = false;
        $merged['show_intent_classification'] = false;

        $merged['min_content_length'] = max(100, (int) ($merged['min_content_length'] ?? 300));
        $merged['target_readability_score'] = max(30, min(90, (int) ($merged['target_readability_score'] ?? 60)));
        $merged['auto_analyze_delay'] = max(500, min(5000, (int) ($merged['auto_analyze_delay'] ?? 2000)));

        return $merged;
    }
}
