/**
 * TAMRANK Schema Detector JavaScript
 *
 * Afhandeling van AJAX interacties voor schema detectie in de metabox
 *
 * @package TamRank
 * @subpackage Schema
 * @since 1.0.0
 */

(function($) {
    'use strict';

    /**
     * Fill one placeholder without letting the value expand.
     *
     * Copy of the canonical helper in assets/js/tamrank-onboarding.js; read the
     * docblock there for why String.replace() with a STRING replacement mangles
     * any value carrying $&, $`, $' or $$, and why this is a copy instead of a
     * shared global. `token` may be a string or a RegExp; a FUNCTION replacement
     * is exempt from that expansion in both cases. Keep the body identical.
     */
    function fillPlaceholder(tpl, token, value) {
        var literal = String(value);
        return String(tpl).replace(token, function () { return literal; });
    }

    /**
     * Schema Detector Module
     */
    var TamRankSchemaDetector = {

        /**
         * Configuratie uit PHP localization
         */
        config: {},

        /**
         * Initialiseer de module
         */
        init: function() {
            // Haal configuratie op
            if (typeof tamrankSchemaDetector !== 'undefined') {
                this.config = tamrankSchemaDetector;
            } else {
                console.warn('TamRank Schema Detector: configuration not found');
                return;
            }

            this.bindEvents();
        },

        /**
         * Bind alle event handlers
         */
        bindEvents: function() {
            var self = this;

            // Detecteer schema button
            $(document).on('click', '.tam-detecteer-opnieuw', function(e) {
                e.preventDefault();
                self.detecteerSchema($(this));
            });

            // Accepteer aanbeveling button (oude UI)
            $(document).on('click', '.tam-accepteer-schema', function(e) {
                e.preventDefault();
                self.accepteerSchema($(this));
            });

            // Advies overnemen button (nieuwe UI)
            $(document).on('click', '.tam-advies-overnemen', function(e) {
                e.preventDefault();
                self.adviesOvernemen($(this));
            });

            // Bron kaart selectie (nieuwe UI)
            $(document).on('click', '.tam-schema-bron-kaart', function(e) {
                // Niet voorkomen als het een radio button of label is
                if ($(e.target).is('input[type="radio"]') || $(e.target).is('label')) {
                    return;
                }
                var $radio = $(this).find('input[type="radio"]');
                if ($radio.length && !$radio.prop('disabled')) {
                    $radio.prop('checked', true).trigger('change');
                }
            });

            // Bron wijziging handler (nieuwe UI)
            $(document).on('change', 'input[name="tamrank_schema_bron"]', function() {
                self.handleBronWijziging($(this).val());
            });

            // Toon handmatige selectie
            $(document).on('click', '.tam-toon-handmatig', function(e) {
                e.preventDefault();
                self.toonHandmatigPanel();
            });

            // Verberg handmatige selectie
            $(document).on('click', '.tam-verberg-handmatig', function(e) {
                e.preventDefault();
                self.verbergHandmatigPanel();
            });

            // Sla handmatige keuze op
            $(document).on('click', '.tam-sla-handmatig-op', function(e) {
                e.preventDefault();
                self.slaHandmatigOp($(this));
            });

            // Reset naar automatisch
            $(document).on('click', '.tam-reset-naar-auto', function(e) {
                e.preventDefault();
                self.resetNaarAutomatisch($(this));
            });

            // JSON-LD toggle (nieuwe UI)
            $(document).on('click', '.tam-toggle-jsonld', function(e) {
                e.preventDefault();
                self.toggleJsonLd();
            });

            // Template wijziging handler (nieuwe UI)
            $(document).on('change', '#tamrank_schema_template_id', function() {
                self.handleTemplateWijziging($(this).val());
            });
        },

        /**
         * Detecteer schema via AJAX
         *
         * @param {jQuery} $button Button element
         */
        detecteerSchema: function($button) {
            var self = this;
            var postId = $button.data('post-id') || this.config.postId;
            var origineleTekst = $button.html();

            // Disable button en toon loading
            $button.prop('disabled', true).html(
                '<svg class="tam-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
                '<path d="M21 12a9 9 0 11-6.219-8.56"/></svg> ' +
                this.config.teksten.detecteren
            );

            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'tamrank_detecteer_schema',
                    nonce: this.getNonce(),
                    post_id: postId
                },
                success: function(response) {
                    $button.prop('disabled', false).html(origineleTekst);
                    if (response.success) {
                        // Bouw melding met alle gedetecteerde schema's
                        var schemas = [response.data.hoofd_schema];
                        if (response.data.extra_schemas && response.data.extra_schemas.length > 0) {
                            schemas = schemas.concat(response.data.extra_schemas);
                        }
                        self.toonSuccesMelding((self.config.teksten ? self.config.teksten.schemas_detected : 'Schemas detected:') + ' ' + schemas.join(', '));

                        // Update de UI dynamisch zonder pagina te herladen
                        self.updateSchemaUI(response.data);
                    } else {
                        self.toonFoutMelding(response.data && response.data.message ? response.data.message :self.config.teksten.fout);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', status, error);
                    self.toonFoutMelding(self.config.teksten.fout);
                    $button.prop('disabled', false).html(origineleTekst);
                }
            });
        },

        /**
         * Update de hele schema UI na herdetectie (zonder page reload)
         */
        updateSchemaUI: function(data) {
            var self = this;
            var hoofdSchema = data.hoofd_schema || 'WebPage';
            var extraSchemas = data.extra_schemas || [];
            var betrouwbaarheid = Math.round((data.betrouwbaarheid || 0) * 100);

            // BELANGRIJK: Update de globale tamrankDetectieData zodat andere functies
            // (zoals updateSchemaVoorDezePagina in meta-boxes.php) de nieuwe data gebruiken
            if (typeof window.tamrankDetectieData !== 'undefined') {
                window.tamrankDetectieData.hoofdSchema = hoofdSchema;
                window.tamrankDetectieData.extraSchemas = extraSchemas;
                window.tamrankDetectieData.betrouwbaarheid = data.betrouwbaarheid || 0;
            }

            // Update de "Schema voor deze pagina" sectie (hoofd badges container)
            var $hoofdBadgeContainer = $('#tam-schema-badges-container');
            if ($hoofdBadgeContainer.length) {
                var hoofdBadgesHtml = '';

                // Hoofd schema badge (groen)
                hoofdBadgesHtml += '<span class="tam-hoofd-badge" style="display: inline-flex; align-items: center; padding: 6px 14px; background: #ecfdf5; color: #059669; border: 1px solid #a7f3d0; border-radius: 8px; font-size: 13px; font-weight: 600;">' + self.escapeHtml(hoofdSchema) + '</span>';

                // Extra schema badges (groen, consistent met de brand + de Automatisch-kaart)
                if (extraSchemas.length > 0) {
                    hoofdBadgesHtml += '<span class="tam-plus-separator" style="color: #d1d5db; font-size: 14px;">+</span>';
                    extraSchemas.forEach(function(extra) {
                        hoofdBadgesHtml += '<span class="tam-extra-badge" style="display: inline-flex; align-items: center; padding: 5px 12px; background: #f0fdf4; color: #15803d; border: 1px solid #bbf7d0; border-radius: 8px; font-size: 12px; font-weight: 500;">' + self.escapeHtml(extra) + '</span>';
                    });
                }

                $hoofdBadgeContainer.html(hoofdBadgesHtml);
            }

            // Update de schema badges in de Automatisch kaart (met specifieke ID)
            var $autoBadgeContainer = $('#tam-auto-schema-badges');
            if ($autoBadgeContainer.length) {
                var autoBadgesHtml = '<span style="display: inline-flex; align-items: center; padding: 4px 10px; background: #ecfdf5; color: #059669; border: 1px solid #a7f3d0; border-radius: 6px; font-size: 12px; font-weight: 600;">' + self.escapeHtml(hoofdSchema) + '</span>';

                if (extraSchemas.length > 0) {
                    autoBadgesHtml += '<span style="color: #cbd5e1; font-size: 12px;">+</span>';
                    extraSchemas.forEach(function(extra) {
                        autoBadgesHtml += '<span style="display: inline-flex; align-items: center; padding: 3px 8px; background: #f0fdf4; color: #15803d; border: 1px solid #bbf7d0; border-radius: 5px; font-size: 11px; font-weight: 500;">' + self.escapeHtml(extra) + '</span>';
                    });
                }

                $autoBadgeContainer.html(autoBadgesHtml);
            }

            // Update de betrouwbaarheid balk en toon container
            var $autoBetrouwbaarheid = $('#tam-auto-betrouwbaarheid');
            if ($autoBetrouwbaarheid.length) {
                $autoBetrouwbaarheid.show();
                $autoBetrouwbaarheid.find('div > div').css('width', betrouwbaarheid + '%');
                $autoBetrouwbaarheid.find('span').text(betrouwbaarheid + '%');
            }

            // Update ook de oude detectie banner formaat (indien aanwezig)
            this.updateDetectieBanner(data);

            // Update de JSON-LD preview via AJAX (zodat nieuwe detectie data getoond wordt)
            if (typeof window.tamrankUpdateSchemaPreview === 'function') {
                window.tamrankUpdateSchemaPreview();
            }

            // Flash effect om aan te geven dat er iets is veranderd
            var $card = $('.tam-bronkeuze-kaart').first();
            $card.css('transition', 'background 0.3s');
            $card.css('background', 'linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%)');
            setTimeout(function() {
                // Reset naar originele kleur afhankelijk van of het actief is
                var isActief = $card.find('input[type="radio"]').prop('checked');
                if (isActief) {
                    $card.css('background', 'linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%)');
                } else {
                    $card.css('background', '#f8fafc');
                }
            }, 500);
        },

        /**
         * Update de detectie banner met nieuwe data
         */
        updateDetectieBanner: function(data) {
            var $sectie = $('.tamrank-schema-detectie-sectie');
            if (!$sectie.length) return;

            // Verberg de gele "geen detectie" banner
            $sectie.find('.tam-detectie-leeg').hide();

            // Toon of update de blauwe aanbeveling banner
            var $banner = $sectie.find('.tam-detectie-aanbeveling');
            if ($banner.length) {
                // Update bestaande banner
                $banner.find('strong').first().text(data.hoofd_schema);
                $banner.show();
            }
        },

        /**
         * Accepteer gedetecteerd schema via AJAX
         *
         * @param {jQuery} $button Button element
         */
        accepteerSchema: function($button) {
            var self = this;
            var postId = $button.data('post-id') || this.config.postId;
            var origineleTekst = $button.html();

            $button.prop('disabled', true).html(
                '<svg class="tam-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
                '<path d="M21 12a9 9 0 11-6.219-8.56"/></svg> ' +
                this.config.teksten.opslaan
            );

            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'tamrank_accepteer_schema',
                    nonce: this.getNonce(),
                    post_id: postId
                },
                success: function(response) {
                    $button.prop('disabled', false).html(origineleTekst);
                    if (response.success) {
                        self.toonSuccesMelding(self.config.teksten.geaccepteerd);
                        // Verberg de aanbeveling banner en toon groene "handmatig gekozen" banner
                        var hoofdSchema = response.data.hoofd_schema || '';
                        var extraSchemas = response.data.extra_schemas || [];
                        self.toonHandmatigGekozenBanner(hoofdSchema, extraSchemas);
                    } else {
                        self.toonFoutMelding(response.data && response.data.message ? response.data.message :self.config.teksten.fout);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', status, error);
                    self.toonFoutMelding(self.config.teksten.fout);
                    $button.prop('disabled', false).html(origineleTekst);
                }
            });
        },

        /**
         * Toon de groene "actief schema" banner
         *
         * @param {string} hoofdSchema Hoofd schema type
         * @param {array} extraSchemas Extra schema types
         * @param {string} labelTekst Label tekst (optioneel, default: "Actief schema:")
         */
        toonHandmatigGekozenBanner: function(hoofdSchema, extraSchemas, labelTekst) {
            var self = this;
            var $sectie = $('.tamrank-schema-detectie-sectie');
            var label = labelTekst || (this.config.teksten ? this.config.teksten.active_schema : 'Active schema:');

            // Verberg andere banners
            $sectie.find('.tam-detectie-aanbeveling').hide();
            $sectie.find('.tam-detectie-leeg').hide();

            // Verwijder bestaande handmatig banner als die er is
            $sectie.find('.tam-detectie-handmatig').remove();

            // Bouw extra types tekst
            var extraTekst = '';
            if (extraSchemas && extraSchemas.length > 0) {
                extraTekst = '<span style="color: #15803d; font-size: 13px; margin-left: 6px;">+ ' + extraSchemas.join(', ') + '</span>';
            }

            // Maak nieuwe groene banner
            var bannerHtml =
                '<div class="tam-detectie-handmatig" style="background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%); border: 2px solid #86efac; border-radius: 12px; padding: 15px 20px; margin-bottom: 15px;">' +
                    '<div style="display: flex; align-items: center; justify-content: space-between; gap: 15px; flex-wrap: wrap;">' +
                        '<div style="display: flex; align-items: center; gap: 12px;">' +
                            '<div style="width: 36px; height: 36px; background: #22c55e; border-radius: 8px; display: flex; align-items: center; justify-content: center;">' +
                                '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">' +
                                    '<polyline points="20 6 9 17 4 12"/>' +
                                '</svg>' +
                            '</div>' +
                            '<div>' +
                                '<span style="color: #166534; font-weight: 600; font-size: 14px;">' + label + '</span>' +
                                '<strong style="color: #166534; font-size: 15px; margin-left: 6px;">' + (hoofdSchema || '') + '</strong>' +
                                extraTekst +
                            '</div>' +
                        '</div>' +
                        '<div style="display: flex; gap: 8px;">' +
                            '<button type="button" class="tam-toon-handmatig" style="padding: 8px 16px; background: white; color: #2C3E50; border: 2px solid #d0d0d0; border-radius: 8px; font-size: 13px; font-weight: 500; cursor: pointer; transition: all 0.2s ease;">' + (this.config.teksten ? this.config.teksten.change : 'Change') + '</button>' +
                            '<button type="button" class="tam-reset-naar-auto" data-post-id="' + this.config.postId + '" style="padding: 8px 16px; background: white; color: #64748b; border: 2px solid #e0e0e0; border-radius: 8px; font-size: 13px; font-weight: 500; cursor: pointer; transition: all 0.2s ease;">' + (this.config.teksten ? this.config.teksten.back_to_automatic : 'Back to Automatic') + '</button>' +
                        '</div>' +
                    '</div>' +
                '</div>';

            // Voeg banner toe aan het begin van de sectie
            $sectie.prepend(bannerHtml);
        },

        /**
         * Toon de blauwe aanbeveling banner (na reset naar automatisch)
         *
         * @param {string} hoofdSchema Hoofd schema type
         * @param {array} extraSchemas Extra schema types
         */
        toonAanbevelingBanner: function(hoofdSchema, extraSchemas) {
            var self = this;
            var $sectie = $('.tamrank-schema-detectie-sectie');

            // Verberg andere banners
            $sectie.find('.tam-detectie-handmatig').remove();
            $sectie.find('.tam-detectie-leeg').hide();
            $sectie.find('.tam-detectie-aanbeveling').remove();

            // Als geen schema, toon lege banner
            if (!hoofdSchema) {
                // Toon de gele "geen detectie" banner als die er is
                $sectie.find('.tam-detectie-leeg').show();
                return;
            }

            // Bouw extra types tekst
            var extraHtml = '';
            if (extraSchemas && extraSchemas.length > 0) {
                extraHtml = '<p style="margin: 0 0 12px 0; color: #2C3E50; font-size: 13px;">' + (self.config.teksten ? self.config.teksten.schema_extra_found : 'Extra schemas found:') + ' ';
                extraSchemas.forEach(function(extra) {
                    extraHtml += '<span style="background: #ddeaf7; color: #3d6ba3; padding: 2px 8px; border-radius: 4px; font-size: 12px; margin-left: 4px;">' + extra + '</span>';
                });
                extraHtml += '</p>';
            }

            // Maak nieuwe blauwe aanbeveling banner
            var bannerHtml =
                '<div class="tam-detectie-aanbeveling" style="background: var(--tr-color-info-light); border: 2px solid var(--tr-color-info); border-radius: 12px; padding: 20px; margin-bottom: 15px;">' +
                    '<div style="display: flex; align-items: flex-start; gap: 15px;">' +
                        '<div style="flex-shrink: 0; width: 48px; height: 48px; background: var(--tr-color-info); border-radius: 12px; display: flex; align-items: center; justify-content: center;">' +
                            '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">' +
                                '<path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/>' +
                            '</svg>' +
                        '</div>' +
                        '<div style="flex: 1;">' +
                            '<h4 style="margin: 0 0 8px 0; color: #3d6ba3; font-size: 16px; font-weight: 600;">' + (this.config.teksten ? this.config.teksten.schema_recommendation : 'Schema Recommendation') + '</h4>' +
                            '<p style="margin: 0 0 12px 0; color: #2C3E50; font-size: 14px; line-height: 1.5;">' +
                                (this.config.teksten && this.config.teksten.schema_recommend_text ? fillPlaceholder(this.config.teksten.schema_recommend_text, '%s', '<strong>' + hoofdSchema + '</strong>') : 'Based on the content we recommend <strong>' + hoofdSchema + '</strong>.') +
                            '</p>' +
                            extraHtml +
                            '<div style="display: flex; gap: 10px; flex-wrap: wrap;">' +
                                '<button type="button" class="tam-accepteer-schema" data-post-id="' + this.config.postId + '" style="display: inline-flex; align-items: center; gap: 6px; padding: 10px 18px; background: #25AC75; color: white; border: none; border-radius: 8px; font-size: 14px; font-weight: 500; cursor: pointer; transition: all 0.2s ease;">' +
                                    '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>' +
                                    (this.config.teksten ? this.config.teksten.accept_recommendation : 'Accept Recommendation') +
                                '</button>' +
                                '<button type="button" class="tam-toon-handmatig" style="display: inline-flex; align-items: center; gap: 6px; padding: 10px 18px; background: white; color: #2C3E50; border: 2px solid #d0d0d0; border-radius: 8px; font-size: 14px; font-weight: 500; cursor: pointer; transition: all 0.2s ease;">' +
                                    '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>' +
                                    (this.config.teksten ? this.config.teksten.choose_manual : 'Choose Manually') +
                                '</button>' +
                                '<button type="button" class="tam-detecteer-opnieuw" data-post-id="' + this.config.postId + '" style="display: inline-flex; align-items: center; gap: 6px; padding: 10px 18px; background: white; color: #64748b; border: 2px solid #e0e0e0; border-radius: 8px; font-size: 14px; font-weight: 500; cursor: pointer; transition: all 0.2s ease;">' +
                                    '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>' +
                                    (this.config.teksten ? this.config.teksten.detect_again : 'Detect Again') +
                                '</button>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>';

            // Voeg banner toe aan het begin van de sectie
            $sectie.prepend(bannerHtml);
        },

        /**
         * Toon handmatige selectie panel
         */
        toonHandmatigPanel: function() {
            $('.tam-handmatige-selectie').slideDown(200);
        },

        /**
         * Verberg handmatige selectie panel
         */
        verbergHandmatigPanel: function() {
            $('.tam-handmatige-selectie').slideUp(200);
        },

        /**
         * Sla handmatige keuze op via AJAX
         *
         * @param {jQuery} $button Button element
         */
        slaHandmatigOp: function($button) {
            var self = this;
            var postId = $button.data('post-id') || this.config.postId;
            var origineleTekst = $button.html();

            // Haal geselecteerde waarden op
            var hoofdType = $('#tamrank_handmatig_schema_type').val();
            var extraTypes = [];

            $('input[name="tamrank_handmatig_extra_schemas[]"]:checked').each(function() {
                extraTypes.push($(this).val());
            });

            // Validatie
            if (!hoofdType) {
                self.toonFoutMelding(self.config.teksten ? self.config.teksten.select_main_type : 'Select a main schema type.');
                $('#tamrank_handmatig_schema_type').focus();
                return;
            }

            $button.prop('disabled', true).html(
                '<svg class="tam-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
                '<path d="M21 12a9 9 0 11-6.219-8.56"/></svg> ' +
                this.config.teksten.opslaan
            );

            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'tamrank_sla_handmatig_schema_op',
                    nonce: this.getNonce(),
                    post_id: postId,
                    hoofd_type: hoofdType,
                    extra_types: extraTypes
                },
                success: function(response) {
                    $button.prop('disabled', false).html(origineleTekst);
                    if (response.success) {
                        self.toonSuccesMelding(self.config.teksten.opgeslagen);
                        // Verberg het handmatige selectie panel
                        self.verbergHandmatigPanel();
                        // Toon handmatig gekozen banner met de opgeslagen waarden
                        var hoofdSchema = response.data.hoofd_schema || hoofdType;
                        var extraSchemas = response.data.extra_schemas || extraTypes;
                        self.toonHandmatigGekozenBanner(hoofdSchema, extraSchemas, self.config.teksten ? self.config.teksten.manually_chosen : 'Manually chosen:');
                    } else {
                        self.toonFoutMelding(response.data && response.data.message ? response.data.message :self.config.teksten.fout);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', status, error);
                    self.toonFoutMelding(self.config.teksten.fout);
                    $button.prop('disabled', false).html(origineleTekst);
                }
            });
        },

        /**
         * Reset naar automatische detectie
         *
         * @param {jQuery} $button Button element
         */
        resetNaarAutomatisch: function($button) {
            var self = this;
            var postId = $button.data('post-id') || this.config.postId;
            var origineleTekst = $button.html();

            window.TamRank.confirm({
                title: (self.config.teksten && self.config.teksten.reset_keuze_titel) || 'Reset schema choice?',
                message: (self.config.teksten && self.config.teksten.reset_keuze_bericht) || 'The manual choice will be removed and automatic detection will be used again.',
                confirmLabel: (self.config.teksten && self.config.teksten.resetten) || 'Reset',
                variant: 'default'
            }).then(function (ok) {
                if (!ok) return;
                doReset();
            });

            function doReset() {
            $button.prop('disabled', true).text((self.config.teksten && self.config.teksten.busy) || 'Processing...');

            $.ajax({
                url: self.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'tamrank_reset_schema_keuze',
                    nonce: self.getNonce(),
                    post_id: postId
                },
                success: function(response) {
                    $button.prop('disabled', false).html(origineleTekst);
                    if (response.success) {
                        self.toonSuccesMelding(self.config.teksten.gereset);
                        // Verberg handmatig banner en toon aanbeveling banner
                        var hoofdSchema = response.data.hoofd_schema || '';
                        var extraSchemas = response.data.extra_schemas || [];
                        self.toonAanbevelingBanner(hoofdSchema, extraSchemas);
                    } else {
                        self.toonFoutMelding(response.data && response.data.message ? response.data.message :self.config.teksten.fout);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', status, error);
                    self.toonFoutMelding(self.config.teksten.fout);
                    $button.prop('disabled', false).html(origineleTekst);
                }
            });
            }
        },

        /**
         * Handle advies overnemen (nieuwe UI)
         *
         * @param {jQuery} $button Button element
         */
        adviesOvernemen: function($button) {
            var self = this;
            var postId = $button.data('post-id') || this.config.postId;
            var origineleTekst = $button.html();

            $button.prop('disabled', true).html(
                '<svg class="tam-spin" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
                '<path d="M21 12a9 9 0 11-6.219-8.56"/></svg> ' + (self.config.teksten ? self.config.teksten.busy : 'Processing...')
            );

            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'tamrank_accepteer_schema',
                    nonce: this.getNonce(),
                    post_id: postId
                },
                success: function(response) {
                    if (response.success) {
                        self.toonSuccesMelding(self.config.teksten ? self.config.teksten.advice_applied : 'Schema advice applied!');
                        // Selecteer automatisch bron en update UI
                        $('input[name="tamrank_schema_bron"][value="automatisch"]').prop('checked', true);
                        self.updateStatusBalk(response.data.hoofd_schema || '', 'automatisch');
                        self.updateAdviesBlokStatus(true);
                        $button.html(
                            '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
                            '<polyline points="20 6 9 17 4 12"/></svg> ' + (self.config.teksten ? self.config.teksten.active : 'Active')
                        ).addClass('tam-btn-actief').prop('disabled', true);
                    } else {
                        self.toonFoutMelding(response.data && response.data.message ? response.data.message : self.config.teksten ? self.config.teksten.fout : 'An error occurred.');
                        $button.prop('disabled', false).html(origineleTekst);
                    }
                },
                error: function() {
                    self.toonFoutMelding(self.config.teksten ? self.config.teksten.fout : 'An error occurred.');
                    $button.prop('disabled', false).html(origineleTekst);
                }
            });
        },

        /**
         * Handle bron wijziging (nieuwe UI)
         *
         * @param {string} bron Geselecteerde bron
         */
        handleBronWijziging: function(bron) {
            var self = this;
            var postId = this.config.postId;

            // Update visuele selectie van kaarten
            $('.tam-schema-bron-kaart').removeClass('tam-kaart-geselecteerd');
            $('input[name="tamrank_schema_bron"]:checked').closest('.tam-schema-bron-kaart').addClass('tam-kaart-geselecteerd');

            // Toon/verberg template selector bij template bron
            if (bron === 'template') {
                $('.tam-template-selector-row').slideDown(200);
            } else {
                $('.tam-template-selector-row').slideUp(200);
            }

            // Toon/verberg handmatige selector bij handmatig bron
            if (bron === 'handmatig') {
                $('.tam-handmatige-schema-row').slideDown(200);
            } else {
                $('.tam-handmatige-schema-row').slideUp(200);
            }

            // Toon/verberg extra schemas bij geen bron
            if (bron === 'geen') {
                $('.tam-extra-schemas-sectie').slideUp(200);
            } else {
                $('.tam-extra-schemas-sectie').slideDown(200);
            }

            // AJAX opslaan van bron keuze
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'tamrank_sla_schema_bron_op',
                    nonce: this.getNonce(),
                    post_id: postId,
                    bron: bron
                },
                success: function(response) {
                    if (response.success) {
                        self.updateStatusBalk(response.data.schema_type || '', bron);
                        // Update JSON-LD preview als deze zichtbaar is
                        if ($('.tam-jsonld-preview').is(':visible')) {
                            self.updateJsonLdPreview();
                        }
                    }
                }
            });
        },

        /**
         * Handle template wijziging (nieuwe UI)
         *
         * @param {string} templateId Geselecteerde template ID
         */
        handleTemplateWijziging: function(templateId) {
            var self = this;
            var postId = this.config.postId;

            // AJAX opslaan van template keuze
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'tamrank_sla_schema_template_op',
                    nonce: this.getNonce(),
                    post_id: postId,
                    template_id: templateId
                },
                success: function(response) {
                    if (response.success) {
                        // Update status balk met nieuwe schema type
                        if (response.data && response.data.schema_type) {
                            self.updateStatusBalk(response.data.schema_type, 'template');
                        }
                        // Update JSON-LD preview als deze zichtbaar is
                        if ($('.tam-jsonld-preview').is(':visible')) {
                            self.updateJsonLdPreview();
                        }
                    }
                }
            });
        },

        /**
         * Toggle JSON-LD preview (nieuwe UI)
         */
        toggleJsonLd: function() {
            var $preview = $('.tam-jsonld-preview');
            var $button = $('.tam-toggle-jsonld');

            if ($preview.is(':visible')) {
                $preview.slideUp(200);
                $button.html(
                    '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
                    '<polyline points="6 9 12 15 18 9"/></svg> ' + (this.config.teksten ? this.config.teksten.show_jsonld : 'Show JSON-LD')
                );
            } else {
                $preview.slideDown(200);
                $button.html(
                    '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
                    '<polyline points="18 15 12 9 6 15"/></svg> ' + (this.config.teksten ? this.config.teksten.hide_jsonld : 'Hide JSON-LD')
                );
                // Update preview content
                this.updateJsonLdPreview();
            }
        },

        /**
         * Update JSON-LD preview content
         */
        updateJsonLdPreview: function() {
            var self = this;
            var $preview = $('#tam-schema-preview-code');
            if (!$preview.length) return;

            var postId = this.config.postId;
            var templateId = $('#tamrank_schema_template_id').val() || '';
            var bron = $('input[name="tamrank_schema_bron"]:checked').val() || 'automatisch';

            $preview.html('<em style="color: #94a3b8;">' + (this.config.teksten ? this.config.teksten.opslaan : 'Loading...') + '</em>');

            // Als bron "geen" is, toon lege preview
            if (bron === 'geen') {
                $preview.html('<em style="color: #94a3b8;">' + (self.config.teksten ? self.config.teksten.schema_disabled : 'Schema is disabled') + '</em>');
                return;
            }

            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'tamrank_preview_schema',
                    nonce: this.config.previewNonce || this.getNonce(),
                    post_id: postId,
                    template_id: templateId,
                    bron: bron
                },
                success: function(response) {
                    if (response.success && response.data) {
                        var formatted = JSON.stringify(response.data, null, 2);
                        $preview.html('<pre style="margin: 0; white-space: pre-wrap; word-break: break-word;">' +
                            self.escapeHtml(formatted) + '</pre>');
                    } else {
                        var errorMsg = (response.data && typeof response.data === 'string') ? response.data : (self.config.teksten ? self.config.teksten.no_schema_data : 'No schema data available');
                        $preview.html('<em style="color: #94a3b8;">' + self.escapeHtml(errorMsg) + '</em>');
                    }
                },
                error: function() {
                    $preview.html('<em style="color: #ef4444;">' + (self.config.teksten ? self.config.teksten.preview_error : 'Error loading preview') + '</em>');
                }
            });
        },

        /**
         * Update de status balk (nieuwe UI)
         *
         * @param {string} schemaType Schema type
         * @param {string} bron Bron type
         */
        updateStatusBalk: function(schemaType, bron) {
            var $badges = $('.tam-schema-type-badges');
            var $bronLabel = $('.tam-schema-bron-label');

            // Update badges
            if (schemaType) {
                var badgeHtml = '<span class="tam-schema-badge">' + this.escapeHtml(schemaType) + '</span>';
                $badges.html(badgeHtml);
            } else {
                $badges.html('<span style="color: #94a3b8; font-size: 13px;">' + (this.config.teksten ? this.config.teksten.no_schema_selected : 'No schema selected') + '</span>');
            }

            // Update bron label
            var t = this.config.teksten || {};
            var bronLabels = {
                'automatisch': t.source_automatic || 'Automatic (TamRank)',
                'template': t.source_template || 'Schema Template',
                'handmatig': t.source_manual || 'Manually selected',
                'geen': t.source_disabled || 'Schema disabled'
            };
            $bronLabel.text(bronLabels[bron] || bron);
        },

        /**
         * Update advies blok status (nieuwe UI)
         *
         * @param {boolean} isActief Of het advies actief is
         */
        updateAdviesBlokStatus: function(isActief) {
            var $status = $('.tam-advies-status');
            var $button = $('.tam-advies-overnemen');

            var t = this.config.teksten || {};
            if (isActief) {
                $status.removeClass('tam-status-afwijkend').addClass('tam-status-actief')
                    .html('<span class="tam-status-dot tam-dot-actief"></span> ' + (t.active || 'Active'));
                $button.html(
                    '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
                    '<polyline points="20 6 9 17 4 12"/></svg> ' + (t.active || 'Active')
                ).addClass('tam-btn-actief').prop('disabled', true);
            } else {
                $status.removeClass('tam-status-actief').addClass('tam-status-afwijkend')
                    .html('<span class="tam-status-dot tam-dot-afwijkend"></span> ' + (t.deviates || 'Deviates'));
                $button.html(t.take_advice || 'Apply advice').removeClass('tam-btn-actief').prop('disabled', false);
            }
        },

        /**
         * Escape HTML for safe display
         *
         * @param {string} text Text to escape
         * @return {string} Escaped text
         */
        escapeHtml: function(text) {
            var map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
        },

        /**
         * Haal nonce op
         *
         * @return {string} Nonce waarde
         */
        getNonce: function() {
            return $('#tamrank_detectie_nonce').val() || this.config.nonce;
        },

        /**
         * Toon succes melding
         *
         * @param {string} bericht Melding tekst
         */
        toonSuccesMelding: function(bericht) {
            this.toonMelding(bericht, 'succes');
        },

        /**
         * Toon fout melding
         *
         * @param {string} bericht Melding tekst
         */
        toonFoutMelding: function(bericht) {
            this.toonMelding(bericht, 'fout');
        },

        /**
         * Toon melding
         *
         * @param {string} bericht Melding tekst
         * @param {string} type    Type: 'succes' of 'fout'
         */
        toonMelding: function(bericht, type) {
            var kleuren = {
                succes: {
                    bg: '#f0fdf4',
                    border: '#86efac',
                    text: '#166534'
                },
                fout: {
                    bg: '#fef2f2',
                    border: '#fca5a5',
                    text: '#991b1b'
                }
            };

            var kleur = kleuren[type] || kleuren.fout;

            // Verwijder bestaande meldingen
            $('.tam-schema-melding').remove();

            // Maak nieuwe melding
            var $melding = $('<div class="tam-schema-melding" style="' +
                'position: fixed; top: 40px; right: 20px; z-index: 100000; ' +
                'padding: 15px 20px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); ' +
                'background: ' + kleur.bg + '; border: 2px solid ' + kleur.border + '; color: ' + kleur.text + '; ' +
                'font-size: 14px; font-weight: 500; max-width: 400px;">' +
                bericht +
                '</div>');

            $('body').append($melding);

            // Animatie
            $melding.hide().fadeIn(200);

            // Auto-verberg na 4 seconden
            setTimeout(function() {
                $melding.fadeOut(200, function() {
                    $(this).remove();
                });
            }, 4000);
        }
    };

    // Initialiseer wanneer document klaar is
    $(document).ready(function() {
        TamRankSchemaDetector.init();
    });

    // Voeg CSS voor spin animatie toe
    $('<style>')
        .text('@keyframes tam-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } ' +
              '.tam-spin { animation: tam-spin 1s linear infinite; }')
        .appendTo('head');

})(jQuery);
