<?php

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

require_once SEO_FURY_PATH . 'includes/class-post-meta-basic.php';
require_once SEO_FURY_PATH . 'includes/class-post-meta-social.php';
require_once SEO_FURY_PATH . 'includes/class-post-meta-schema.php';

class SEO_Fury_Post_Meta
{
    private $basic_meta;
    private $social_meta;
    private $schema_meta;
    private $internal_links;
    private $modal_data = null;

    public function __construct()
    {
        $this->init_hooks();
        $this->basic_meta = new SEO_Fury_Post_Meta_Basic();
        $this->social_meta = new SEO_Fury_Post_Meta_Social();
        $this->schema_meta = new SEO_Fury_Post_Meta_Schema();
        $this->internal_links = new SEO_Fury_Post_Meta_Internal_Links();
    }

    private function init_hooks()
    {
        add_action('add_meta_boxes', array($this, 'add_seo_meta_box'));

        add_action('save_post', array($this, 'save_seo_meta'), 10, 2);

        add_action('admin_enqueue_scripts', array($this, 'enqueue_post_meta_assets'));
        add_action('enqueue_block_editor_assets', array($this, 'enqueue_block_editor_assets'));

        add_action('wp_head', array($this, 'remove_default_meta_tags'), -1);
        add_action('wp_head', array($this, 'output_seo_meta_tags'), 1);

        add_action('admin_footer', array($this, 'render_modals_in_footer'));

        add_action('wp_ajax_seo_fury_check_duplicate_meta', array($this, 'ajax_check_duplicate_meta'));
    }

