<?php
/**
 * Elementor Editor Integration
 *
 * Adds the SEO Fury metabox panel inside the Elementor page editor so users
 * can edit SEO metadata without leaving the visual builder.
 *
 * Approach:
 *  - A toggle button is injected into Elementor's footer tools bar.
 *  - Clicking it slides up a docked panel that contains the full SEO metabox.
 *  - On Elementor save (Publish / Update) the SEO fields are sent via AJAX.
 */

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

class SEO_Fury_Elementor_Integration
{
    private static $instance = null;

    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct()
    {
        // Register hooks only when Elementor editor is active
        add_action('elementor/editor/after_enqueue_scripts', array($this, 'enqueue_editor_assets'));
        add_action('elementor/editor/footer', array($this, 'render_editor_panel'));

        // AJAX handler for saving SEO data from Elementor
        add_action('wp_ajax_seo_fury_elementor_save', array($this, 'ajax_save'));

        // Frontend compatibility patch: must run after wp_print_footer_scripts (priority 20)
        // so the inline patch appears in the HTML after Elementor's config scripts but
        // before DOMContentLoaded fires and elementorFrontend.init() runs.
        add_action('wp_footer', array($this, 'maybe_patch_elementor_config'), 21);
    }

    /* ───────────────────────────────────────────────
     *  Frontend compatibility patch
     * ─────────────────────────────────────────────── */

    /**
     * Output a small inline script that ensures window.elementorFrontendConfig.tools
     * exists before Elementor's jQuery-ready handler runs.
     *
     * Root cause: Elementor Pro (older versions) re-declares window.elementorFrontendConfig
     * for logged-in editors, but its version omits the `tools` property introduced in
     * Elementor Free 3.26+. When Free's Frontend.initOnReadyComponents() then tries to
     * iterate this.config.tools it throws:
     *   "Cannot read properties of undefined (reading 'tools')"
     * which prevents all Elementor widgets (including nav-menu dropdowns) from
     * initialising on the frontend for logged-in users.
     *
     * This patch runs at wp_footer priority 21 — after wp_print_footer_scripts() (20)
     * has printed Elementor's scripts, but before the browser fires DOMContentLoaded.
     * Because this.config is an object *reference* set during script execution, adding
     * the missing property here is reflected when init() eventually reads it.
     */
    public function maybe_patch_elementor_config() {
        // Only needed on the frontend for logged-in editors.
        if (is_admin() || !is_user_logged_in() || !current_user_can('edit_posts')) {
            return;
        }

        // Skip if Elementor's frontend script was not printed on this page.
        if (!wp_script_is('elementor-frontend', 'done')) {
            return;
        }
        ?>
        <script id="seo-fury-elementor-config-patch">
        (function() {
            'use strict';

            function seoFuryPatchElementorTools() {
                // 1. Patch the raw PHP-generated config object.
                if (window.elementorFrontendConfig &&
                    typeof window.elementorFrontendConfig.tools === 'undefined') {
                    window.elementorFrontendConfig.tools = {};
                }
                // 2. Patch the frontend *instance* config.
                //    Elementor Pro may re-assign elementorFrontend.config to a
                //    shallow-copy (or entirely different object) that omits the
                //    'tools' key introduced in Elementor Free 3.26+.
                if (window.elementorFrontend && window.elementorFrontend.config &&
                    typeof window.elementorFrontend.config.tools === 'undefined') {
                    window.elementorFrontend.config.tools = {};
                }
            }

            // Run synchronously — patches whatever objects exist at script-parse time
            // (handles the case where config is assigned in the script body / constructor).
            seoFuryPatchElementorTools();

            // Run again in the DOMContentLoaded *capture* phase.
            // Capture fires before jQuery's non-capture ready() callbacks, so this
            // corrects the config even when elementorFrontend.config is assigned
            // inside a jQuery ready handler (non-capture, fires after capture).
            document.addEventListener('DOMContentLoaded', seoFuryPatchElementorTools, true);
        }());
        </script>
        <?php
    }

