<?php
/**
 * Tam Rank™ Content Tab
 *
 * Rendert de Content tab in de meta box met score overzicht,
 * aanbevelingen en gedetailleerde checks.
 *
 * @package TamRank
 * @subpackage Content
 * @since 6.2.2
 */

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

class TamRank_Content_Tab
{

    /**
     * Singleton instance
     *
     * @var TamRank_Content_Tab
     */
    private static $instance = null;

    /**
     * Content Analyzer instance
     *
     * @var TamRank_Content_Analyzer
     */
    private $analyzer;

    /**
     * Constructor
     */
    private function __construct()
    {
        // Laad de analyzer klasse
        require_once dirname(__FILE__) . '/class-tamrank-content-analyzer.php';
        $this->analyzer = new TamRank_Content_Analyzer();

        // Registreer scripts en styles
        add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));

        // AJAX handlers — content analysis stays in FREE. The three AI internal-link
        // handlers (generate / poll / save) moved to tam-rank-pro (cluster-7b strip).
        add_action('wp_ajax_tamrank_analyze_content', array($this, 'ajax_analyze_content'));
    }

    /**
     * Get singleton instance
     *
     * @return TamRank_Content_Tab
     */
    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Enqueue scripts en styles voor de Content tab
     *
     * @param string $hook Huidige admin pagina
     */
    public function enqueue_assets($hook)
    {
        if ($hook !== 'post.php' && $hook !== 'post-new.php') {
            return;
        }

        // CSS
        wp_enqueue_style(
            'tamrank-content-tab',
            TAM_RANK_PLUGIN_URL . 'assets/css/content-tab.css',
            array('tamrank-variables'),
            TAM_RANK_VERSION . '.3'
        );

        // JavaScript
        wp_enqueue_script(
            'tamrank-content-tab',
            TAM_RANK_PLUGIN_URL . 'assets/js/content-tab.js',
            array('jquery', 'tam-rank-toast'),
            TAM_RANK_VERSION . '.7',
            true
        );

        // Cluster id is used for the localized data below. The cluster graph
        // itself (D3 + graph engine + its CSS) is a PRO feature: PRO builds the
        // cluster data and enqueues the renderer when it hooks
        // tamrank_content_ai_links_panel. FREE no longer ships or orchestrates it.
        $post_cluster_id = get_post_meta(get_the_ID(), '_tamrank_cluster_id', true);

        // Localize script met benodigde data
        wp_localize_script('tamrank-content-tab', 'tamRankContent', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('tamrank_content_nonce'),
            'postId' => get_the_ID(),
            'postTitle' => get_the_title(),
            'clusterName' => get_post_meta(get_the_ID(), '_tamrank_cluster_name', true) ?: '',
            'clusterId' => $post_cluster_id ?: '',
            'strings' => array(
                'analyzing' => __('Analyzing...', 'tam-rank'),
                'analyzeButton' => __('Analyze Content', 'tam-rank'),
                'reanalyze' => __('Re-analyze', 'tam-rank'),
                'noContent' => __('First add content to the page', 'tam-rank'),
                'excellent' => __('Excellent', 'tam-rank'),
                'good' => __('Good', 'tam-rank'),
                'attention' => __('Attention', 'tam-rank'),
                'improve' => __('Improve', 'tam-rank'),
                'critical' => __('Critical', 'tam-rank'),
                'passed' => __('Passed', 'tam-rank'),
                'warning' => __('Improvement', 'tam-rank'),
                'error' => __('Critical', 'tam-rank'),
                'improvements' => __('improvement(s)', 'tam-rank'),
                'criticalIssues' => __('critical issue(s)', 'tam-rank'),

                // Analysis Results
                'noHeadings' => tamrank__('no_headings_found', 'No headings found'),
                'noImages' => tamrank__('no_images_found', 'No images found'),
                'noInternalLinks' => tamrank__('no_internal_links_found', 'No internal links found'),
                'noExternalLinks' => tamrank__('no_external_links_found', 'No external links found'),
                'noIssuesGoodJob' => tamrank__('no_issues_good_job', 'Great! No issues found. Your content is well optimized.'),
                'noAltText' => tamrank__('no_alt_text', 'No alt text'),
                'sizeUnknown' => tamrank__('size_unknown', 'Unknown'),
                'noWebP' => tamrank__('no_webp', 'No WebP'),
                'noLazy' => tamrank__('no_lazy', 'No lazy'),
                'noAnchorText' => tamrank__('no_anchor_text', 'No anchor text'),
                'internalLinksLabel' => tamrank__('internal_links_label', 'Internal links'),
                'externalLinksLabel' => tamrank__('external_links_label', 'External links'),
                'analysisFailed' => tamrank__('analysis_failed', 'Analysis failed'),
                'analysisError' => tamrank__('analysis_error', 'An error occurred during analysis'),
                'statusOk' => tamrank__('status_ok', 'OK'),
                'statusWarning' => tamrank__('status_warning', 'Warning'),
                'statusError' => tamrank__('status_error', 'Error'),
                'statusUnknown' => tamrank__('status_unknown', 'Unknown'),
                'allChecks' => tamrank__('All checks', 'All checks'),
                'passed' => tamrank__('passed', 'passed'),
                // Wave 3 additions
                'words' => tamrank__('words', 'words'),
                'images_count_label' => tamrank__('images_count_label', 'Images (%d)'),
                'critical_issue_singular' => tamrank__('critical_issue_singular', 'Critical issue'),
                'critical_issues_plural' => tamrank__('critical_issues_plural', 'Critical issues'),
                'improvement_singular' => tamrank__('improvement_singular', 'Improvement point'),
                'improvement_plural' => tamrank__('improvement_plural', 'Improvement points'),
            )
        ));
    }

    /**
     * AJAX handler voor content analyse
     */
    public function ajax_analyze_content()
    {
        // Controleer nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'tamrank_content_nonce')) {
            wp_send_json_error(array('message' => tamrank__('error_security_token', 'Invalid security token. Please refresh the page.'), 'code' => 'nonce_invalid'));
        }

        // Controleer post ID en rechten
        $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' => tamrank__('error_permission_denied', 'You do not have permission for this action.'), 'code' => 'permission_denied'));
        }

        // Haal content op - wp_unslash verwijdert escaping, wp_kses_post stript onveilige
        // markup (script/iframe/event-handlers) voordat de analyzer the_content/do_shortcode
        // draait. wp_kses_post laat tekst, koppen, links, images en shortcode-tekst intact,
        // dus de SEO-score blijft gelijk; alleen niet-toegestane HTML wordt verwijderd.
        // PHP 8.1+ null-safe: zorg dat content en focus_keyword altijd strings zijn.
        $content = isset($_POST['content']) ? (string) wp_kses_post(wp_unslash($_POST['content'])) : '';
        $focus_keyword = isset($_POST['focus_keyword']) ? sanitize_text_field((string) wp_unslash($_POST['focus_keyword'])) : '';

        // Altijd proberen de post content te gebruiken als bron van waarheid
        // Dit werkt beter omdat we daar de originele shortcodes/block comments hebben
        $post = get_post($post_id);
        if ($post && !empty($post->post_content)) {
            // PHP 8.1+ null-safe: cast naar string
            $post_content = (string) $post->post_content;

            // Check welk type content we hebben
            $has_divi = strpos($post_content, '[et_pb_') !== false;
            $has_wpbakery = strpos($post_content, '[vc_') !== false;
            $has_gutenberg = strpos($post_content, '<!-- wp:') !== false;
            $has_elementor = strpos($post_content, 'data-elementor') !== false || strpos($post_content, 'elementor-element') !== false;

            // Als de post page builder content bevat, gebruik de post content als primaire bron
            // De analyzer zal de shortcodes/blocks parsen voor images
            if ($has_divi || $has_wpbakery || $has_gutenberg) {
                // Geef de ruwe post content mee - analyzer pakt hier de shortcodes/blocks uit
                $content = $post_content;
            } elseif ($has_elementor) {
                // Voor Elementor: combineer post content met JS content voor maximale detectie
                // Elementor slaat data op in post_content maar ook in _elementor_data meta
                $elementor_data = get_post_meta($post_id, '_elementor_data', true);
                if (!empty($elementor_data)) {
                    // Elementor data is JSON - extraheer image IDs
                    $content = $post_content . ' ' . $this->extract_elementor_images_from_data($elementor_data);
                } else {
                    $content = $post_content;
                }
            } elseif ($content !== '' && strpos($content, '<img') === false && strpos($post_content, '<img') !== false) {
                // Content van JS bevat geen images maar post_content wel - gebruik post_content
                $content = $post_content;
            }
        }

        // Een expliciete heranalyse mag de vijf-minutenrem op de paginafetch
        // overslaan: wie zelf op de knop drukt vraagt om een verse meting. De
        // automatische heranalyse na een typepauze stuurt dit nooit mee, en dat
        // is precies de reeks die geen reeks paginarenders mag worden.
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- de nonce is bovenaan deze methode al geverifieerd.
        $force_fetch = isset($_POST['force_fetch']) && '1' === sanitize_text_field(wp_unslash($_POST['force_fetch']));
        $this->analyzer->set_force_page_fetch($force_fetch);

        // Voer analyse uit
        $result = $this->analyzer->analyze($content, $focus_keyword, $post_id);

        wp_send_json_success($result);
    }

    /**
     * AI Internal Links (generate / poll / save handlers + candidate gathering)
     * moved to tam-rank-pro (TamRank_Pro_Content_Links) during the cluster-7b
     * strip. FREE keeps the content-analysis panels, the accordion shell and the
     * PRO upsell; PRO renders the working panel via the
     * `tamrank_content_ai_links_panel` action.
     */
    /**
     * Render de Content tab content
     *
     * @param WP_Post $post Het huidige post object
     */
    public function render($post)
    {
        // Haal focus zoekwoord op
        $focus_keyword = get_post_meta($post->ID, '_tam_rank_focus_keyword', true);

        // Initiële analyse (server-side)
        // We gebruiken de ruwe post_content - de analyzer zal shortcodes renderen indien nodig
        // PHP 8.1+ null-safe: zorg dat content altijd een string is
        $content = isset($post->post_content) ? (string) $post->post_content : '';

        // Voor Divi/page builders: haal ook de gerenderde content op voor betere image detectie
        // Dit zorgt ervoor dat [et_pb_image] shortcodes worden omgezet naar <img> tags
        if ($content !== '' && (strpos($content, '[et_pb_') !== false || strpos($content, '[vc_') !== false)) {
            // Render de content via the_content filter om shortcodes te verwerken
            $rendered_content = apply_filters('the_content', $content); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- applying WordPress core 'the_content' filter, not a custom plugin hook
            // Gebruik de gerenderde content als die img tags bevat
            if (strpos($rendered_content, '<img') !== false) {
                $content = $rendered_content;
            }
        }

        $initial_analysis = $this->analyzer->analyze($content, $focus_keyword, $post->ID);
        $score = $initial_analysis['score'];
        $score_color = $this->get_score_color($score);
        ?>

        <div class="tam-content-tab" id="tam-content-tab">
            <!-- Laad indicator -->
            <div id="content-loading" class="tam-content-loading"
                style="display: none; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(255,255,255,0.9); display: none; flex-direction: column; align-items: center; justify-content: center; z-index: 100;">
                <div class="tam-loading-spinner"
                    style="width: 32px; height: 32px; border: 3px solid var(--tr-color-slate-200); border-top-color: var(--tr-color-primary); border-radius: 50%; animation: tam-spin 0.8s linear infinite;">
                </div>
                <span style="margin-top: 12px; font-size: 13px; color: var(--tr-color-slate-600);"><?php esc_html_e('Analyzing content...', 'tam-rank'); ?></span>
            </div>

            <!-- Score Overzicht -->
            <?php
            // SVG Circle berekeningen
            $radius = 42;
            $circumference = 2 * M_PI * $radius;
            $dashoffset = $circumference - ($score / 100) * $circumference;
            ?>
            <div class="tam-content-score-section">
                <div class="tam-content-score-card">
                    <div class="tam-content-score-main">
                        <!-- SVG Cirkel Score -->
                        <div class="tam-score-circle-container" id="content-score-circle">
                            <svg class="tam-score-circle-svg" viewBox="0 0 100 100">
                                <circle class="tam-score-circle-bg" cx="50" cy="50" r="<?php echo esc_attr($radius); ?>" />
                                <circle class="tam-score-circle-progress" id="content-score-progress" cx="50" cy="50"
                                    r="<?php echo esc_attr($radius); ?>" stroke="<?php echo esc_attr($score_color); ?>"
                                    stroke-dasharray="<?php echo esc_attr($circumference); ?>"
                                    stroke-dashoffset="<?php echo esc_attr($dashoffset); ?>" />
                            </svg>
                            <div class="tam-score-circle-text">
                                <span class="tam-score-circle-value"
                                    id="content-score-value"><?php echo intval($score); ?></span>
                                <span class="tam-score-circle-max">/ 100</span>
                            </div>
                        </div>

                        <!-- Score Info -->
                        <div class="tam-content-score-info">
                            <div class="tam-content-score-label" id="content-score-label">
                                <?php echo esc_html($this->get_score_label($score)); ?>
                            </div>
                            <div class="tam-content-score-summary" id="content-score-summary">
                                <?php
                                $has_issues = $initial_analysis['warnings_count'] > 0 || $initial_analysis['errors_count'] > 0;
                                $issues_style = $has_issues ? '' : 'display: none;';
                                $all_good_style = $has_issues ? 'display: none;' : '';
                                ?>
                                <div id="content-status-issues" style="<?php echo esc_attr($issues_style); ?>">
                                    <span class="tam-content-criticals">
                                        <?php echo wp_kses($this->render_inline_icon('error'), tam_rank_kses_svg()); ?>
                                        <span
                                            id="content-criticals-count"><?php echo intval($initial_analysis['errors_count']); ?></span>
                                        <?php esc_html_e('critical issue(s)', 'tam-rank'); ?>
                                    </span>
                                    <span class="tam-content-improvements">
                                        <?php echo wp_kses($this->render_inline_icon('warning'), tam_rank_kses_svg()); ?>
                                        <span
                                            id="content-improvements-count"><?php echo intval($initial_analysis['warnings_count']); ?></span>
                                        <?php esc_html_e('improvement(s)', 'tam-rank'); ?>
                                    </span>
                                </div>
                                <div id="content-status-all-good" class="tam-content-all-good"
                                    style="<?php echo esc_attr($all_good_style); ?>">
                                    <?php echo wp_kses($this->render_inline_icon('check-circle'), tam_rank_kses_svg()); ?>
                                    <span><?php esc_html_e('All good! No issues found.', 'tam-rank'); ?></span>
                                </div>
                            </div>
                        </div>

                        <!-- Opnieuw analyseren knop -->
                        <div class="tam-content-reanalyze-wrapper">
                            <button type="button" id="content-reanalyze-btn" class="tr-btn tr-btn--secondary tr-btn--sm">
                                <?php echo wp_kses($this->render_inline_icon('refresh'), tam_rank_kses_svg()); ?>
                                <span><?php esc_html_e('Re-analyze', 'tam-rank'); ?></span>
                            </button>
                            <span class="tam-content-reanalyze-hint"><?php echo esc_html(tamrank__('Re-analyze after changes', 'Re-analyze after changes')); ?></span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Belangrijkste Aanbevelingen -->
            <div class="tam-content-top-issues" id="content-top-issues">
                <div class="tam-content-issues-list" id="content-issues-list">
                    <?php $this->render_top_issues($initial_analysis['top_issues']); ?>
                </div>
            </div>

            <!-- Alle Checks Accordion -->
            <div class="tam-content-accordion">
                <button type="button" class="tam-content-accordion-header" data-target="content-all-checks">
                    <?php echo wp_kses($this->render_inline_icon('checklist'), tam_rank_kses_svg()); ?>
                    <span><?php echo esc_html(tamrank__('All checks', 'All checks')); ?></span>
                    <span class="tam-content-accordion-count" id="content-checks-count">
                        <?php echo intval($initial_analysis['passed_count']); ?>/<?php echo intval($initial_analysis['total_checks']); ?>
                        <?php echo esc_html(tamrank__('passed', 'passed')); ?>
                    </span>
                    <?php echo wp_kses($this->render_inline_icon('chevron-down'), tam_rank_kses_svg()); ?>
                </button>
                <div class="tam-content-accordion-content" id="content-all-checks"
                    style="display: none; padding: 16px; border-top: 1px solid #e2e8f0;">
                    <?php $this->render_all_checks($initial_analysis['categories']); ?>
                </div>
            </div>

            <!-- Analyse Details Accordion -->
            <div class="tam-content-accordion">
                <button type="button" class="tam-content-accordion-header" data-target="content-analysis-details">
                    <?php echo wp_kses($this->render_inline_icon('info'), tam_rank_kses_svg()); ?>
                    <span><?php echo esc_html(tamrank__('Analysis details', 'Analysis details')); ?></span>
                    <?php echo wp_kses($this->render_inline_icon('chevron-down'), tam_rank_kses_svg()); ?>
                </button>
                <div class="tam-content-accordion-content" id="content-analysis-details"
                    style="display: none;">
                    <?php $this->render_analysis_details($initial_analysis['details']); ?>
                </div>
            </div>

            <!-- AI Internal Linking Suggester (working panel + AJAX moved to tam-rank-pro, cluster-7b strip) -->
            <div class="tam-content-accordion">
                <button type="button" class="tam-content-accordion-header" data-target="content-ai-links">
                    <?php echo wp_kses($this->render_inline_icon('link'), tam_rank_kses_svg()); ?>
                    <span><?php echo esc_html(tamrank__('AI Internal Link Suggestions', 'AI Internal Link Suggestions')); ?></span>
                    <span class="tam-ai-badge">PRO</span>
                    <?php echo wp_kses($this->render_inline_icon('chevron-down'), tam_rank_kses_svg()); ?>
                </button>
                <div class="tam-content-accordion-content" id="content-ai-links" style="display: none;">
                    <?php if (apply_filters('tamrank_content_ai_links_enabled', false)): ?>
                        <?php
                        // PRO renders the working AI internal-links panel. The AJAX
                        // handlers, candidate gathering and inline driver script live in
                        // tam-rank-pro (TamRank_Pro_Content_Links). FREE passes the post
                        // + the cluster graph data computed in enqueue_assets().
                        //
                        // Gated through a filter (default false), NOT a direct can_use()
                        // call: on a FREE-only install premium_active can be stale-true
                        // (the LicenseManager that clears it lives in PRO, cluster 15), so
                        // a can_use() gate would fire the action with no PRO listener and
                        // render an empty panel. The filter only flips true when PRO is
                        // present AND licensed, so FREE-only always falls through to upsell.
                        //
                        // Third arg is null: PRO (TamRank_Pro_Content_Links::render_panel)
                        // builds its own cluster graph data and enqueues the renderer.
                        do_action('tamrank_content_ai_links_panel', $post, null);
                        ?>
                    <?php else: ?>
                        <!-- FREE: Guide card upsell -->
                        <div class="tr-guide-card">
                            <div class="tr-guide-card__top">
                                <div class="tr-guide-card__icon">
                                    <svg width="18" height="18" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
                                </div>
                                <div class="tr-guide-card__info">
                                    <h4 class="tr-guide-card__title"><?php esc_html_e('Smart link suggestions based on your content', 'tam-rank'); ?></h4>
                                    <p class="tr-guide-card__desc"><?php esc_html_e('AI analyzes your text and finds relevant internal pages to link to. It improves your site structure and helps search engines understand your content.', 'tam-rank'); ?></p>
                                </div>
                            </div>
                            <div class="tr-guide-card__benefits">
                                <div class="tr-guide-card__benefit"><span class="tr-guide-card__check">&check;</span> <?php esc_html_e('AI-driven suggestions', 'tam-rank'); ?></div>
                                <div class="tr-guide-card__benefit"><span class="tr-guide-card__check">&check;</span> <?php esc_html_e('Multiple options per link', 'tam-rank'); ?></div>
                                <div class="tr-guide-card__benefit"><span class="tr-guide-card__check">&check;</span> <?php esc_html_e('Copy in one click', 'tam-rank'); ?></div>
                            </div>
                            <div class="tr-guide-card__action">
                                <span class="tr-guide-card__action-label"><?php esc_html_e('Available with TamRank PRO', 'tam-rank'); ?></span>
                                <a href="https://tamrank.com/pro/" target="_blank" class="tr-btn tr-btn--secondary tr-btn--sm"><?php esc_html_e('View PRO', 'tam-rank'); ?> &rarr;</a>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render de top issues (maximaal 5) als uitklapbare aanbevelingen
     *
     * @param array $issues Array van top issues
     */
    private function render_top_issues($issues)
    {
        if (empty($issues)) {
            echo '<div class="tam-content-no-issues">';
            echo wp_kses($this->render_inline_icon('success'), tam_rank_kses_svg());
            echo '<span>' . esc_html__('Great! No improvements needed. Your content is well optimized.', 'tam-rank') . '</span>';
            echo '</div>';
            return;
        }

        $limited = array_slice($issues, 0, 5);
        $errors = array_filter($limited, function ($i) { return $i['type'] === 'error'; });
        $warnings = array_filter($limited, function ($i) { return $i['type'] !== 'error'; });

        if (!empty($errors)) {
            $count = count($errors);
            ?>
            <div class="tam-content-issues-group">
                <div class="tam-content-issues-group-header tam-content-issues-group-header--critical">
                    <span class="tam-content-issues-group-dot"></span>
                    <span class="tam-content-issues-group-label">
                        <?php
                        /* translators: %d: number of critical issues */
                        echo esc_html(sprintf(_n('%d critical issue', '%d critical issues', $count, 'tam-rank'), $count));
                        ?>
                    </span>
                    <span class="tam-content-issues-group-line"></span>
                </div>
                <?php $this->render_recommendation_cards($errors); ?>
            </div>
            <?php
        }

        if (!empty($warnings)) {
            $count = count($warnings);
            ?>
            <div class="tam-content-issues-group">
                <div class="tam-content-issues-group-header tam-content-issues-group-header--warning">
                    <span class="tam-content-issues-group-dot"></span>
                    <span class="tam-content-issues-group-label">
                        <?php
                        /* translators: %d: number of improvements */
                        echo esc_html(sprintf(_n('%d improvement', '%d improvements', $count, 'tam-rank'), $count));
                        ?>
                    </span>
                    <span class="tam-content-issues-group-line"></span>
                </div>
                <?php $this->render_recommendation_cards($warnings); ?>
            </div>
            <?php
        }
    }

    /**
     * Render individual recommendation cards
     *
     * @param array $issues Array of issues to render as cards
     */
    private function render_recommendation_cards($issues)
    {
        foreach ($issues as $issue) {
            $icon = $issue['type'] === 'error' ? 'error' : 'warning';
            $points = isset($issue['points']) ? intval($issue['points']) : intval($issue['weight']);
            $tip = isset($issue['tip']) ? $issue['tip'] : '';
            ?>
            <div class="tam-content-recommendation"
                data-recommendation-id="<?php echo esc_attr($issue['id']); ?>">
                <button type="button" class="tam-content-recommendation-header">
                    <div class="tam-content-recommendation-icon">
                        <?php echo wp_kses($this->render_inline_icon($icon), tam_rank_kses_svg()); ?>
                    </div>
                    <div class="tam-content-recommendation-content">
                        <div class="tam-content-recommendation-title"><?php echo esc_html($issue['title']); ?></div>
                        <div class="tam-content-recommendation-description"><?php echo esc_html($issue['description']); ?></div>
                    </div>
                    <div class="tam-content-recommendation-points">
                        ↑ +<?php echo esc_html($points); ?>% score
                    </div>
                    <div class="tam-content-recommendation-chevron">
                        <?php echo wp_kses($this->render_inline_icon('chevron-right'), tam_rank_kses_svg()); ?>
                    </div>
                </button>
                <?php if (!empty($tip)): ?>
                    <div class="tam-content-recommendation-tip">
                        <div class="tam-content-tip-box">
                            <div class="tam-content-tip-icon">
                                <?php echo wp_kses($this->render_inline_icon('lightbulb'), tam_rank_kses_svg()); ?>
                            </div>
                            <div class="tam-content-tip-content">
                                <div class="tam-content-tip-label"><?php esc_html_e('How to fix this?', 'tam-rank'); ?></div>
                                <div class="tam-content-tip-text"><?php echo esc_html($tip); ?></div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
            <?php
        }
    }

    /**
     * Render alle checks per categorie
     *
     * @param array $categories Array van categorieën met checks
     */
    private function render_all_checks($categories)
    {
        foreach ($categories as $category_id => $category) {
            ?>
            <div class="tam-content-category">
                <div class="tam-content-category-header">
                    <?php echo wp_kses($this->render_inline_icon($category['icon']), tam_rank_kses_svg()); ?>
                    <span class="tam-content-category-title"><?php echo esc_html($category['title']); ?></span>
                    <span class="tam-content-category-score">
                        <?php echo intval($category['passed']); ?>/<?php echo intval($category['total']); ?>
                    </span>
                </div>
                <div class="tam-content-category-checks">
                    <?php foreach ($category['checks'] as $check): ?>
                        <div class="tam-content-check tam-check-<?php echo esc_attr($check['status']); ?>">
                            <div class="tam-content-check-icon">
                                <?php echo wp_kses($this->render_inline_icon($check['status']), tam_rank_kses_svg()); ?>
                            </div>
                            <div class="tam-content-check-text">
                                <?php echo esc_html($check['label']); ?>
                            </div>
                            <div class="tam-content-check-status">
                                <?php echo esc_html($this->get_status_label($check['status'])); ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php
        }
    }

    /**
     * Render analyse details (headingstructuur, links, afbeeldingen)
     *
     * @param array $details Array met analyse details
     */
    private function render_analysis_details($details)
    {
        ?>
        <!-- Koppenstructuur -->
        <div class="tam-content-detail-section">
            <h5 class="tam-content-detail-title">
                <?php echo wp_kses($this->render_inline_icon('heading'), tam_rank_kses_svg()); ?>
                <?php esc_html_e('Heading structure', 'tam-rank'); ?>
            </h5>
            <div class="tam-content-heading-tree" id="content-heading-tree">
                <?php $this->render_heading_tree($details['headings']); ?>
            </div>
        </div>

        <!-- Intro Snippet -->
        <div class="tam-content-detail-section">
            <h5 class="tam-content-detail-title">
                <?php echo wp_kses($this->render_inline_icon('text'), tam_rank_kses_svg()); ?>
                <?php esc_html_e('First 150 words', 'tam-rank'); ?>
            </h5>
            <div class="tam-content-intro-snippet" id="content-intro-snippet">
                <?php echo esc_html($details['intro_snippet']); ?>
            </div>
        </div>

        <!-- Afbeeldingen -->
        <div class="tam-content-detail-section">
            <h5 class="tam-content-detail-title">
                <?php echo wp_kses($this->render_inline_icon('image'), tam_rank_kses_svg()); ?>
                <?php echo esc_html(sprintf(tamrank__('Images (%d)', 'Images (%d)'), count($details['images']))); ?>
            </h5>
            <div class="tam-content-images-list" id="content-images-list">
                <?php $this->render_images_list($details['images']); ?>
            </div>
        </div>

        <!-- Interne Links -->
        <div class="tam-content-detail-section">
            <h5 class="tam-content-detail-title">
                <?php echo wp_kses($this->render_inline_icon('internal-link'), tam_rank_kses_svg()); ?>
                <?php echo esc_html(sprintf(tamrank__('Internal links (%d)', 'Internal links (%d)'), count($details['internal_links']))); ?>
            </h5>
            <div class="tam-content-links-list" id="content-internal-links">
                <?php $this->render_links_list($details['internal_links'], 'internal'); ?>
            </div>
        </div>

        <!-- Externe Links -->
        <div class="tam-content-detail-section">
            <h5 class="tam-content-detail-title">
                <?php echo wp_kses($this->render_inline_icon('external-link'), tam_rank_kses_svg()); ?>
                <?php echo esc_html(sprintf(tamrank__('External links (%d)', 'External links (%d)'), count($details['external_links']))); ?>
            </h5>
            <div class="tam-content-links-list" id="content-external-links">
                <?php $this->render_links_list($details['external_links'], 'external'); ?>
            </div>
        </div>
        <?php
    }

    /**
     * Render heading tree
     *
     * @param array $headings Array van headings
     */
    private function render_heading_tree($headings)
    {
        if (empty($headings)) {
            echo '<div class="tam-content-empty">' . esc_html__('No headings found', 'tam-rank') . '</div>';
            return;
        }

        echo '<div class="tam-heading-tree">';
        foreach ($headings as $heading) {
            $level = intval($heading['level']);
            $indent = ($level - 1) * 20;
            $class = 'tam-heading-item tam-heading-h' . $level;
            if (isset($heading['issue'])) {
                $class .= ' tam-heading-issue';
            }
            ?>
            <div class="<?php echo esc_attr($class); ?>" style="padding-left: <?php echo esc_attr($indent); ?>px;">
                <span class="tam-heading-tag">H<?php echo esc_html($level); ?></span>
                <span class="tam-heading-text"><?php echo esc_html($heading['text']); ?></span>
                <?php if (isset($heading['issue'])): ?>
                    <span class="tam-heading-issue-badge"><?php echo esc_html($heading['issue']); ?></span>
                <?php endif; ?>
            </div>
            <?php
        }
        echo '</div>';
    }

    /**
     * Render images list
     *
     * @param array $images Array van afbeeldingen
     */
    private function render_images_list($images)
    {
        if (empty($images)) {
            echo '<div class="tam-content-empty">' . esc_html__('No images found', 'tam-rank') . '</div>';
            return;
        }

        echo '<div class="tam-images-list">';
        foreach ($images as $image) {
            $has_alt = !empty($image['alt']);
            $is_filename_alt = $image['is_filename_alt'] ?? false;
            $file_size_status = $image['file_size_status'] ?? 'unknown';
            $file_size_formatted = $image['file_size_formatted'] ?? '';
            $has_webp = $image['has_webp'] ?? false;
            $has_lazy_loading = $image['has_lazy_loading'] ?? false;
            $format = strtoupper($image['format'] ?? '');

            // Bepaal hoofdklasse
            $class = 'tam-image-item';
            if (!$has_alt) {
                $class .= ' tam-image-no-alt';
            } elseif ($is_filename_alt) {
                $class .= ' tam-image-filename-alt';
            }
            ?>
            <div class="<?php echo esc_attr($class); ?>">
                <div class="tam-image-preview">
                    <img src="<?php echo esc_url($image['src']); ?>" alt="" loading="lazy">
                    <?php if ($format): ?>
                        <span class="tam-image-format-badge"><?php echo esc_html($format); ?></span>
                    <?php endif; ?>
                </div>
                <div class="tam-image-info">
                    <!-- Alt tekst -->
                    <div class="tam-image-alt">
                        <?php if ($has_alt): ?>
                            <?php echo wp_kses($this->render_inline_icon($is_filename_alt ? 'warning' : 'success'), tam_rank_kses_svg()); ?>
                            <span><?php echo esc_html($image['alt']); ?></span>
                        <?php else: ?>
                            <?php echo wp_kses($this->render_inline_icon('error'), tam_rank_kses_svg()); ?>
                            <span><?php esc_html_e('No alt text', 'tam-rank'); ?></span>
                        <?php endif; ?>
                    </div>

                    <!-- Extra info onder alt -->
                    <div class="tam-image-extra-info"
                        style="margin-top: 8px; padding-top: 8px; border-top: 1px solid #cbd5e1; text-align: center;">
                        <?php
                        // Bestandsgrootte met kleurcodering
                        $size_class = 'size-good';
                        $size_color = '#10b981';
                        if ($file_size_status === 'error') {
                            $size_class = 'size-error';
                            $size_color = '#f43f5e';
                        } elseif ($file_size_status === 'warning') {
                            $size_class = 'size-warning';
                            $size_color = '#f59e0b';
                        } elseif ($file_size_status === 'info') {
                            $size_class = 'size-info';
                            $size_color = 'var(--tr-color-info)';
                        }

                        // Als geen file_size_formatted, toon 'Onbekend'
                        $size_display = !empty($file_size_formatted) ? $file_size_formatted : __('Unknown', 'tam-rank');
                        ?>
                        <span class="tam-image-size <?php echo esc_attr($size_class); ?>"
                            style="display: block; margin-bottom: 6px; font-weight: 600; font-size: 11px; color: <?php echo esc_attr($size_color); ?>;"><?php echo esc_html($size_display); ?></span>

                        <!-- Badges -->
                        <div class="tam-image-badges" style="display: flex; flex-wrap: wrap; justify-content: center; gap: 4px;">
                            <?php if ($has_webp || $format === 'WEBP'): ?>
                                <span class="tam-image-badge tam-badge-success"
                                    style="display: inline-flex; padding: 2px 6px; border-radius: 8px; font-size: 9px; font-weight: 500; background: #d1fae5; color: #10b981;">WebP</span>
                            <?php else: ?>
                                <span class="tam-image-badge tam-badge-info"
                                    style="display: inline-flex; padding: 2px 6px; border-radius: 8px; font-size: 9px; font-weight: 500; background: var(--tr-color-info-light); color: var(--tr-color-info);"><?php esc_html_e('No WebP', 'tam-rank'); ?></span>
                            <?php endif; ?>
                            <?php if ($has_lazy_loading): ?>
                                <span class="tam-image-badge tam-badge-success"
                                    style="display: inline-flex; padding: 2px 6px; border-radius: 8px; font-size: 9px; font-weight: 500; background: #d1fae5; color: #10b981;">Lazy</span>
                            <?php else: ?>
                                <span class="tam-image-badge tam-badge-warning"
                                    style="display: inline-flex; padding: 2px 6px; border-radius: 8px; font-size: 9px; font-weight: 500; background: #fff8eb; color: #b8860b;"><?php esc_html_e('No lazy', 'tam-rank'); ?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        }
        echo '</div>';
    }

    /**
     * Render links list
     *
     * @param array $links Array van links
     * @param string $type Type links (internal/external)
     */
    private function render_links_list($links, $type)
    {
        if (empty($links)) {
            echo '<div class="tam-content-empty">' . ($type === 'internal' ? esc_html__('No internal links found', 'tam-rank') : esc_html__('No external links found', 'tam-rank')) . '</div>';
            return;
        }

        echo '<div class="tam-links-list">';
        foreach ($links as $link) {
            $status_class = '';
            $status_icon = 'success';
            if (isset($link['status']) && $link['status'] === 404) {
                $status_class = 'tam-link-broken';
                $status_icon = 'error';
            } elseif (isset($link['is_spam']) && $link['is_spam']) {
                $status_class = 'tam-link-spam';
                $status_icon = 'warning';
            }
            ?>
            <div class="tam-link-item <?php echo esc_attr($status_class); ?>">
                <?php echo wp_kses($this->render_inline_icon($status_icon), tam_rank_kses_svg()); ?>
                <span class="tam-link-anchor"><?php echo esc_html($link['anchor'] ?: __('(no anchor text)', 'tam-rank')); ?></span>
                <span class="tam-link-url"><?php echo esc_html($link['url']); ?></span>
                <?php if (isset($link['status']) && $link['status'] === 404): ?>
                    <span class="tam-link-status-badge">404</span>
                <?php endif; ?>
            </div>
            <?php
        }
        echo '</div>';
    }

    /**
     * Get score class gebaseerd op score
     *
     * @param int $score Score waarde
     * @return string CSS class
     */
    private function get_score_class($score)
    {
        if ($score >= 80)
            return 'score-excellent';
        if ($score >= 60)
            return 'score-good';
        if ($score >= 40)
            return 'score-needs-work';
        return 'score-poor';
    }

    /**
     * Get score color based on score
     *
     * @param int $score Score waarde
     * @return string Hex color
     */
    private function get_score_color($score)
    {
        if ($score >= 80)
            return '#10b981'; // --tr-color-status-excellent
        if ($score >= 60)
            return '#14b8a6'; // --tr-color-status-good
        if ($score >= 40)
            return '#f59e0b'; // --tr-color-status-attention
        return '#f43f5e'; // --tr-color-status-improve
    }

    /**
     * Get score label gebaseerd op score
     *
     * @param int $score Score waarde
     * @return string Label tekst
     */
    private function get_score_label($score)
    {
        if ($score >= 80)
            return __('Excellent', 'tam-rank');
        if ($score >= 60)
            return __('Good', 'tam-rank');
        if ($score >= 40)
            return __('Needs attention', 'tam-rank');
        return __('Improve', 'tam-rank');
    }

    /**
     * Get status label
     *
     * @param string $status Status (success/warning/error)
     * @return string Label tekst
     */
    private function get_status_label($status)
    {
        switch ($status) {
            case 'success':
                return __('OK', 'tam-rank');
            case 'warning':
                return __('Improvement', 'tam-rank');
            case 'error':
                return __('Critical', 'tam-rank');
            default:
                return '';
        }
    }

    /**
     * Render inline SVG icon
     *
     * @param string $icon Icon naam
     * @return string SVG HTML
     */
    private function render_inline_icon($icon)
    {
        $icons = array(
            'success' => '<svg class="tam-icon tam-icon-success" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" fill="currentColor"/><path d="M8 12L11 15L16 9" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',

            'warning' => '<svg class="tam-icon tam-icon-warning" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" fill="currentColor"/><path d="M12 8V12M12 16H12.01" stroke="white" stroke-width="2" stroke-linecap="round"/></svg>',

            'error' => '<svg class="tam-icon tam-icon-error" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" fill="currentColor"/><path d="M15 9L9 15M9 9L15 15" stroke="white" stroke-width="2" stroke-linecap="round"/></svg>',

            'info' => '<svg class="tam-icon tam-icon-info" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/><path d="M12 16V12M12 8H12.01" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',

            'alert' => '<svg class="tam-icon tam-icon-alert" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 9V13M12 17H12.01M10.29 3.86L1.82 18A2 2 0 003.54 21H20.46A2 2 0 0022.18 18L13.71 3.86A2 2 0 0010.29 3.86Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',

            'refresh' => '<svg class="tam-icon tam-icon-refresh" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 4V10H7M23 20V14H17M20.49 9A9 9 0 005.64 5.64L1 10M3.51 15A9 9 0 0018.36 18.36L23 14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',

            'checklist' => '<svg class="tam-icon tam-icon-checklist" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9 11L12 14L22 4M21 12V19A2 2 0 0119 21H5A2 2 0 013 19V5A2 2 0 015 3H16" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',

            'chevron-down' => '<svg class="tam-icon tam-icon-chevron tam-accordion-chevron" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6 9L12 15L18 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',

            'heading' => '<svg class="tam-icon tam-icon-heading" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 12H20M4 6V18M20 6V18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',

            'text' => '<svg class="tam-icon tam-icon-text" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 7V4H20V7M9 20H15M12 4V20" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',

            'image' => '<svg class="tam-icon tam-icon-image" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect x="3" y="3" width="18" height="18" rx="2" stroke="currentColor" stroke-width="2"/><circle cx="8.5" cy="8.5" r="1.5" fill="currentColor"/><path d="M21 15L16 10L5 21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',

            'internal-link' => '<svg class="tam-icon tam-icon-internal-link" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M10 13A5 5 0 007.54 17.54L7.54 17.54A5 5 0 0014 17.54L16 15.54M14 11A5 5 0 0016.46 6.46L16.46 6.46A5 5 0 0010 6.46L8 8.46" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',

            'external-link' => '<svg class="tam-icon tam-icon-external-link" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M18 13V19A2 2 0 0116 21H5A2 2 0 013 19V8A2 2 0 015 6H11M15 3H21V9M10 14L21 3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',

            'keyword' => '<svg class="tam-icon tam-icon-keyword" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="11" cy="11" r="8" stroke="currentColor" stroke-width="2"/><path d="M21 21L16.65 16.65" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',

            'readability' => '<svg class="tam-icon tam-icon-readability" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M2 3H8A4 4 0 0112 7V21A3 3 0 009 18H2V3ZM22 3H16A4 4 0 0012 7V21A3 3 0 0015 18H22V3Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',

            'link' => '<svg class="tam-icon tam-icon-link" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M10 13A5 5 0 007.54 17.54L7.54 17.54A5 5 0 0014 17.54L16 15.54M14 11A5 5 0 0016.46 6.46L16.46 6.46A5 5 0 0010 6.46L8 8.46" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',

            'sparkle' => '<svg class="tam-icon tam-icon-sparkle" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 2L14.5 9.5L22 12L14.5 14.5L12 22L9.5 14.5L2 12L9.5 9.5L12 2Z" fill="currentColor"/><path d="M19 4L19.5 5.5L21 6L19.5 6.5L19 8L18.5 6.5L17 6L18.5 5.5L19 4Z" fill="currentColor"/></svg>',

            'length' => '<svg class="tam-icon tam-icon-length" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M21 10H3M21 6H3M21 14H3M21 18H10" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',

            'technical' => '<svg class="tam-icon tam-icon-technical" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M14.7 6.3A1 1 0 0016 5L12 1L8 5A1 1 0 009.3 6.3L11 4.6V10.4L9.3 8.7A1 1 0 008 10L12 14L16 10A1 1 0 0014.7 8.7L13 10.4V4.6L14.7 6.3ZM5 16H19V18H5V16ZM5 20H19V22H5V20Z" fill="currentColor"/></svg>',

            'chevron-right' => '<svg class="tam-icon tam-icon-chevron-right" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9 18L15 12L9 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',

            'lightbulb' => '<svg class="tam-icon tam-icon-lightbulb" width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9 21H15M12 3C8.13401 3 5 6.13401 5 10C5 12.38 6.19 14.47 8 15.74V17C8 17.55 8.45 18 9 18H15C15.55 18 16 17.55 16 17V15.74C17.81 14.47 19 12.38 19 10C19 6.13401 15.866 3 12 3Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 3V1M4.22 4.22L2.81 2.81M1 12H3M4.22 19.78L2.81 21.19M21.19 2.81L19.78 4.22M23 12H21M21.19 21.19L19.78 19.78" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',
        );

        return isset($icons[$icon]) ? $icons[$icon] : '';
    }

    /**
     * Extraheer image IDs uit Elementor JSON data
     *
     * @param string $elementor_data Elementor JSON data string
     * @return string Pseudo-content met wp-image classes voor detectie
     */
    private function extract_elementor_images_from_data($elementor_data)
    {
        $pseudo_content = '';

        // Decode JSON data
        $data = json_decode($elementor_data, true);
        if (!is_array($data)) {
            return '';
        }

        // Recursief zoeken naar image IDs
        $image_ids = $this->find_elementor_image_ids($data);

        // Genereer pseudo-content met wp-image classes zodat de analyzer ze kan vinden
        foreach ($image_ids as $id) {
            $pseudo_content .= ' <img class="wp-image-' . intval($id) . '" src="placeholder" /> ';
        }

        return $pseudo_content;
    }

    /**
     * Recursief zoeken naar image IDs in Elementor data structuur
     *
     * @param array $data Elementor data array
     * @return array Array van image IDs
     */
    private function find_elementor_image_ids($data)
    {
        $ids = array();

        if (!is_array($data)) {
            return $ids;
        }

        foreach ($data as $key => $value) {
            // Check voor image object met id
            if ($key === 'image' && is_array($value) && isset($value['id'])) {
                $ids[] = intval($value['id']);
            }
            // Check voor background_image
            elseif ($key === 'background_image' && is_array($value) && isset($value['id'])) {
                $ids[] = intval($value['id']);
            }
            // Check voor _id (Elementor image widget)
            elseif ($key === 'id' && is_numeric($value) && isset($data['url']) && strpos($data['url'], 'uploads') !== false) {
                $ids[] = intval($value);
            }
            // Recursief zoeken in nested arrays
            elseif (is_array($value)) {
                $nested_ids = $this->find_elementor_image_ids($value);
                $ids = array_merge($ids, $nested_ids);
            }
        }

        return array_unique($ids);
    }
}