    /**
     * AJAX: warn if another post uses the exact same custom SEO title or meta
     * description. Template values (containing %variables%) are skipped because
     * they resolve to different text per post, so they aren't real duplicates.
     */
    public function ajax_check_duplicate_meta()
    {
        check_ajax_referer('seo_fury_nonce', 'nonce');
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'seo-fury')));
        }

        global $wpdb;
        $post_id = isset($_POST['post_id']) ? (int) $_POST['post_id'] : 0;
        $title   = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : '';
        $desc    = isset($_POST['description']) ? sanitize_text_field(wp_unslash($_POST['description'])) : '';

        $out = array('title' => array(), 'description' => array());

        $lookup = function ($meta_key, $value) use ($wpdb, $post_id) {
            $value = trim($value);
            if ($value === '' || strpos($value, '%') !== false) {
                return array(); // empty or a template — not a real duplicate
            }
            $rows = $wpdb->get_results($wpdb->prepare(
                "SELECT pm.post_id, p.post_title FROM {$wpdb->postmeta} pm
                 JOIN {$wpdb->posts} p ON p.ID = pm.post_id
                 WHERE pm.meta_key = %s AND pm.meta_value = %s AND pm.post_id != %d
                 AND p.post_status IN ('publish','future','draft','pending','private')
                 LIMIT 5",
                $meta_key, $value, $post_id
            ));
            $list = array();
            foreach ((array) $rows as $r) {
                $list[] = array(
                    'id'    => (int) $r->post_id,
                    'title' => $r->post_title !== '' ? $r->post_title : __('(no title)', 'seo-fury'),
                    'edit'  => get_edit_post_link($r->post_id, ''),
                );
            }
            return $list;
        };

        $out['title']       = $lookup('_seo_fury_title', $title);
        $out['description'] = $lookup('_seo_fury_description', $desc);

        wp_send_json_success($out);
    }


    public function remove_default_meta_tags()
    {
        if (!is_singular()) {
            return;
        }

        global $post;
        if (!$post) {
            return;
        }

        // Always remove WP default canonical — our plugin outputs its own
        remove_action('wp_head', 'rel_canonical');

        $has_page_robots = get_post_meta($post->ID, '_seo_fury_page_robots_noindex', true) ||
            get_post_meta($post->ID, '_seo_fury_page_robots_nofollow', true);

        if ($has_page_robots) {
            remove_action('wp_head', 'wp_robots');
            add_filter('wp_robots', '__return_empty_array', 999);
        }

        // We always output our own canonical on singular pages (and removed the
        // WP core one above), so suppress other active SEO plugins' canonical to
        // avoid two conflicting canonical tags on the same page. These filters
        // are no-ops when the respective plugin isn't active.
        add_filter('wpseo_canonical', '__return_false');               // Yoast SEO
        add_filter('aioseop_canonical_url', '__return_false');         // All in One SEO (v3)
        add_filter('aioseo_canonical_url', '__return_false');          // All in One SEO (v4)
        add_filter('rank_math/frontend/canonical', '__return_false');  // Rank Math
        add_filter('seopress_titles_canonical', '__return_false');     // SEOPress
    }

    public function add_seo_meta_box()
    {
        $post_types = get_post_types(array('public' => true), 'names');
        $brand = function_exists('seo_fury_get_brand_name') ? seo_fury_get_brand_name() : 'SEO Fury';

        foreach ($post_types as $post_type) {
            add_meta_box(
                'seo_fury_post_meta',
                $brand,
                array($this, 'render_meta_box'),
                $post_type,
                'normal',
                'high'
            );
        }
    }

    public function enqueue_post_meta_assets($hook)
    {
        if (!in_array($hook, array('post.php', 'post-new.php'))) {
            return;
        }

        // Skip in Elementor editor — handled by SEO_Fury_Elementor_Integration
        if (isset($_GET['action']) && $_GET['action'] === 'elementor') {
            return;
        }

        wp_enqueue_media();

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

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

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

        global $post;
        if ($post) {
            $content = !empty($post->post_content) ? $post->post_content : '';
            $content = strip_shortcodes($content);
            $content = wp_strip_all_tags($content);
            $excerpt = wp_trim_words($content, 20, '...');

            $author_name = '';
            if (!empty($post->post_author)) {
                $user = get_userdata($post->post_author);
                $author_name = $user ? $user->display_name : '';
            }
            $post_date = '';
            $post_modified = '';
            if (!empty($post->post_date) && $post->post_date !== '0000-00-00 00:00:00') {
                $post_date = wp_date('c', strtotime($post->post_date));
            }
            if (!empty($post->post_modified) && $post->post_modified !== '0000-00-00 00:00:00') {
                $post_modified = wp_date('c', strtotime($post->post_modified));
            }
            $thumbnail_url = '';
            if (has_post_thumbnail($post->ID)) {
                $thumbnail_url = get_the_post_thumbnail_url($post->ID, 'full');
            }

            $has_builder = ! empty( get_post_meta( $post->ID, '_elementor_data', true ) )
                || ! empty( get_post_meta( $post->ID, '_fl_builder_data', true ) )
                || ! empty( get_post_meta( $post->ID, '_brizy_post_compiled_html_body', true ) );

            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' => $has_builder,
                'postPermalink' => get_permalink($post->ID) ?: '',
                'postStatus' => $post->post_status,
                'postAuthor' => $author_name,
                'postDate' => $post_date,
                'postModified' => $post_modified,
                'postThumbnail' => $thumbnail_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'),
                'i18n' => 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'),
                    'faqBlockImportPrompt' => __('Add the questions and answers from this block to FAQPage schema markup?', 'seo-fury'),
                    'faqBlockImportYes' => __('Yes', 'seo-fury'),
                    'faqBlockImportNo' => __('No', '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'),
                ),
                'language' => get_locale(),
                'shortcodeVariables' => SEO_Fury_Shortcode_Variables::get_variables(),
            ));

            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 scripts — only load if files exist (PRO addon provides them)
            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'),
                    ),
                ));
            }

            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'),
                    ),
                ));
            }

            // AI Content Editor toolbar (PRO feature)
            $pro = class_exists('SEO_Fury_Core') ? SEO_Fury_Core::get_instance()->get_pro_features() : null;
            if ($pro && $pro->has_feature('ai_content')) {
                wp_enqueue_script('seo-fury-ai-content-editor', SEO_FURY_URL . 'assets/ai-content-editor.js', array('jquery'), SEO_FURY_VERSION, true);
                wp_localize_script('seo-fury-ai-content-editor', 'seoFuryAIContent', array(
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'nonce'    => wp_create_nonce('seo_fury_ai_seo_text_nonce'),
                    'language' => get_locale(),
                    'i18n'     => array(
                        'generate'        => __('Generate', 'seo-fury'),
                        'expand'          => __('Expand', 'seo-fury'),
                        'rewrite'         => __('Rewrite', 'seo-fury'),
                        'generating'      => __('Generating...', 'seo-fury'),
                        'generateTitle'   => __('Generate Content', 'seo-fury'),
                        'expandTitle'     => __('Expand Content', 'seo-fury'),
                        'rewriteTitle'    => __('Rewrite Content', 'seo-fury'),
                        'generateMsg'     => __('This will replace all current content with AI-generated text based on the post title. Continue?', 'seo-fury'),
                        'expandMsg'       => __('This will expand and add more content to your existing text. Continue?', 'seo-fury'),
                        'rewriteMsg'      => __('This will rewrite your entire content to improve it. The original text will be replaced. Continue?', 'seo-fury'),
                        'generateTooltip' => __('Generate a complete article from the post title', 'seo-fury'),
                        'expandTooltip'   => __('Add more content to the existing text', 'seo-fury'),
                        'rewriteTooltip'  => __('Rewrite and improve the existing content', 'seo-fury'),
                        'titleRequired'   => __('Please add a post title first.', 'seo-fury'),
                        'contentRequired' => __('Please add some content first before expanding or rewriting.', 'seo-fury'),
                        'confirm'         => __('Continue', 'seo-fury'),
                        'cancel'          => __('Cancel', 'seo-fury'),
                        'networkError'    => __('Network error', 'seo-fury'),
                        'timeout'         => __('Request timed out. Please try again.', 'seo-fury'),
                    ),
                ));
            }
        }
    }

    public function enqueue_block_editor_assets()
    {
        wp_enqueue_script(
            'seo-fury-post-meta-gutenberg',
            SEO_FURY_URL . 'assets/post-meta-gutenberg.js',
            array('wp-plugins', 'wp-edit-post', 'wp-element', 'wp-components', 'wp-dom-ready'),
            SEO_FURY_VERSION,
            true
        );

        wp_localize_script('seo-fury-post-meta-gutenberg', 'seoFuryGutenberg', array(
            'brandName' => function_exists('seo_fury_get_brand_name') ? seo_fury_get_brand_name() : 'SEO Fury',
        ));
    }

    public function parse_shortcodes($text, $post)
    {
        if (!is_string($text) || $text === '' || strpos($text, '%') === false) {
            return $text;
        }

        // Normalize legacy / mistyped variable names (from older dropdowns that
        // used a non-underscore syntax) to the canonical names understood by
        // SEO_Fury_Shortcode_Variables::resolve(). Without this, templates
        // already saved by users would leak literal %seotitle% into the page.
        $aliases = array(
            '%separator%'       => '%sep%',
            '%parenttitle%'     => '%parent_title%',
            '%seotitle%'        => '%seo_title%',
            '%seodescription%'  => '%seo_description%',
            '%excerptonly%'     => '%excerpt_only%',
            '%ptsingle%'        => '%pt_single%',
            '%ptplural%'        => '%pt_plural%',
            '%searchquery%'     => '%search_query%',
            '%termdescription%' => '%term_description%',
            '%userdescription%' => '%user_description%',
            '%wcshortdesc%'     => '%wc_shortdesc%',
            '%wcprice%'         => '%wc_price%',
            '%wcsku%'           => '%wc_sku%',
            '%wcbrand%'         => '%wc_brand%',
        );
        $text = str_replace(array_keys($aliases), array_values($aliases), $text);

        // Delegate to the full resolver (~60 variables: author, categories,
        // tags, focus keyword, post type, WooCommerce, dynamic patterns, etc.).
        if (class_exists('SEO_Fury_Shortcode_Variables')) {
            $text = SEO_Fury_Shortcode_Variables::resolve($text, $post);
        }

        // Legacy date parts not provided by the resolver, kept for templates
        // saved before these were superseded by %date(FORMAT)% / %currentyear%.
        if (strpos($text, '%') !== false) {
            $text = str_replace(
                array('%year%', '%month%', '%day%'),
                array(get_the_date('Y', $post->ID), get_the_date('m', $post->ID), get_the_date('d', $post->ID)),
                $text
            );
        }

        return $text;
    }




    public function render_meta_box($post)
    {
        wp_nonce_field('seo_fury_post_meta_nonce', 'seo_fury_post_meta_nonce_field');

        $meta_data = array(
            'meta_title' => get_post_meta($post->ID, '_seo_fury_title', true),
            'meta_description' => get_post_meta($post->ID, '_seo_fury_description', true),
            'meta_keywords' => get_post_meta($post->ID, '_seo_fury_keywords', true),
            'focus_keyword' => get_post_meta($post->ID, '_seo_fury_focus_keyword', true),
            'secondary_keywords' => get_post_meta($post->ID, '_seo_fury_secondary_keywords', true),
            'page_robots_noindex' => get_post_meta($post->ID, '_seo_fury_page_robots_noindex', true),
            'page_robots_nofollow' => get_post_meta($post->ID, '_seo_fury_page_robots_nofollow', true),
            'page_robots_noarchive' => get_post_meta($post->ID, '_seo_fury_page_robots_noarchive', true),
            'page_robots_nosnippet' => get_post_meta($post->ID, '_seo_fury_page_robots_nosnippet', true),
            'page_robots_noimageindex' => get_post_meta($post->ID, '_seo_fury_page_robots_noimageindex', true),
            'page_robots_max_snippet' => get_post_meta($post->ID, '_seo_fury_page_robots_max_snippet', true),
            'page_robots_max_video' => get_post_meta($post->ID, '_seo_fury_page_robots_max_video', true),
            'page_robots_max_image' => get_post_meta($post->ID, '_seo_fury_page_robots_max_image', true),
            'canonical_url' => get_post_meta($post->ID, '_seo_fury_canonical', true),
            'og_title' => get_post_meta($post->ID, '_seo_fury_og_title', true),
            'og_description' => get_post_meta($post->ID, '_seo_fury_og_description', true),
            'og_image' => get_post_meta($post->ID, '_seo_fury_og_image', true),
            'og_type' => get_post_meta($post->ID, '_seo_fury_og_type', true),
            'twitter_title' => get_post_meta($post->ID, '_seo_fury_twitter_title', true),
            'twitter_description' => get_post_meta($post->ID, '_seo_fury_twitter_description', true),
            'twitter_image' => get_post_meta($post->ID, '_seo_fury_twitter_image', true),
            'twitter_card_type' => get_post_meta($post->ID, '_seo_fury_twitter_card_type', true),
            'fb_title' => get_post_meta($post->ID, '_seo_fury_fb_title', true),
            'fb_description' => get_post_meta($post->ID, '_seo_fury_fb_description', true),
            'fb_image' => get_post_meta($post->ID, '_seo_fury_fb_image', true),
            'snippet_permalink' => get_post_meta($post->ID, '_seo_fury_snippet_permalink', true),
        );

        if (empty($meta_data['canonical_url'])) {
            $meta_data['canonical_url'] = get_permalink($post->ID);
            if (!$meta_data['canonical_url']) $meta_data['canonical_url'] = '';
        }

        if (empty($meta_data['og_type'])) $meta_data['og_type'] = 'article';
        if (empty($meta_data['twitter_card_type'])) $meta_data['twitter_card_type'] = 'summary_large_image';

        $preview_title = $this->parse_shortcodes($meta_data['meta_title'] ?: '%title%', $post);
        $preview_description = $this->parse_shortcodes($meta_data['meta_description'] ?: '%excerpt%', $post);

        $current_url = get_permalink($post->ID);
        if (!$current_url) $current_url = home_url();

        $og_preview_title = !empty($meta_data['og_title']) ? $meta_data['og_title'] : $preview_title;
        $og_preview_desc = !empty($meta_data['og_description']) ? $meta_data['og_description'] : $preview_description;
        $og_preview_image = !empty($meta_data['og_image']) ? $meta_data['og_image'] : '';

        $tw_preview_title = !empty($meta_data['twitter_title']) ? $meta_data['twitter_title'] : $og_preview_title;
        $tw_preview_desc = !empty($meta_data['twitter_description']) ? $meta_data['twitter_description'] : $og_preview_desc;
        $tw_preview_image = !empty($meta_data['twitter_image']) ? $meta_data['twitter_image'] : $og_preview_image;

        $fb_preview_title = !empty($meta_data['fb_title']) ? $meta_data['fb_title'] : $og_preview_title;
        $fb_preview_desc = !empty($meta_data['fb_description']) ? $meta_data['fb_description'] : $og_preview_desc;
        $fb_preview_image = !empty($meta_data['fb_image']) ? $meta_data['fb_image'] : $og_preview_image;

        $preview_data = array(
            'preview_title' => $preview_title,
            'preview_description' => $preview_description,
            'current_url' => $current_url,
            'og_preview_title' => $og_preview_title,
            'og_preview_desc' => $og_preview_desc,
            'og_preview_image' => $og_preview_image,
            'tw_preview_title' => $tw_preview_title,
            'tw_preview_desc' => $tw_preview_desc,
            'tw_preview_image' => $tw_preview_image,
            'fb_preview_title' => $fb_preview_title,
            'fb_preview_desc' => $fb_preview_desc,
            'fb_preview_image' => $fb_preview_image,
        );

?>
        <div class="seo-fury-wrapper">
            <div class="seo-fury-content">
                <!-- Navigation tabs -->
                <div class="seo-fury-tabs">
                    <button type="button" class="seo-fury-tab active" data-tab="basic">
                        <span class="dashicons dashicons-search"></span>
                        <span class="seo-fury-tab-label"><?php esc_html_e('SEO Basics', 'seo-fury'); ?></span>
                    </button>
                    <button type="button" class="seo-fury-tab" data-tab="advanced">
                        <span class="dashicons dashicons-admin-generic"></span>
                        <span class="seo-fury-tab-label"><?php esc_html_e('Advanced', 'seo-fury'); ?></span>
                    </button>
                    <button type="button" class="seo-fury-tab" data-tab="schema">
                        <span class="dashicons dashicons-editor-code"></span>
                        <span class="seo-fury-tab-label"><?php esc_html_e('Schema', 'seo-fury'); ?></span>
                    </button>
                    <button type="button" class="seo-fury-tab" data-tab="links">
                        <span class="dashicons dashicons-admin-links"></span>
                        <span class="seo-fury-tab-label"><?php esc_html_e('Links', 'seo-fury'); ?></span>
                    </button>
                    <button type="button" class="seo-fury-tab" data-tab="speed">
                        <span class="dashicons dashicons-performance"></span>
                        <span class="seo-fury-tab-label"><?php esc_html_e('Speed', 'seo-fury'); ?></span>
                    </button>
                    <button type="button" class="seo-fury-tab" data-tab="ai_image">
                        <span class="dashicons dashicons-superhero-alt"></span>
                        <span class="seo-fury-tab-label"><?php esc_html_e('AI', 'seo-fury'); ?></span>
                    </button>
                </div>

                <!-- Content tabs -->
                <div class="seo-fury-tab-panels">
                    <?php
                    $this->basic_meta->render_basic_tab($post, $meta_data, $preview_data);
                    $this->basic_meta->render_advanced_tab($post, $meta_data);
                    $this->schema_meta->render_schema_tab($post, $meta_data);
                    ?>
                    <div id="tab-links" class="seo-fury-tab-content">
                        <?php $this->internal_links->render_tab($post); ?>
                    </div>
                    <div id="tab-speed" class="seo-fury-tab-content">
                        <?php
                        $core = SEO_Fury_Core::get_instance();
                        $ps = $core->get_page_speed();
                        if ($ps) { $ps->render_post_meta_tab($post); }
                        ?>
                    </div>
                    <div id="tab-ai_image" class="seo-fury-tab-content">
                        <!-- AI Text Section -->
                        <div class="sf-ai-section" style="margin-bottom: 16px;">
                            <h4 style="margin: 0 0 10px; font-size: 13px; font-weight: 600; display: flex; align-items: center; gap: 6px; color: var(--sf-gray-900, #1e293b);">
                                <span class="dashicons dashicons-edit-page" style="color: #6B46C1;"></span>
                                <?php esc_html_e('AI Content', 'seo-fury'); ?>
                                <span style="background: linear-gradient(135deg, #4F46E5, #7C3AED); color: #fff; font-size: 10px; padding: 2px 8px; border-radius: 10px; font-weight: 500;">PRO</span>
                            </h4>
                            <?php $this->render_ai_text_section($post); ?>
                        </div>

                        <hr style="border: none; border-top: 1px solid var(--sf-gray-200, #e2e8f0); margin: 16px 0;">

                        <!-- AI Images Section -->
                        <div class="sf-ai-section">
                            <h4 style="margin: 0 0 10px; font-size: 13px; font-weight: 600; display: flex; align-items: center; gap: 6px; color: var(--sf-gray-900, #1e293b);">
                                <span class="dashicons dashicons-format-image" style="color: #6B46C1;"></span>
                                <?php esc_html_e('AI Images', 'seo-fury'); ?>
                            </h4>
                            <?php
                            $core = SEO_Fury_Core::get_instance();
                            $ai_img = $core->get_ai_image_generator();
                            if ($ai_img) {
                                $ai_img->render_post_meta_tab($post);
                            } else {
                                echo '<p style="color:var(--sf-gray-400, #94a3b8);font-size:12px;">' . esc_html__('Available with PRO license.', 'seo-fury') . '</p>';
                            }
                            ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Hidden fields inside the metabox (inside <form>) to capture modal values on save -->
            <input type="hidden" id="sf_hidden_title" name="seo_fury_title" value="<?php echo esc_attr($meta_data['meta_title']); ?>">
            <input type="hidden" id="sf_hidden_description" name="seo_fury_description" value="<?php echo esc_attr($meta_data['meta_description']); ?>">
            <input type="hidden" id="sf_hidden_keywords" name="seo_fury_keywords" value="<?php echo esc_attr($meta_data['meta_keywords']); ?>">
            <input type="hidden" id="sf_hidden_og_title" name="seo_fury_og_title" value="<?php echo esc_attr($meta_data['og_title']); ?>">
            <input type="hidden" id="sf_hidden_og_description" name="seo_fury_og_description" value="<?php echo esc_attr($meta_data['og_description']); ?>">
            <input type="hidden" id="sf_hidden_og_image" name="seo_fury_og_image" value="<?php echo esc_attr($meta_data['og_image']); ?>">
            <input type="hidden" id="sf_hidden_og_type" name="seo_fury_og_type" value="<?php echo esc_attr($meta_data['og_type']); ?>">
            <input type="hidden" id="sf_hidden_twitter_title" name="seo_fury_twitter_title" value="<?php echo esc_attr($meta_data['twitter_title']); ?>">
            <input type="hidden" id="sf_hidden_twitter_description" name="seo_fury_twitter_description" value="<?php echo esc_attr($meta_data['twitter_description']); ?>">
            <input type="hidden" id="sf_hidden_twitter_image" name="seo_fury_twitter_image" value="<?php echo esc_attr($meta_data['twitter_image']); ?>">
            <input type="hidden" id="sf_hidden_twitter_card_type" name="seo_fury_twitter_card_type" value="<?php echo esc_attr($meta_data['twitter_card_type']); ?>">
            <input type="hidden" id="sf_hidden_fb_title" name="seo_fury_fb_title" value="<?php echo esc_attr($meta_data['fb_title']); ?>">
            <input type="hidden" id="sf_hidden_fb_description" name="seo_fury_fb_description" value="<?php echo esc_attr($meta_data['fb_description']); ?>">
            <input type="hidden" id="sf_hidden_fb_image" name="seo_fury_fb_image" value="<?php echo esc_attr($meta_data['fb_image']); ?>">
            <input type="hidden" id="sf_hidden_permalink" name="seo_fury_snippet_permalink" value="<?php echo esc_attr($meta_data['snippet_permalink'] ?: $current_url); ?>">
        </div>

<?php
        // Store modal data for rendering in admin_footer (outside of metabox/sidebar DOM)
        $this->modal_data = array(
            'meta_data' => $meta_data,
            'preview_data' => $preview_data,
            'current_url' => $current_url,
            'preview_title' => $preview_title,
            'preview_description' => $preview_description,
        );
    }

    /**
     * Render AI text generation section in the AI tab.
     */
    private function render_ai_text_section($post) {
        $core = SEO_Fury_Core::get_instance();
        $pro = $core->get_pro_features();
        $has_ai = $pro && $pro->has_feature('ai_content');

        if (!$has_ai) {
            ?>
            <div style="text-align: center; padding: 16px; background: #F5F3FF; border: 1px dashed #C4B5FD; border-radius: 8px;">
                <p style="margin: 0; font-size: 12px; color: #6D28D9;">
                    <?php esc_html_e('AI content generation requires a PRO license. Upgrade to generate articles, expand content, and rewrite text using AI.', 'seo-fury'); ?>
                </p>
            </div>
            <?php
            return;
        }
        ?>
        <div style="margin-bottom: 10px;">
            <label for="sf-ai-custom-prompt" style="font-size: 12px; font-weight: 600; display: block; margin-bottom: 4px; color: var(--sf-gray-700, #475569);">
                <?php esc_html_e('Custom Prompt (optional)', 'seo-fury'); ?>
            </label>
            <textarea id="sf-ai-custom-prompt" rows="2" style="width: 100%; font-size: 12px; border: 1px solid var(--sf-gray-300, #cbd5e1); border-radius: 6px; padding: 8px;" placeholder="<?php esc_attr_e('Enter a custom prompt or leave empty to auto-generate from post title...', 'seo-fury'); ?>"></textarea>
        </div>
        <div style="display: flex; gap: 6px; flex-wrap: wrap;">
            <button type="button" class="button sf-ai-tab-btn" data-action="content_body" title="<?php esc_attr_e('Generate a complete article from the post title', 'seo-fury'); ?>">
                <span class="dashicons dashicons-edit-page" style="font-size:14px;width:14px;height:14px;margin-top:4px;"></span>
                <?php esc_html_e('Generate', 'seo-fury'); ?>
            </button>
            <button type="button" class="button sf-ai-tab-btn" data-action="content_expand" title="<?php esc_attr_e('Add more content to the existing text', 'seo-fury'); ?>">
                <span class="dashicons dashicons-plus-alt2" style="font-size:14px;width:14px;height:14px;margin-top:4px;"></span>
                <?php esc_html_e('Expand', 'seo-fury'); ?>
            </button>
            <button type="button" class="button sf-ai-tab-btn" data-action="content_rewrite" title="<?php esc_attr_e('Rewrite and improve the existing content', 'seo-fury'); ?>">
                <span class="dashicons dashicons-controls-repeat" style="font-size:14px;width:14px;height:14px;margin-top:4px;"></span>
                <?php esc_html_e('Rewrite', 'seo-fury'); ?>
            </button>
        </div>
        <p style="margin: 8px 0 0; font-size: 11px; color: var(--sf-gray-400, #94a3b8);">
            <strong><?php esc_html_e('Generate', 'seo-fury'); ?></strong> — <?php esc_html_e('creates a new article from the post title', 'seo-fury'); ?> |
            <strong><?php esc_html_e('Expand', 'seo-fury'); ?></strong> — <?php esc_html_e('adds more content to existing text', 'seo-fury'); ?> |
            <strong><?php esc_html_e('Rewrite', 'seo-fury'); ?></strong> — <?php esc_html_e('improves and rewrites existing content', 'seo-fury'); ?>
        </p>
        <?php
    }

    /**
     * Render modals in footer for Elementor editor (bypasses screen check).
     */
    public function render_modals_in_footer_elementor()
    {
        if (!$this->modal_data) {
            return;
        }
        $this->render_modals_html();
    }

    public function render_modals_in_footer()
    {
        $screen = get_current_screen();
        if (!$screen || $screen->base !== 'post') {
            return;
        }

        // Skip in Elementor editor — handled by SEO_Fury_Elementor_Integration
        if (isset($_GET['action']) && $_GET['action'] === 'elementor') {
            return;
        }

        if (!$this->modal_data) {
            return;
        }

        $this->render_modals_html();
    }

    /**
     * Shared method that outputs the actual modal markup.
     * Called by render_modals_in_footer() and render_modals_in_footer_elementor().
     */
    private function render_modals_html()
    {
        $meta_data = $this->modal_data['meta_data'] ?? array();
        $preview_data = $this->modal_data['preview_data'] ?? array();
        $current_url = $this->modal_data['current_url'] ?? '';
        $preview_title = $this->modal_data['preview_title'] ?? '';
        $preview_description = $this->modal_data['preview_description'] ?? '';
?>
        <!-- Snippet editing modal (rendered in footer for Gutenberg compatibility) -->
        <div id="seo-fury-snippet-modal" class="seo-fury-modal" style="display: none;">
            <div class="seo-fury-modal-overlay"></div>
            <div class="seo-fury-modal-content">
                <div class="seo-fury-modal-header">
                    <h2><?php esc_html_e('Edit SEO Snippet', 'seo-fury'); ?></h2>
                    <button type="button" class="seo-fury-modal-close">
                        <span class="dashicons dashicons-no-alt"></span>
                    </button>
                </div>

                <div class="seo-fury-modal-body">
                    <div class="seo-fury-modal-tabs">
                        <button type="button" class="seo-fury-modal-tab active" data-tab="basic">
                            <span class="dashicons dashicons-admin-generic"></span>
                            <?php esc_html_e('General', 'seo-fury'); ?>
                        </button>
                        <button type="button" class="seo-fury-modal-tab" data-tab="social">
                            <span class="dashicons dashicons-share"></span>
                            <?php esc_html_e('Social', 'seo-fury'); ?>
                        </button>
                    </div>

                    <div class="seo-fury-modal-tab-panels">
                        <div class="seo-fury-modal-panel active" data-panel="basic">
                            <div class="seo-fury-modal-grid">
                                <div class="seo-fury-modal-grid-left">
                                    <div class="seo-fury-modal-preview">
                                        <h4><?php esc_html_e('Google Preview', 'seo-fury'); ?></h4>
                                        <div class="google-preview google-preview-modal">
                                            <div class="preview-url"><?php echo esc_html($meta_data['snippet_permalink'] ?: $current_url); ?></div>
                                            <div class="preview-title"><?php echo esc_html($preview_title); ?></div>
                                            <div class="preview-description"><?php echo esc_html($preview_description); ?></div>
                                        </div>
                                    </div>
                                    <div class="seo-fury-field seo-fury-modal-permalink-field">
                                        <div class="field-header">
                                            <label for="seo_fury_permalink"><?php esc_html_e('Permalink', 'seo-fury'); ?></label>
                                            <div class="char-counter">
                                                <span><span id="permalink-length">0</span> / 75</span>
                                            </div>
                                        </div>
                                        <input type="url" id="seo_fury_permalink" value="<?php echo esc_attr($meta_data['snippet_permalink'] ?: $current_url); ?>" placeholder="<?php echo esc_attr($current_url); ?>">
                                        <p class="description"><?php esc_html_e('Unique URL of this page, displayed under the post title in search results.', 'seo-fury'); ?></p>
                                    </div>
                                </div>

                                <div class="seo-fury-modal-grid-right">
                                    <div class="seo-fury-field">
                                        <div class="field-header">
                                            <label for="seo_fury_title"><?php esc_html_e('SEO Title', 'seo-fury'); ?></label>
                                            <div class="char-counter">
                                                <span><span id="title-length">0</span> / 60</span>
                                                <span class="seo-fury-pixel-counter"><span id="title-pixels">0</span> / 580px</span>
                                            </div>
                                        </div>
                                        <div class="input-with-dropdown">
                                            <input type="text" id="seo_fury_title" value="<?php echo esc_attr($meta_data['meta_title']); ?>">
                                            <button type="button" class="sf-ai-gen-btn" data-ai-type="seo_title" data-ai-target="seo_fury_title" title="<?php esc_attr_e('Generate with AI', 'seo-fury'); ?>">
                                                <span class="dashicons dashicons-superhero-alt"></span>
                                            </button>
                                            <button type="button" class="shortcode-dropdown-btn" data-target="seo_fury_title">
                                                <span class="dashicons dashicons-arrow-down-alt2"></span>
                                            </button>
                                            <div class="shortcode-dropdown-menu">
                                                <div class="shortcode-item" data-var="%sep%"><strong>%sep%</strong> <span><?php esc_html_e('Separator -, —', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%sitename%"><strong>%sitename%</strong> <span><?php esc_html_e('Site name', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%sitedesc%"><strong>%sitedesc%</strong> <span><?php esc_html_e('Site description', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%title%"><strong>%title%</strong> <span><?php esc_html_e('Post title', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%parent_title%"><strong>%parent_title%</strong> <span><?php esc_html_e('Parent page', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%seo_title%"><strong>%seo_title%</strong> <span><?php esc_html_e('SEO title', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%category%"><strong>%category%</strong> <span><?php esc_html_e('Category', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%tag%"><strong>%tag%</strong> <span><?php esc_html_e('Tag', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%term%"><strong>%term%</strong> <span><?php esc_html_e('Taxonomy term', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%date%"><strong>%date%</strong> <span><?php esc_html_e('Publish date', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%currentdate%"><strong>%currentdate%</strong> <span><?php esc_html_e('Current date', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%currentyear%"><strong>%currentyear%</strong> <span><?php esc_html_e('Current year', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%name%"><strong>%name%</strong> <span><?php esc_html_e('Author name', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%page%"><strong>%page%</strong> <span><?php esc_html_e('Page number (2 of 4)', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%pt_single%"><strong>%pt_single%</strong> <span><?php esc_html_e('Post type (singular)', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%search_query%"><strong>%search_query%</strong> <span><?php esc_html_e('Search query', 'seo-fury'); ?></span></div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="seo-fury-field">
                                        <div class="field-header">
                                            <label for="seo_fury_description"><?php esc_html_e('Meta Description', 'seo-fury'); ?></label>
                                            <div class="char-counter">
                                                <span><span id="description-length">0</span> / 160</span>
                                                <span class="seo-fury-pixel-counter"><span id="description-pixels">0</span> / 920px</span>
                                            </div>
                                        </div>
                                        <div class="input-with-dropdown">
                                            <textarea id="seo_fury_description" rows="2"><?php echo esc_textarea($meta_data['meta_description']); ?></textarea>
                                            <button type="button" class="sf-ai-gen-btn" data-ai-type="meta_description" data-ai-target="seo_fury_description" title="<?php esc_attr_e('Generate with AI', 'seo-fury'); ?>">
                                                <span class="dashicons dashicons-superhero-alt"></span>
                                            </button>
                                            <button type="button" class="shortcode-dropdown-btn" data-target="seo_fury_description">
                                                <span class="dashicons dashicons-arrow-down-alt2"></span>
                                            </button>
                                            <div class="shortcode-dropdown-menu">
                                                <div class="shortcode-item" data-var="%excerpt%"><strong>%excerpt%</strong> <span><?php esc_html_e('Post excerpt', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%excerpt_only%"><strong>%excerpt_only%</strong> <span><?php esc_html_e('Excerpt field only', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%seo_description%"><strong>%seo_description%</strong> <span><?php esc_html_e('SEO description', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%title%"><strong>%title%</strong> <span><?php esc_html_e('Post title', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%sitename%"><strong>%sitename%</strong> <span><?php esc_html_e('Site name', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%sitedesc%"><strong>%sitedesc%</strong> <span><?php esc_html_e('Site description', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%category%"><strong>%category%</strong> <span><?php esc_html_e('Category', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%term_description%"><strong>%term_description%</strong> <span><?php esc_html_e('Term description', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%date%"><strong>%date%</strong> <span><?php esc_html_e('Publish date', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%name%"><strong>%name%</strong> <span><?php esc_html_e('Author name', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%user_description%"><strong>%user_description%</strong> <span><?php esc_html_e('Author bio', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%wc_shortdesc%"><strong>%wc_shortdesc%</strong> <span><?php esc_html_e('Product short description', 'seo-fury'); ?></span></div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="seo-fury-field">
                                        <label for="seo_fury_keywords"><?php esc_html_e('Meta Keywords', 'seo-fury'); ?></label>
                                        <div class="input-with-dropdown">
                                            <input type="text" id="seo_fury_keywords" value="<?php echo esc_attr($meta_data['meta_keywords']); ?>">
                                            <button type="button" class="shortcode-dropdown-btn" data-target="seo_fury_keywords">
                                                <span class="dashicons dashicons-arrow-down-alt2"></span>
                                            </button>
                                            <div class="shortcode-dropdown-menu">
                                                <div class="shortcode-item" data-var="%focuskw%"><strong>%focuskw%</strong> <span><?php esc_html_e('Focus keyword', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%keywords%"><strong>%keywords%</strong> <span><?php esc_html_e('Keywords', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%tags%"><strong>%tags%</strong> <span><?php esc_html_e('Tags', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%category%"><strong>%category%</strong> <span><?php esc_html_e('Category', 'seo-fury'); ?></span></div>
                                                <div class="shortcode-item" data-var="%categories%"><strong>%categories%</strong> <span><?php esc_html_e('All categories', 'seo-fury'); ?></span></div>
                                            </div>
                                        </div>
                                        <p class="description"><?php esc_html_e('Separate keywords with commas', 'seo-fury'); ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="seo-fury-modal-panel" data-panel="social">
                            <div class="seo-fury-modal-social-grid">
                                <div class="seo-fury-modal-social-left">
                                    <div class="seo-fury-section seo-fury-social-settings">
                                        <h4><?php esc_html_e('Social Settings', 'seo-fury'); ?></h4>
                                        <div class="seo-fury-social-settings-tabs">
                                            <button type="button" class="seo-fury-social-settings-tab active" data-settings-tab="all"><?php esc_html_e('All Networks', 'seo-fury'); ?></button>
                                            <button type="button" class="seo-fury-social-settings-tab" data-settings-tab="facebook"><?php esc_html_e('Facebook', 'seo-fury'); ?></button>
                                            <button type="button" class="seo-fury-social-settings-tab" data-settings-tab="twitter"><?php esc_html_e('Twitter', 'seo-fury'); ?></button>
                                        </div>

                                        <div class="seo-fury-social-settings-panels">
                                            <div class="seo-fury-social-settings-panel active" data-settings-panel="all">
                                                <div class="seo-fury-fields-grid">
                                                    <div class="seo-fury-field">
                                                        <label for="seo_fury_social_title_modal"><?php esc_html_e('Title', 'seo-fury'); ?></label>
                                                        <input type="text" id="seo_fury_social_title_modal" class="seo-fury-social-all-title" placeholder="<?php echo esc_attr__('Title for all networks', 'seo-fury'); ?>">
                                                    </div>
                                                    <div class="seo-fury-field">
                                                        <label for="seo_fury_social_description_modal"><?php esc_html_e('Description', 'seo-fury'); ?></label>
                                                        <textarea id="seo_fury_social_description_modal" class="seo-fury-social-all-description" rows="3" placeholder="<?php echo esc_attr__('Description for all networks', 'seo-fury'); ?>"></textarea>
                                                    </div>
                                                    <div class="seo-fury-field">
                                                        <label for="seo_fury_social_image_modal"><?php esc_html_e('Image', 'seo-fury'); ?></label>
                                                        <input type="url" id="seo_fury_social_image_modal" class="seo-fury-social-all-image" placeholder="https://">
                                                        <button type="button" class="button sf-upload-image" data-target="seo_fury_social_image_modal">
                                                            <span class="dashicons dashicons-format-image" style="vertical-align: middle;"></span>
                                                            <?php esc_html_e('Choose Image', 'seo-fury'); ?>
                                                        </button>
                                                    </div>
                                                </div>
                                                <p class="description"><?php esc_html_e('Values apply to Facebook and Twitter', 'seo-fury'); ?></p>
                                            </div>

                                            <div class="seo-fury-social-settings-panel" data-settings-panel="facebook">
                                                <div class="seo-fury-fields-grid">
                                                    <div class="seo-fury-field">
                                                        <label for="seo_fury_fb_title"><?php esc_html_e('Facebook Title', 'seo-fury'); ?></label>
                                                        <div class="input-with-dropdown">
                                                            <input type="text" id="seo_fury_fb_title" value="<?php echo esc_attr($meta_data['fb_title']); ?>">
                                                            <button type="button" class="sf-ai-gen-btn" data-ai-type="og_title" data-ai-target="seo_fury_fb_title" title="<?php esc_attr_e('Generate with AI', 'seo-fury'); ?>">
                                                                <span class="dashicons dashicons-superhero-alt"></span>
                                                            </button>
                                                            <button type="button" class="shortcode-dropdown-btn" data-target="seo_fury_fb_title">
                                                                <span class="dashicons dashicons-arrow-down-alt2"></span>
                                                            </button>
                                                            <div class="shortcode-dropdown-menu">
                                                                <div class="shortcode-item" data-var="%title%"><strong>%title%</strong> <span><?php esc_html_e('Post title', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%seo_title%"><strong>%seo_title%</strong> <span><?php esc_html_e('SEO title', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%sitename%"><strong>%sitename%</strong> <span><?php esc_html_e('Site name', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%sep%"><strong>%sep%</strong> <span><?php esc_html_e('Separator —', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%category%"><strong>%category%</strong> <span><?php esc_html_e('Category', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%date%"><strong>%date%</strong> <span><?php esc_html_e('Publish date', 'seo-fury'); ?></span></div>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div class="seo-fury-field">
                                                        <label for="seo_fury_fb_image"><?php esc_html_e('Facebook Image', 'seo-fury'); ?></label>
                                                        <input type="url" id="seo_fury_fb_image" value="<?php echo esc_attr($meta_data['fb_image']); ?>">
                                                        <button type="button" class="button sf-upload-image" data-target="seo_fury_fb_image">
                                                            <span class="dashicons dashicons-format-image" style="vertical-align: middle;"></span>
                                                            <?php esc_html_e('Choose Image', 'seo-fury'); ?>
                                                        </button>
                                                        <button type="button" class="button sf-remove-image-button" data-target="seo_fury_fb_image"
                                                            style="<?php echo esc_attr( $meta_data['fb_image'] ? '' : 'display:none;' ); ?>margin-left: 5px;">
                                                            <span class="dashicons dashicons-no" style="vertical-align: middle;"></span>
                                                            <?php esc_html_e('Remove', 'seo-fury'); ?>
                                                        </button>
                                                    </div>

                                                    <div class="seo-fury-field">
                                                        <label for="seo_fury_fb_description"><?php esc_html_e('Facebook Description', 'seo-fury'); ?></label>
                                                        <div class="input-with-dropdown">
                                                            <textarea id="seo_fury_fb_description" rows="3"><?php echo esc_textarea($meta_data['fb_description']); ?></textarea>
                                                            <button type="button" class="sf-ai-gen-btn" data-ai-type="og_description" data-ai-target="seo_fury_fb_description" title="<?php esc_attr_e('Generate with AI', 'seo-fury'); ?>">
                                                                <span class="dashicons dashicons-superhero-alt"></span>
                                                            </button>
                                                            <button type="button" class="shortcode-dropdown-btn" data-target="seo_fury_fb_description">
                                                                <span class="dashicons dashicons-arrow-down-alt2"></span>
                                                            </button>
                                                            <div class="shortcode-dropdown-menu">
                                                                <div class="shortcode-item" data-var="%excerpt%"><strong>%excerpt%</strong> <span><?php esc_html_e('Post excerpt', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%seo_description%"><strong>%seo_description%</strong> <span><?php esc_html_e('SEO description', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%title%"><strong>%title%</strong> <span><?php esc_html_e('Post title', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%sitedesc%"><strong>%sitedesc%</strong> <span><?php esc_html_e('Site description', 'seo-fury'); ?></span></div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="seo-fury-social-settings-panel" data-settings-panel="twitter">
                                                <div class="seo-fury-fields-grid">
                                                    <div class="seo-fury-field">
                                                        <label for="seo_fury_twitter_title"><?php esc_html_e('Twitter Title', 'seo-fury'); ?></label>
                                                        <div class="input-with-dropdown">
                                                            <input type="text" id="seo_fury_twitter_title" value="<?php echo esc_attr($meta_data['twitter_title']); ?>">
                                                            <button type="button" class="sf-ai-gen-btn" data-ai-type="twitter_title" data-ai-target="seo_fury_twitter_title" title="<?php esc_attr_e('Generate with AI', 'seo-fury'); ?>">
                                                                <span class="dashicons dashicons-superhero-alt"></span>
                                                            </button>
                                                            <button type="button" class="shortcode-dropdown-btn" data-target="seo_fury_twitter_title">
                                                                <span class="dashicons dashicons-arrow-down-alt2"></span>
                                                            </button>
                                                            <div class="shortcode-dropdown-menu">
                                                                <div class="shortcode-item" data-var="%title%"><strong>%title%</strong> <span><?php esc_html_e('Post title', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%seo_title%"><strong>%seo_title%</strong> <span><?php esc_html_e('SEO title', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%sitename%"><strong>%sitename%</strong> <span><?php esc_html_e('Site name', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%sep%"><strong>%sep%</strong> <span><?php esc_html_e('Separator —', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%category%"><strong>%category%</strong> <span><?php esc_html_e('Category', 'seo-fury'); ?></span></div>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div class="seo-fury-field">
                                                        <label for="seo_fury_twitter_card_type"><?php esc_html_e('Twitter Card Type', 'seo-fury'); ?></label>
                                                        <select id="seo_fury_twitter_card_type">
                                                            <option value="summary" <?php selected($meta_data['twitter_card_type'], 'summary'); ?>><?php esc_html_e('Summary', 'seo-fury'); ?></option>
                                                            <option value="summary_large_image" <?php selected($meta_data['twitter_card_type'], 'summary_large_image'); ?>><?php esc_html_e('Summary Large Image', 'seo-fury'); ?></option>
                                                        </select>
                                                    </div>

                                                    <div class="seo-fury-field">
                                                        <label for="seo_fury_twitter_description"><?php esc_html_e('Twitter Description', 'seo-fury'); ?></label>
                                                        <div class="input-with-dropdown">
                                                            <textarea id="seo_fury_twitter_description" rows="3"><?php echo esc_textarea($meta_data['twitter_description']); ?></textarea>
                                                            <button type="button" class="sf-ai-gen-btn" data-ai-type="twitter_description" data-ai-target="seo_fury_twitter_description" title="<?php esc_attr_e('Generate with AI', 'seo-fury'); ?>">
                                                                <span class="dashicons dashicons-superhero-alt"></span>
                                                            </button>
                                                            <button type="button" class="shortcode-dropdown-btn" data-target="seo_fury_twitter_description">
                                                                <span class="dashicons dashicons-arrow-down-alt2"></span>
                                                            </button>
                                                            <div class="shortcode-dropdown-menu">
                                                                <div class="shortcode-item" data-var="%excerpt%"><strong>%excerpt%</strong> <span><?php esc_html_e('Post excerpt', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%seo_description%"><strong>%seo_description%</strong> <span><?php esc_html_e('SEO description', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%title%"><strong>%title%</strong> <span><?php esc_html_e('Post title', 'seo-fury'); ?></span></div>
                                                                <div class="shortcode-item" data-var="%sitedesc%"><strong>%sitedesc%</strong> <span><?php esc_html_e('Site description', 'seo-fury'); ?></span></div>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div class="seo-fury-field">
                                                        <label for="seo_fury_twitter_image"><?php esc_html_e('Twitter Image', 'seo-fury'); ?></label>
                                                        <input type="url" id="seo_fury_twitter_image" value="<?php echo esc_attr($meta_data['twitter_image']); ?>">
                                                        <button type="button" class="button sf-upload-image" data-target="seo_fury_twitter_image">
                                                            <span class="dashicons dashicons-format-image" style="vertical-align: middle;"></span>
                                                            <?php esc_html_e('Choose Image', 'seo-fury'); ?>
                                                        </button>
                                                        <button type="button" class="button sf-remove-image-button" data-target="seo_fury_twitter_image"
                                                            style="<?php echo esc_attr( $meta_data['twitter_image'] ? '' : 'display:none;' ); ?>margin-left: 5px;">
                                                            <span class="dashicons dashicons-no" style="vertical-align: middle;"></span>
                                                            <?php esc_html_e('Remove', 'seo-fury'); ?>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="seo-fury-modal-social-right">
                                    <div class="seo-fury-section">
                                        <h4><?php esc_html_e('Social Preview', 'seo-fury'); ?></h4>
                                        <div class="seo-fury-social-preview-tabs">
                                            <button type="button" class="seo-fury-social-tab active" data-social-tab="facebook">
                                                <span class="dashicons dashicons-facebook"></span>
                                                <?php esc_html_e('Facebook', 'seo-fury'); ?>
                                            </button>
                                            <button type="button" class="seo-fury-social-tab" data-social-tab="twitter">
                                                <span class="dashicons dashicons-twitter"></span>
                                                <?php esc_html_e('Twitter', 'seo-fury'); ?>
                                            </button>
                                        </div>
                                        <div class="seo-fury-social-preview-panels">
                                            <div class="seo-fury-social-panel active" data-social-panel="facebook">
                                                <div class="social-post-card facebook-card">
                                                    <div class="social-post-header">
                                                        <div class="social-avatar"></div>
                                                        <div class="social-post-meta">
                                                            <strong class="social-username"><?php esc_html_e('Facebook user', 'seo-fury'); ?></strong>
                                                            <div class="social-time"><?php esc_html_e('2 hours ago', 'seo-fury'); ?></div>
                                                        </div>
                                                    </div>
                                                    <?php if ($preview_data['fb_preview_image']): ?>
                                                        <div class="social-post-image">
                                                            <img src="<?php echo esc_url($preview_data['fb_preview_image']); ?>" alt="<?php echo esc_attr__('FB Preview', 'seo-fury'); ?>">
                                                        </div>
                                                    <?php endif; ?>
                                                    <div class="social-post-footer facebook-footer">
                                                        <div class="social-link-domain"><?php echo esc_html(strtoupper(wp_parse_url($preview_data['current_url'], PHP_URL_HOST))); ?></div>
                                                        <div class="social-link-title fb-title"><?php echo esc_html($preview_data['fb_preview_title']); ?></div>
                                                        <div class="social-link-description fb-description"><?php echo esc_html($preview_data['fb_preview_desc']); ?></div>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="seo-fury-social-panel" data-social-panel="twitter">
                                                <div class="social-post-card twitter-card">
                                                    <div class="social-post-header">
                                                        <div class="social-avatar"></div>
                                                        <div class="social-post-meta">
                                                            <strong class="social-username"><?php esc_html_e('Twitter user', 'seo-fury'); ?></strong>
                                                            <div class="social-handle">@username · <?php esc_html_e('2 hours', 'seo-fury'); ?></div>
                                                        </div>
                                                    </div>
                                                    <div class="social-post-text"><?php esc_html_e('Post with a link!', 'seo-fury'); ?></div>
                                                    <?php if ($preview_data['tw_preview_image']): ?>
                                                        <div class="social-post-image">
                                                            <img src="<?php echo esc_url($preview_data['tw_preview_image']); ?>" alt="<?php echo esc_attr__('Twitter Preview', 'seo-fury'); ?>">
                                                        </div>
                                                    <?php endif; ?>
                                                    <div class="social-post-footer twitter-footer">
                                                        <div class="social-link-title tw-title"><?php echo esc_html($preview_data['tw_preview_title']); ?></div>
                                                        <div class="social-link-description tw-description"><?php echo esc_html($preview_data['tw_preview_desc']); ?></div>
                                                        <div class="social-link-domain"><?php echo esc_html(wp_parse_url($preview_data['current_url'], PHP_URL_HOST)); ?></div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="seo-fury-modal-footer">
                    <button type="button" class="button button-primary seo-fury-modal-save"><?php esc_html_e('Save Changes', 'seo-fury'); ?></button>
                    <button type="button" class="button seo-fury-modal-close"><?php esc_html_e('Cancel', 'seo-fury'); ?></button>
                </div>
            </div>
        </div>
<?php
    }



    public function save_seo_meta($post_id, $post)
    {
        if (!isset($_POST['seo_fury_post_meta_nonce_field']) || !wp_verify_nonce($_POST['seo_fury_post_meta_nonce_field'], 'seo_fury_post_meta_nonce')) {
            return;
        }

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        if (isset($_POST['seo_fury_title'])) {
            update_post_meta($post_id, '_seo_fury_title', sanitize_text_field(wp_unslash($_POST['seo_fury_title'])));
        }

        if (isset($_POST['seo_fury_description'])) {
            update_post_meta($post_id, '_seo_fury_description', sanitize_textarea_field(wp_unslash($_POST['seo_fury_description'])));
        }

        if (isset($_POST['seo_fury_keywords'])) {
            update_post_meta($post_id, '_seo_fury_keywords', sanitize_text_field(wp_unslash($_POST['seo_fury_keywords'])));
        }

        if (isset($_POST['seo_fury_focus_keyword'])) {
            update_post_meta($post_id, '_seo_fury_focus_keyword', sanitize_text_field(wp_unslash($_POST['seo_fury_focus_keyword'])));
        }

        if (isset($_POST['seo_fury_secondary_keywords'])) {
            $secondary = sanitize_text_field(wp_unslash($_POST['seo_fury_secondary_keywords']));
            // Clean: trim each keyword, remove empties, limit to 10
            $kw_array = array_filter(array_map('trim', explode(',', $secondary)));
            $kw_array = array_slice($kw_array, 0, 10);
            update_post_meta($post_id, '_seo_fury_secondary_keywords', implode(', ', $kw_array));
        }

        if (isset($_POST['seo_fury_snippet_permalink'])) {
            update_post_meta($post_id, '_seo_fury_snippet_permalink', esc_url_raw(wp_unslash($_POST['seo_fury_snippet_permalink'])));
        }

        $this->basic_meta->save_meta($post_id);
        $this->social_meta->save_meta($post_id);
        $this->schema_meta->save_meta($post_id);
    }


    public function output_seo_meta_tags()
    {
        if (!is_singular()) {
            return;
        }

        global $post;
        if (!$post) {
            return;
        }

        $brand = function_exists('seo_fury_get_brand_name') ? seo_fury_get_brand_name() : 'SEO Fury';
        echo "\n<!-- " . esc_html($brand) . " -->\n";

        $meta_title = get_post_meta($post->ID, '_seo_fury_title', true);
        if (!$meta_title) {
            $meta_title = get_option('seo_fury_title_template_' . $post->post_type, '');
        }
        if ($meta_title) {
            echo '<meta name="title" content="' . esc_attr($this->parse_shortcodes($meta_title, $post)) . '">' . "\n";
        }

        $meta_description = get_post_meta($post->ID, '_seo_fury_description', true);
        if (!$meta_description) {
            $meta_description = get_option('seo_fury_description_template_' . $post->post_type, '');
        }
        // Auto-generate description from content as fallback
        if (!$meta_description && !empty($post->post_content)) {
            $meta_description = wp_trim_words(wp_strip_all_tags(strip_shortcodes($post->post_content)), 30, '...');
        }
        if ($meta_description) {
            echo '<meta name="description" content="' . esc_attr($this->parse_shortcodes($meta_description, $post)) . '">' . "\n";
        }

        $meta_keywords = get_post_meta($post->ID, '_seo_fury_keywords', true);
        if ($meta_keywords) {
            echo '<meta name="keywords" content="' . esc_attr($this->parse_shortcodes($meta_keywords, $post)) . '">' . "\n";
        }

        $this->basic_meta->output_meta_tags($post);
        $this->social_meta->output_meta_tags($post, array($this, 'parse_shortcodes'));

        $this->schema_meta->output_schema($post);

        echo "<!-- /" . esc_html($brand) . " -->\n";
    }
}