    /* ───────────────────────────────────────────────
     *  Enqueue CSS / JS for Elementor editor
     * ─────────────────────────────────────────────── */
    public function enqueue_editor_assets()
    {
        $post_id = $this->get_current_post_id();
        if (!$post_id) {
            return;
        }

        $post = get_post($post_id);
        if (!$post) {
            return;
        }

        // WordPress media uploader (for OG images etc.)
        wp_enqueue_media();

        // Dashicons
        wp_enqueue_style('dashicons');

        // Core metabox CSS
        wp_enqueue_style(
            'seo-fury-post-meta',
            SEO_FURY_URL . 'assets/post-meta.css',
            array(),
            SEO_FURY_VERSION
        );

        // Schema builder JS (dependency for post-meta.js)
        wp_enqueue_script(
            'seo-fury-schema-builder',
            SEO_FURY_URL . 'assets/schema-builder.js',
            array('jquery'),
            SEO_FURY_VERSION,
            true
        );

        // Core metabox JS
        wp_enqueue_script(
            'seo-fury-post-meta',
            SEO_FURY_URL . 'assets/post-meta.js',
            array('jquery', 'seo-fury-schema-builder'),
            SEO_FURY_VERSION,
            true
        );

        // Localize seoFuryData — same payload as class-post-meta.php
        $content    = !empty($post->post_content) ? wp_strip_all_tags(strip_shortcodes($post->post_content)) : '';
        $excerpt    = $content ? wp_trim_words($content, 20, '...') : '';
        $author     = !empty($post->post_author) ? get_userdata($post->post_author) : null;
        $thumb_url  = has_post_thumbnail($post_id) ? get_the_post_thumbnail_url($post_id, 'full') : '';
        $post_date  = (!empty($post->post_date) && $post->post_date !== '0000-00-00 00:00:00') ? wp_date('c', strtotime($post->post_date)) : '';
        $post_mod   = (!empty($post->post_modified) && $post->post_modified !== '0000-00-00 00:00:00') ? wp_date('c', strtotime($post->post_modified)) : '';

        wp_localize_script('seo-fury-post-meta', 'seoFuryData', array(
            'siteName'          => get_bloginfo('name'),
            'separator'         => get_option('seo_fury_title_separator', '—'),
            'postTitle'         => $post->post_title ?: '',
            'postExcerpt'       => $excerpt ?: '',
            'postId'            => $post->ID,
            'post_id'           => $post->ID,
            'has_builder'       => true,
            'postPermalink'     => get_permalink($post->ID) ?: '',
            'postStatus'        => $post->post_status,
            'postAuthor'        => $author ? $author->display_name : '',
            'postDate'          => $post_date,
            'postModified'      => $post_mod,
            'postThumbnail'     => $thumb_url,
            'defaultSchemaType' => get_option('seo_fury_default_schema_' . $post->post_type, ''),
            'ajaxUrl'           => admin_url('admin-ajax.php'),
            'nonce'             => wp_create_nonce('seo_fury_nonce'),
            'postMetaNonce'     => wp_create_nonce('seo_fury_post_meta_nonce'),
            'internalLinksNonce'   => wp_create_nonce('seo_fury_internal_links_nonce'),
            'schemaTemplatesNonce' => wp_create_nonce('seo_fury_schema_templates_nonce'),
            'isElementor'       => true,
            'language'          => get_locale(),
            'i18n'              => $this->get_i18n_strings(),
            'shortcodeVariables' => class_exists('SEO_Fury_Shortcode_Variables') ? SEO_Fury_Shortcode_Variables::get_variables() : array(),
        ));

        // Page-speed tab assets
        wp_enqueue_style('seo-fury-page-speed', SEO_FURY_URL . 'assets/page-speed.css', array(), SEO_FURY_VERSION);
        wp_enqueue_script('seo-fury-page-speed', SEO_FURY_URL . 'assets/page-speed.js', array('jquery'), SEO_FURY_VERSION, true);
        wp_localize_script('seo-fury-page-speed', 'seoFuryPageSpeed', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('seo_fury_page_speed_nonce'),
            'post_id'  => $post->ID,
            'i18n'     => array(
                'networkError'  => __('Network error', 'seo-fury'),
                'opportunities' => __('Opportunities', 'seo-fury'),
                'speedHistory'  => __('Speed History', 'seo-fury'),
                'date'          => __('Date', 'seo-fury'),
                'device'        => __('Device', 'seo-fury'),
                'score'         => __('Score', 'seo-fury'),
            ),
        ));

        // AI image generation — only if file exists (PRO)
        if (file_exists(SEO_FURY_PATH . 'assets/ai-image.js')) {
            wp_enqueue_script('seo-fury-ai-image', SEO_FURY_URL . 'assets/ai-image.js', array('jquery'), SEO_FURY_VERSION, true);
            wp_localize_script('seo-fury-ai-image', 'seoFuryAIImage', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce'    => wp_create_nonce('seo_fury_ai_image_nonce'),
                'post_id'  => $post->ID,
                'i18n'     => array(
                    'promptRequired'   => __('Please enter a prompt', 'seo-fury'),
                    'saving'           => __('Saving...', 'seo-fury'),
                    'saveBtn'          => __('Save to Media Library', 'seo-fury'),
                    'networkError'     => __('Network error', 'seo-fury'),
                    'timeout'          => __('Request timed out', 'seo-fury'),
                    'autoPromptPrefix' => __('A professional, high-quality image for a blog post titled: ', 'seo-fury'),
                    'removeFeatured'   => __('Remove featured image', 'seo-fury'),
                ),
            ));
        }

        // AI SEO text generation — only if file exists (PRO)
        if (file_exists(SEO_FURY_PATH . 'assets/ai-seo-text.js')) {
            wp_enqueue_script('seo-fury-ai-seo-text', SEO_FURY_URL . 'assets/ai-seo-text.js', array('jquery'), SEO_FURY_VERSION, true);
            wp_localize_script('seo-fury-ai-seo-text', 'seoFuryAISeoText', array(
                'ajax_url'   => admin_url('admin-ajax.php'),
                'nonce'      => wp_create_nonce('seo_fury_ai_seo_text_nonce'),
                'post_title' => $post->post_title ?: '',
                'language'   => get_locale(),
                'i18n'       => array(
                    'titleRequired' => __('Post title is required for AI generation', 'seo-fury'),
                    'networkError'  => __('Network error', 'seo-fury'),
                ),
            ));
        }

        // Elementor-specific panel JS
        wp_enqueue_script(
            'seo-fury-elementor-panel',
            SEO_FURY_URL . 'assets/elementor-panel.js',
            array('jquery', 'seo-fury-post-meta'),
            SEO_FURY_VERSION,
            true
        );

        $brand = function_exists('seo_fury_get_brand_name') ? seo_fury_get_brand_name() : 'SEO Fury';

        wp_localize_script('seo-fury-elementor-panel', 'seoFuryElementor', array(
            'ajax_url'   => admin_url('admin-ajax.php'),
            'nonce'      => wp_create_nonce('seo_fury_elementor_save'),
            'post_id'    => $post_id,
            'brand_name' => $brand,
        ));
    }

    /* ───────────────────────────────────────────────
     *  Render hidden panel + modals in Elementor footer
     * ─────────────────────────────────────────────── */
    public function render_editor_panel()
    {
        $post_id = $this->get_current_post_id();
        if (!$post_id) {
            return;
        }

        $post = get_post($post_id);
        if (!$post) {
            return;
        }

        $post_meta = SEO_Fury_Core::get_instance()->get_post_meta();
        if (!$post_meta) {
            return;
        }
        $brand = function_exists('seo_fury_get_brand_name') ? seo_fury_get_brand_name() : 'SEO Fury';

        // Inline CSS for the Elementor panel (self-contained)
        $this->render_panel_styles();
        ?>

        <!-- SEO Fury Elementor Panel (hidden by default, toggled via JS) -->
        <div id="seo-fury-elementor-panel" class="seo-fury-el-panel">
            <div class="seo-fury-el-panel-header">
                <div class="seo-fury-el-panel-title">
                    <span class="dashicons dashicons-search"></span>
                    <?php echo esc_html($brand); ?>
                </div>
                <button type="button" id="seo-fury-el-panel-close" class="seo-fury-el-panel-close" title="<?php esc_attr_e('Close', 'seo-fury'); ?>">
                    <span class="dashicons dashicons-no-alt"></span>
                </button>
            </div>
            <div class="seo-fury-el-panel-body">
                <div id="seo_fury_post_meta">
                    <?php $post_meta->render_meta_box($post); ?>
                </div>
            </div>
        </div>

        <?php
        // Force-render modals (snippet editor etc.) — bypass screen check
        $post_meta->render_modals_in_footer_elementor();
    }

    /* ───────────────────────────────────────────────
     *  AJAX: Save SEO meta from Elementor editor
     * ─────────────────────────────────────────────── */
    public function ajax_save()
    {
        check_ajax_referer('seo_fury_elementor_save', '_el_nonce');

        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        if (!$post_id || !current_user_can('edit_post', $post_id)) {
            wp_send_json_error(array('message' => 'Unauthorized'));
        }

        $post = get_post($post_id);
        if (!$post) {
            wp_send_json_error(array('message' => 'Post not found'));
        }

        // Inject the nonce so save_seo_meta() passes verification
        $_POST['seo_fury_post_meta_nonce_field'] = wp_create_nonce('seo_fury_post_meta_nonce');

        $post_meta = SEO_Fury_Core::get_instance()->get_post_meta();
        $post_meta->save_seo_meta($post_id, $post);

        wp_send_json_success(array('message' => 'SEO data saved'));
    }

    /* ───────────────────────────────────────────────
     *  Helpers
     * ─────────────────────────────────────────────── */
    private function get_current_post_id()
    {
        if (isset($_GET['post'])) {
            return intval($_GET['post']);
        }
        $post_id = get_the_ID();
        return $post_id ?: 0;
    }

    /**
     * Return i18n strings — mirrors class-post-meta.php enqueue_post_meta_assets()
     */
    private function get_i18n_strings()
    {
        return array(
            'focusKeywordSet'            => __('Focus keyword is set', 'seo-fury'),
            'addFocusKeyword'            => __('Add a focus keyword', 'seo-fury'),
            'keywordInTitle'             => __('Focus keyword in SEO title', 'seo-fury'),
            'addKeywordToTitle'          => __('Add focus keyword to SEO title', 'seo-fury'),
            'keywordInDescription'       => __('Focus keyword in meta description', 'seo-fury'),
            'addKeywordToDescription'    => __('Add focus keyword to meta description', 'seo-fury'),
            'keywordInContent'           => __('Focus keyword in content', 'seo-fury'),
            'addKeywordToContent'        => __('Add focus keyword to content', 'seo-fury'),
            'keywordInUrl'               => __('Focus keyword in URL', 'seo-fury'),
            'addKeywordToUrl'            => __('Add focus keyword to URL', 'seo-fury'),
            'keywordDensityOk'           => __('Keyword density is OK (0.5–2.5%)', 'seo-fury'),
            'keywordDensityBad'          => __('Keyword density out of range (0.5–2.5%)', 'seo-fury'),
            'titleLengthOk'              => __('SEO title length is OK (50–60)', 'seo-fury'),
            'titleLengthBad'             => __('Optimize SEO title length (50–60)', 'seo-fury'),
            'descLengthOk'              => __('Meta description length is OK (120–160)', 'seo-fury'),
            'descLengthBad'             => __('Optimize meta description length (120–160)', 'seo-fury'),
            'contentLengthOk'            => __('Content length is sufficient (300+ words)', 'seo-fury'),
            'contentLengthBad'           => __('Add more content (minimum 300 words)', 'seo-fury'),
            'h1Present'                  => __('H1 heading is present', 'seo-fury'),
            'addH1'                      => __('Add an H1 heading', 'seo-fury'),
            'h2Present'                  => __('H2 subheadings are present', 'seo-fury'),
            'addH2'                      => __('Add H2 subheadings', 'seo-fury'),
            'imagesAltOk'                => __('Images have alt attributes', 'seo-fury'),
            'addImageAlt'                => __('Add alt attributes to images', 'seo-fury'),
            'internalLinkPresent'        => __('Internal link is present', 'seo-fury'),
            'addInternalLink'            => __('Add an internal link', 'seo-fury'),
            'enoughSentences'            => __('Enough sentences for readability', 'seo-fury'),
            'addMoreSentences'           => __('Add more sentences', 'seo-fury'),
            'avgSentenceLengthOk'        => __('Average sentence length is OK', 'seo-fury'),
            'makeSentencesShorter'       => __('Make sentences shorter', 'seo-fury'),
            'noLongSentences'            => __('No overly long sentences', 'seo-fury'),
            'longSentences'              => __('There are overly long sentences', 'seo-fury'),
            'multipleParagraphs'         => __('Multiple paragraphs detected', 'seo-fury'),
            'splitParagraphs'            => __('Split text into paragraphs', 'seo-fury'),
            'paragraphLengthOk'          => __('Paragraph length is OK', 'seo-fury'),
            'makeParagraphsShorter'      => __('Make paragraphs shorter', 'seo-fury'),
            'listsPresent'               => __('Lists are present', 'seo-fury'),
            'addLists'                   => __('Add lists (ul/ol)', 'seo-fury'),
            'excellent'                  => __('Excellent', 'seo-fury'),
            'okay'                       => __('Okay', 'seo-fury'),
            'needsWork'                  => __('Needs work', 'seo-fury'),
            'selectImage'                => __('Select an image', 'seo-fury'),
            'useThisImage'               => __('Use this image', 'seo-fury'),
            'keywordInFirstParagraph'    => __('Keyword in first paragraph', 'seo-fury'),
            'addKeywordToFirstParagraph' => __('Add keyword to first paragraph', 'seo-fury'),
            'urlLengthOk'               => __('URL length is OK', 'seo-fury'),
            'shortenUrl'                 => __('Shorten URL (up to 75 chars)', 'seo-fury'),
            'externalLinkPresent'        => __('External link is present', 'seo-fury'),
            'addExternalLink'            => __('Add an external link', 'seo-fury'),
            'imagesInContent'            => __('Images are present in content', 'seo-fury'),
            'addImage'                   => __('Add an image', 'seo-fury'),
            'scanContent'                => __('Scan Content', 'seo-fury'),
            'scanning'                   => __('Scanning...', 'seo-fury'),
            'linked'                     => __('Linked!', 'seo-fury'),
            'notFound'                   => __('Not found', 'seo-fury'),
            'matchExact'                 => __('Exact', 'seo-fury'),
            'matchPartial'               => __('Partial', 'seo-fury'),
            'titlePlaceholder'           => __('Title', 'seo-fury'),
            'descriptionPlaceholder'     => __('Description', 'seo-fury'),
            'pasteJsonLd'                => __('// Paste your JSON-LD here', 'seo-fury'),
            'noSchemaSelected'           => __('No schema selected. Choose a template or import JSON-LD.', 'seo-fury'),
            'customJsonLd'               => __('Custom JSON-LD', 'seo-fury'),
            'preview'                    => __('Preview', 'seo-fury'),
            'edit'                       => __('Edit', 'seo-fury'),
            'remove'                     => __('Remove', 'seo-fury'),
            'jsonLdEmpty'                => __('JSON-LD is empty.', 'seo-fury'),
            'insertLink'                 => __('+ Link', 'seo-fury'),
            'findInText'                 => __('Find in text', 'seo-fury'),
            'question'                   => __('Question', 'seo-fury'),
            'answer'                     => __('Answer', 'seo-fury'),
            'questionPlaceholder'        => __('What is your question?', 'seo-fury'),
            'answerPlaceholder'          => __('Type the answer here...', 'seo-fury'),
            'defaultHint'                => __('(default)', 'seo-fury'),
            'enterTemplateName'          => __('Enter a name for this template:', 'seo-fury'),
            'templateSaved'              => __('Template saved successfully.', 'seo-fury'),
            'templateSaveError'          => __('Failed to save template.', 'seo-fury'),
            'confirmDeleteTemplate'      => __('Delete this saved template?', 'seo-fury'),
            'noSavedTemplates'           => __('No saved templates yet. Save a schema from the Schema Editor to create one.', 'seo-fury'),
            'applyTemplate'              => __('Apply', 'seo-fury'),
            'loadingTemplates'           => __('Loading templates...', 'seo-fury'),
            // Keyword variations (partial match)
            'keywordInTitlePartial'          => __('Keyword variation found in SEO title', 'seo-fury'),
            'keywordInDescriptionPartial'    => __('Keyword variation found in meta description', 'seo-fury'),
            'keywordInContentPartial'        => __('Keyword variation found in content', 'seo-fury'),
            'keywordInUrlPartial'            => __('Keyword variation found in URL', 'seo-fury'),
            'keywordInFirstParagraphPartial' => __('Keyword variation found in first paragraph', 'seo-fury'),
            // Passive voice
            'passiveVoiceOk'         => __('Passive voice usage is minimal', 'seo-fury'),
            'tooMuchPassiveVoice'    => __('Too much passive voice (%d% of sentences)', 'seo-fury'),
            // Transition words
            'transitionWordsOk'      => __('Good use of transition words (%d%)', 'seo-fury'),
            'addTransitionWords'     => __('Use more transition words (%d%, aim for 30%+)', 'seo-fury'),
            // Flesch Reading Ease
            'fleschScoreOk'          => __('Flesch readability score is good', 'seo-fury'),
            'fleschScoreBad'         => __('Content may be difficult to read', 'seo-fury'),
            'fleschVeryEasy'         => __('Very Easy', 'seo-fury'),
            'fleschEasy'             => __('Easy', 'seo-fury'),
            'fleschModerate'         => __('Moderate', 'seo-fury'),
            'fleschDifficult'        => __('Difficult', 'seo-fury'),
            'fleschVeryDifficult'    => __('Very Difficult', 'seo-fury'),
            // Schema builder
            'searchPlaceholder'      => __('Search...', 'seo-fury'),
            'selectSchemaType'       => __('Select Schema Type', 'seo-fury'),
            'searchTypePlaceholder'  => __('Search type...', 'seo-fury'),
            'dragToReorder'          => __('Drag to reorder', 'seo-fury'),
            'propertyPlaceholder'    => __('Property (e.g. name)', 'seo-fury'),
            'valuePlaceholder'       => __('Value or %shortcode%', 'seo-fury'),
            'typeText'               => __('Text', 'seo-fury'),
            'typeNumber'             => __('Number', 'seo-fury'),
            'typeDate'               => __('Date', 'seo-fury'),
            'typeArray'              => __('Array', 'seo-fury'),
            'moveUp'                 => __('Up', 'seo-fury'),
            'moveDown'               => __('Down', 'seo-fury'),
            'deleteItem'             => __('Delete', 'seo-fury'),
            'specifySchemaType'      => __('Please specify @type for schema', 'seo-fury'),
            'addProperty'            => __('Property', 'seo-fury'),
            'addGroup'               => __('Group', 'seo-fury'),
        );
    }

    /**
     * Inline CSS for the Elementor integration panel.
     *
     * Elementor's editor loads its own CSS framework that aggressively resets
     * buttons, inputs, fonts, colors, etc.  We must use high-specificity
     * selectors with !important to ensure our metabox looks correct inside
     * the narrow (~300 px) left panel.
     */
    private function render_panel_styles()
    {
        ?>
        <style id="seo-fury-elementor-panel-css">
            /* ==========================================================
               0. SEO TAB IN ELEMENTOR NAVIGATION
               Custom class seo-fury-nav-tab (NOT elementor-component-tab)
               to avoid Elementor intercepting our click events.
               Styled to match Elementor's native tabs visually.
            ========================================================== */

            /* Keep all tabs on one line */
            #elementor-panel-elements-navigation,
            .elementor-panel-navigation {
                flex-wrap: nowrap !important;
            }

            /* Our SEO tab — matches Elementor native tab appearance */
            .seo-fury-nav-tab {
                all: unset !important;
                display: flex !important;
                align-items: center !important;
                justify-content: center !important;
                flex: 1 1 0 !important;
                padding: 10px 0 !important;
                cursor: pointer !important;
                font-size: 12px !important;
                font-weight: 500 !important;
                font-family: Arial, Helvetica, sans-serif !important;
                color: #a4afb7 !important;
                background: transparent !important;
                border: none !important;
                border-bottom: 2px solid transparent !important;
                box-sizing: border-box !important;
                text-align: center !important;
                transition: color .2s, border-color .2s !important;
                line-height: 1 !important;
            }
            .seo-fury-nav-tab:hover {
                color: #d5dadf !important;
            }
            .seo-fury-nav-tab.seo-fury-nav-tab-active {
                color: #d5dadf !important;
                border-bottom-color: #d5dadf !important;
                font-weight: 600 !important;
            }

            /* ── Fallback: header button (if navigation not found) ── */
            .seo-fury-el-header-btn {
                display: flex;
                align-items: center;
                gap: 4px;
                padding: 4px 10px;
                background: #5b4bdb;
                color: #fff;
                border: none;
                border-radius: 3px;
                cursor: pointer;
                font-size: 12px;
                font-weight: 600;
                margin: 4px 6px;
                transition: background .15s;
            }
            .seo-fury-el-header-btn:hover { background: #4338ca; }

            /* ── Hidden source panel (footer, holds original HTML) ── */
            #seo-fury-elementor-panel { display: none !important; }

            /* ==========================================================
               1. OVERLAY PANEL — on <body>, position:fixed
               Positioned via JS to exactly overlay #elementor-panel.
               Completely outside Elementor's DOM.
            ========================================================== */
            #seo-fury-el-overlay {
                display: none;
                position: fixed !important;
                z-index: 200000 !important;
                flex-direction: column !important;
                overflow: hidden !important;
                background: #fff !important;
                box-shadow: 2px 0 8px rgba(0,0,0,.15) !important;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif !important;
            }

            #seo-fury-el-overlay.seo-fury-el-ov-visible {
                display: flex !important;
            }

            /* ── Header (back + title) ── */
            .seo-fury-el-ov-hdr {
                display: flex !important;
                align-items: center !important;
                gap: 8px !important;
                padding: 0 10px !important;
                height: 48px !important;
                min-height: 48px !important;
                background: #27272a !important;
                border-bottom: 1px solid #3f3f46 !important;
                color: #e4e4e7 !important;
                flex-shrink: 0 !important;
            }

            .seo-fury-el-ov-back {
                all: unset !important;
                display: flex !important;
                align-items: center !important;
                justify-content: center !important;
                width: 28px !important;
                height: 28px !important;
                cursor: pointer !important;
                color: #a1a1aa !important;
                border-radius: 3px !important;
                transition: color .15s, background .15s !important;
                flex-shrink: 0 !important;
                pointer-events: auto !important;
            }
            .seo-fury-el-ov-back:hover {
                color: #fff !important;
                background: rgba(255,255,255,.1) !important;
            }
            .seo-fury-el-ov-back i {
                font-size: 14px !important;
            }

            .seo-fury-el-ov-title {
                font-size: 13px !important;
                font-weight: 600 !important;
                font-family: Arial, Helvetica, sans-serif !important;
                color: #e4e4e7 !important;
                line-height: 1 !important;
            }
            .seo-fury-el-ov-title i {
                font-size: 13px !important;
                margin-right: 4px !important;
            }

            /* ── Scrollable body ── */
            .seo-fury-el-ov-body {
                flex: 1 1 auto !important;
                overflow-y: auto !important;
                overflow-x: hidden !important;
                background: #fff !important;
                min-height: 0 !important;
            }

            /* ==========================================================
               2. WRAPPER — reset Elementor's overrides
            ========================================================== */
            #seo-fury-el-overlay .seo-fury-wrapper {
                margin: 0 !important;
                padding: 0 !important;
                border: none !important;
                border-radius: 0 !important;
                box-shadow: none !important;
                background: #fff !important;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif !important;
                font-size: 13px !important;
                color: #1e1e1e !important;
                line-height: 1.4 !important;
            }

            #seo-fury-el-overlay .seo-fury-content {
                display: flex !important;
                flex-direction: column !important;
                min-height: auto !important;
            }

            /* ==========================================================
               4. TABS — icon-only row, sticky at top
            ========================================================== */
            #seo-fury-el-overlay .seo-fury-tabs {
                display: flex !important;
                flex-wrap: nowrap !important;
                gap: 0 !important;
                justify-content: space-around !important;
                padding: 4px 2px !important;
                margin: 0 !important;
                background: #f8f9fa !important;
                border-bottom: 1px solid #e2e8f0 !important;
                position: sticky !important;
                top: 0 !important;
                z-index: 10 !important;
            }

            #seo-fury-el-overlay .seo-fury-tab {
                /* Reset Elementor button overrides */
                all: unset !important;
                display: flex !important;
                flex-direction: column !important;
                align-items: center !important;
                justify-content: center !important;
                flex: 1 1 0 !important;
                min-width: 0 !important;
                padding: 8px 4px !important;
                cursor: pointer !important;
                background: transparent !important;
                border: none !important;
                border-bottom: 2px solid transparent !important;
                border-radius: 0 !important;
                color: #94a3b8 !important;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
                font-size: 11px !important;
                font-weight: 500 !important;
                line-height: 1 !important;
                text-align: center !important;
                transition: color .15s, border-color .15s, background .15s !important;
                box-shadow: none !important;
                outline: none !important;
                box-sizing: border-box !important;
            }

            #seo-fury-el-overlay .seo-fury-tab:hover {
                color: #64748b !important;
                background: #f1f5f9 !important;
            }

            #seo-fury-el-overlay .seo-fury-tab.active {
                color: #4F46E5 !important;
                border-bottom-color: #4F46E5 !important;
                background: #fff !important;
                font-weight: 600 !important;
            }

            /* Icons */
            #seo-fury-el-overlay .seo-fury-tab .dashicons {
                font-size: 18px !important;
                width: 18px !important;
                height: 18px !important;
                line-height: 18px !important;
                color: inherit !important;
                display: block !important;
            }

            /* Hide text labels — icons only in narrow panel */
            #seo-fury-el-overlay .seo-fury-tab-label {
                display: none !important;
            }

            /* ==========================================================
               5. TAB PANELS
            ========================================================== */
            #seo-fury-el-overlay .seo-fury-tab-panels {
                flex: 1 !important;
                min-height: auto !important;
            }

            #seo-fury-el-overlay .seo-fury-tab-content {
                padding: 12px 10px !important;
                background: #fff !important;
                color: #1e1e1e !important;
            }

            #seo-fury-el-overlay .seo-fury-tab-content.active {
                display: block !important;
            }

            /* ==========================================================
               6. SECTIONS
            ========================================================== */
            #seo-fury-el-overlay .seo-fury-section {
                margin-bottom: 12px !important;
                padding: 10px !important;
                background: #f8fafc !important;
                border: 1px solid #e2e8f0 !important;
                border-radius: 6px !important;
                box-shadow: none !important;
            }

            #seo-fury-el-overlay .seo-fury-section:last-child {
                margin-bottom: 0 !important;
            }

            #seo-fury-el-overlay .seo-fury-section h4 {
                margin: 0 0 8px 0 !important;
                padding: 0 0 6px 0 !important;
                font-size: 11px !important;
                font-weight: 700 !important;
                text-transform: uppercase !important;
                letter-spacing: 0.5px !important;
                color: #64748b !important;
                border-bottom: none !important;
                background: transparent !important;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
                line-height: 1.3 !important;
            }

            /* ==========================================================
               7. FORM ELEMENTS — override Elementor resets
            ========================================================== */
            #seo-fury-el-overlay input[type="text"],
            #seo-fury-el-overlay input[type="url"],
            #seo-fury-el-overlay input[type="number"],
            #seo-fury-el-overlay input[type="email"],
            #seo-fury-el-overlay textarea,
            #seo-fury-el-overlay select {
                display: block !important;
                width: 100% !important;
                padding: 6px 8px !important;
                font-size: 12px !important;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
                color: #1e1e1e !important;
                background: #fff !important;
                border: 1px solid #cbd5e1 !important;
                border-radius: 4px !important;
                box-shadow: none !important;
                outline: none !important;
                box-sizing: border-box !important;
                line-height: 1.4 !important;
                -webkit-appearance: none !important;
                transition: border-color .15s !important;
            }

            #seo-fury-el-overlay input[type="text"]:focus,
            #seo-fury-el-overlay input[type="url"]:focus,
            #seo-fury-el-overlay input[type="number"]:focus,
            #seo-fury-el-overlay textarea:focus,
            #seo-fury-el-overlay select:focus {
                border-color: #4F46E5 !important;
                box-shadow: 0 0 0 1px #4F46E5 !important;
            }

            #seo-fury-el-overlay textarea {
                min-height: 60px !important;
                resize: vertical !important;
            }

            #seo-fury-el-overlay input[type="checkbox"] {
                -webkit-appearance: checkbox !important;
                appearance: checkbox !important;
                width: 16px !important;
                height: 16px !important;
                min-width: 16px !important;
                margin: 0 6px 0 0 !important;
                padding: 0 !important;
                display: inline-block !important;
                background: #fff !important;
                border: 1px solid #cbd5e1 !important;
                border-radius: 3px !important;
                vertical-align: middle !important;
                cursor: pointer !important;
                accent-color: #4F46E5 !important;
            }

            #seo-fury-el-overlay .seo-fury-field label {
                display: flex !important;
                align-items: center !important;
                gap: 0 !important;
                cursor: pointer !important;
            }

            #seo-fury-el-overlay .seo-fury-field label input[type="checkbox"] {
                display: inline-block !important;
                width: 16px !important;
            }

            /* ==========================================================
               8. LABELS & TEXT
            ========================================================== */
            #seo-fury-el-overlay label {
                display: block !important;
                font-size: 12px !important;
                font-weight: 500 !important;
                color: #334155 !important;
                margin-bottom: 4px !important;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
                line-height: 1.4 !important;
            }

            #seo-fury-el-overlay .description,
            #seo-fury-el-overlay p.description {
                font-size: 11px !important;
                color: #94a3b8 !important;
                margin: 4px 0 0 !important;
                line-height: 1.3 !important;
            }

            #seo-fury-el-overlay .seo-fury-field {
                margin-bottom: 10px !important;
            }

            #seo-fury-el-overlay .seo-fury-fields-grid {
                display: grid !important;
                grid-template-columns: 1fr !important;
                gap: 10px !important;
            }

            #seo-fury-el-overlay .char-counter {
                font-size: 10px !important;
                color: #94a3b8 !important;
            }

            /* ==========================================================
               9. BUTTONS — override Elementor's aggressive button resets
            ========================================================== */
            #seo-fury-el-overlay .button,
            #seo-fury-el-overlay .button-secondary {
                all: unset !important;
                display: inline-flex !important;
                align-items: center !important;
                justify-content: center !important;
                gap: 4px !important;
                padding: 5px 12px !important;
                font-size: 12px !important;
                font-weight: 500 !important;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
                color: #334155 !important;
                background: #fff !important;
                border: 1px solid #cbd5e1 !important;
                border-radius: 4px !important;
                cursor: pointer !important;
                box-sizing: border-box !important;
                line-height: 1.4 !important;
                text-decoration: none !important;
                transition: all .15s !important;
            }

            #seo-fury-el-overlay .button:hover,
            #seo-fury-el-overlay .button-secondary:hover {
                background: #f1f5f9 !important;
                border-color: #94a3b8 !important;
            }

            #seo-fury-el-overlay .button-primary {
                all: unset !important;
                display: inline-flex !important;
                align-items: center !important;
                justify-content: center !important;
                gap: 4px !important;
                padding: 5px 14px !important;
                font-size: 12px !important;
                font-weight: 600 !important;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
                color: #fff !important;
                background: #4F46E5 !important;
                border: 1px solid #4338CA !important;
                border-radius: 4px !important;
                cursor: pointer !important;
                box-sizing: border-box !important;
                line-height: 1.4 !important;
                text-decoration: none !important;
                transition: all .15s !important;
            }

            #seo-fury-el-overlay .button-primary:hover {
                background: #4338CA !important;
            }

            /* AI generate buttons */
            #seo-fury-el-overlay .sf-ai-gen-btn {
                all: unset !important;
                display: inline-flex !important;
                align-items: center !important;
                justify-content: center !important;
                width: 30px !important;
                height: 30px !important;
                padding: 0 !important;
                background: linear-gradient(135deg, #6366F1, #8B5CF6) !important;
                border: none !important;
                border-radius: 4px !important;
                cursor: pointer !important;
                flex-shrink: 0 !important;
                box-sizing: border-box !important;
            }

            #seo-fury-el-overlay .sf-ai-gen-btn .dashicons {
                color: #fff !important;
                font-size: 14px !important;
                width: 14px !important;
                height: 14px !important;
            }

            /* ==========================================================
               10. GOOGLE PREVIEW
            ========================================================== */
            #seo-fury-el-overlay .google-preview {
                max-width: 100% !important;
                background: #fff !important;
                border: 1px solid #e2e8f0 !important;
                border-radius: 6px !important;
                padding: 10px !important;
                margin-bottom: 10px !important;
                box-shadow: none !important;
            }

            #seo-fury-el-overlay .preview-title {
                font-size: 15px !important;
                color: #1a0dab !important;
                line-height: 1.3 !important;
                font-family: Arial, sans-serif !important;
            }

            #seo-fury-el-overlay .preview-url {
                font-size: 11px !important;
                color: #006621 !important;
                line-height: 1.3 !important;
            }

            #seo-fury-el-overlay .preview-description {
                font-size: 12px !important;
                color: #545454 !important;
                line-height: 1.4 !important;
            }

            #seo-fury-el-overlay .seo-fury-edit-snippet {
                width: 100% !important;
                justify-content: center !important;
            }

            /* ==========================================================
               11. SOCIAL PREVIEWS
            ========================================================== */
            #seo-fury-el-overlay .og-preview,
            #seo-fury-el-overlay .facebook-preview,
            #seo-fury-el-overlay .twitter-preview {
                max-width: 100% !important;
                background: #fff !important;
                border: 1px solid #e2e8f0 !important;
                border-radius: 6px !important;
                box-shadow: none !important;
            }

            /* ==========================================================
               12. SCORE BADGES / INDICATORS
            ========================================================== */
            #seo-fury-el-overlay .seo-score-badge,
            #seo-fury-el-overlay .seo-fury-score {
                font-size: 11px !important;
                font-weight: 600 !important;
            }

            /* ==========================================================
               13. INPUT-WITH-DROPDOWN & SHORTCODE
            ========================================================== */
            #seo-fury-el-overlay .input-with-dropdown {
                display: flex !important;
                gap: 4px !important;
                align-items: flex-start !important;
            }

            #seo-fury-el-overlay .input-with-dropdown input[type="text"],
            #seo-fury-el-overlay .input-with-dropdown textarea {
                flex: 1 !important;
                min-width: 0 !important;
            }

            #seo-fury-el-overlay .shortcode-dropdown-btn {
                all: unset !important;
                display: inline-flex !important;
                align-items: center !important;
                justify-content: center !important;
                width: 30px !important;
                height: 30px !important;
                padding: 0 !important;
                background: #f1f5f9 !important;
                border: 1px solid #cbd5e1 !important;
                border-radius: 4px !important;
                cursor: pointer !important;
                flex-shrink: 0 !important;
                box-sizing: border-box !important;
                color: #64748b !important;
                font-size: 16px !important;
            }

            #seo-fury-el-overlay .shortcode-dropdown-btn:hover {
                background: #e2e8f0 !important;
            }

            /* ==========================================================
               14. SCHEMA CARDS
            ========================================================== */
            #seo-fury-el-overlay .seo-fury-schema-card {
                background: #fff !important;
                border: 1px solid #e2e8f0 !important;
                border-radius: 4px !important;
                padding: 8px !important;
                margin-bottom: 6px !important;
                display: flex !important;
                align-items: center !important;
                gap: 6px !important;
            }

            #seo-fury-el-overlay .seo-fury-schema-label {
                flex: 1 !important;
                font-size: 12px !important;
                color: #1e1e1e !important;
            }

            /* ==========================================================
               15. LINKS TAB
            ========================================================== */
            #seo-fury-el-overlay .sf-internal-links-table {
                width: 100% !important;
                font-size: 11px !important;
            }

            #seo-fury-el-overlay .sf-internal-links-table th,
            #seo-fury-el-overlay .sf-internal-links-table td {
                padding: 4px 6px !important;
                font-size: 11px !important;
                color: #334155 !important;
                border-bottom: 1px solid #e2e8f0 !important;
            }

            #seo-fury-el-overlay .sf-internal-links-table th {
                font-weight: 600 !important;
                background: #f8fafc !important;
            }

            /* ==========================================================
               16. MISC OVERRIDES
            ========================================================== */
            /* Dashicons in general */
            #seo-fury-el-overlay .dashicons {
                font-family: dashicons !important;
                line-height: 1 !important;
            }

            /* Any a tags */
            #seo-fury-el-overlay a {
                color: #4F46E5 !important;
                text-decoration: none !important;
            }
            #seo-fury-el-overlay a:hover {
                text-decoration: underline !important;
            }

            /* HR */
            #seo-fury-el-overlay hr {
                border: none !important;
                border-top: 1px solid #e2e8f0 !important;
                margin: 10px 0 !important;
            }

            /* PRO badges */
            #seo-fury-el-overlay .sf-pro-badge,
            #seo-fury-el-overlay .seo-fury-pro-badge {
                font-size: 9px !important;
                background: linear-gradient(135deg, #4F46E5, #7C3AED) !important;
                color: #fff !important;
                padding: 1px 6px !important;
                border-radius: 8px !important;
                font-weight: 600 !important;
            }

            /* Checklist items */
            #seo-fury-el-overlay .seo-fury-checklist li,
            #seo-fury-el-overlay .seo-check-item {
                font-size: 11px !important;
                padding: 4px 0 !important;
                color: #334155 !important;
                line-height: 1.4 !important;
            }

            /* Page Speed section */
            #seo-fury-el-overlay .sf-psi-scores {
                display: flex !important;
                gap: 8px !important;
                flex-wrap: wrap !important;
            }

            /* ==========================================================
               17. TOAST NOTIFICATION
            ========================================================== */
            .seo-fury-el-toast {
                position: fixed;
                bottom: 20px;
                right: 20px;
                background: #22c55e;
                color: #fff;
                padding: 10px 20px;
                border-radius: 6px;
                font-size: 13px;
                z-index: 200000;
                box-shadow: 0 4px 12px rgba(0,0,0,.15);
                opacity: 0;
                transform: translateY(10px);
                transition: all .3s ease;
            }
            .seo-fury-el-toast.seo-fury-el-toast-show {
                opacity: 1;
                transform: translateY(0);
            }
        </style>
        <?php
    }
}
