jQuery(document).ready(function ($) {

    /**
     * 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; });
    }

    // Initialize meta box functionality
    initMetaBoxes();

    /**
     * Initialize all meta box features
     */
    function initMetaBoxes() {
        initCharacterCounters();
        initRealTimePreview();
        initFormValidation();
    }

    /**
     * Initialize character counters for meta fields
     */
    function initCharacterCounters() {
        // Meta title counter
        $('#_tam_rank_meta_title').on('input', function () {
            updateCharacterCounter($(this), 60, 30);
        }).trigger('input');

        // Meta description counter
        $('#_tam_rank_meta_description').on('input', function () {
            updateCharacterCounter($(this), 160, 120);
        }).trigger('input');
    }

    /**
     * Update character counter for field
     */
    function updateCharacterCounter(field, maxLength, minLength) {
        const length = field.val().length;
        var group = field.closest('.tam-field-group');
        let counter = group.length ? group.find('.char-counter').first() : field.siblings('.char-counter').first();

        if (counter.length === 0) {
            counter = $('<div class="char-counter"></div>');
            var footer = field.siblings('.tr-field-card__footer');
            if (footer.length) {
                footer.prepend(counter);
            } else {
                field.after(counter);
            }
        }

        let message = length + ' ' + (tamRankMeta.strings.chars_count_suffix || 'characters');
        let className = 'char-counter ';

        if (length < minLength) {
            message += ' (' + fillPlaceholder(tamRankMeta.strings.chars_too_short || 'too short - minimum %d', '%d', minLength) + ')';
            className += 'tam-warning';
        } else if (length > maxLength) {
            message += ' (' + fillPlaceholder(tamRankMeta.strings.chars_too_long || 'too long - maximum %d', '%d', maxLength) + ')';
            className += 'tam-error';
        } else {
            message += ' (' + (tamRankMeta.strings.chars_good || 'good') + ')';
            className += 'tam-success';
        }

        counter.html(message).attr('class', className);
    }

    /**
     * Initialize real-time Google preview
     */
    function initRealTimePreview() {
        // Update preview when fields change
        $('#_tam_rank_meta_title').on('input', updateGooglePreview);
        $('#_tam_rank_meta_description').on('input', updateGooglePreview);
        $('#title').on('input', updateGooglePreview);

        // Initial preview update
        updateGooglePreview();
    }

    /**
     * Update Google search preview
     */
    function updateGooglePreview() {
        const metaTitle = $('#_tam_rank_meta_title').val();
        const postTitle = $('#title').val();
        const metaDescription = $('#_tam_rank_meta_description').val();

        const displayTitle = metaTitle || postTitle || 'Untitled';
        const displayDescription = metaDescription || 'No description available';

        $('#preview-title').text(truncateText(displayTitle, 60));
        $('#preview-description').text(truncateText(displayDescription, 160));
    }

    /**
     * Truncate text to specified length
     */
    function truncateText(text, length) {
        if (text.length <= length) {
            return text;
        }
        return text.substring(0, length - 3) + '...';
    }

    /**
     * Initialize form validation
     */
    function initFormValidation() {
        var bypassValidation = false;
        $('#post').on('submit', function (e) {
            if (bypassValidation) {
                bypassValidation = false;
                return;
            }
            var errors = validateMetaFields();
            if (errors.length === 0) return;

            e.preventDefault();
            var form = this;

            if (window.TamRank && typeof window.TamRank.confirm === 'function') {
                window.TamRank.confirm({
                    title: tamRankMeta.strings.seo_warnings_title || 'There are some SEO warnings:',
                    message: errors.join('\n') + '\n\n' + (tamRankMeta.strings.proceed_confirmation || 'Do you want to proceed anyway?'),
                    confirmLabel: tamRankMeta.strings.proceed || 'Proceed',
                    cancelLabel: tamRankMeta.strings.cancel || 'Cancel',
                    variant: 'default'
                }).then(function (ok) {
                    if (!ok) return;
                    bypassValidation = true;
                    form.submit();
                });
            } else {
                // Fallback if global confirm dialog isn't loaded (shouldn't happen on admin pages)
                if (confirm(errors.join('\n'))) { bypassValidation = true; form.submit(); }
            }
        });
    }

    /**
     * Validate meta fields
     */
    function validateMetaFields() {
        const errors = [];

        const metaTitle = $('#_tam_rank_meta_title').val();
        const metaDescription = $('#_tam_rank_meta_description').val();
        const focusKeyword = $('#_tam_rank_focus_keyword').val();

        // Check meta title
        if (metaTitle.length < 30) {
            errors.push('• ' + (tamRankMeta.strings.meta_title_too_short || 'Meta title is too short'));
        } else if (metaTitle.length > 60) {
            errors.push('• ' + (tamRankMeta.strings.meta_title_too_long || 'Meta title is too long'));
        }

        // Check meta description
        if (metaDescription.length < 120) {
            errors.push('• ' + (tamRankMeta.strings.meta_desc_too_short || 'Meta description is too short'));
        } else if (metaDescription.length > 160) {
            errors.push('• ' + (tamRankMeta.strings.meta_desc_too_long || 'Meta description is too long'));
        }

        // Check focus keyword in title
        if (focusKeyword && metaTitle && !metaTitle.toLowerCase().includes(focusKeyword.toLowerCase())) {
            errors.push('• ' + (tamRankMeta.strings.focus_keyword_not_in_title || 'Focus keyword missing in title'));
        }

        // Check focus keyword in description
        if (focusKeyword && metaDescription && !metaDescription.toLowerCase().includes(focusKeyword.toLowerCase())) {
            errors.push('• ' + (tamRankMeta.strings.focus_keyword_not_in_desc || 'Focus keyword missing in description'));
        }

        return errors;
    }


    /**
     * Toggle secondary keywords visibility
     */
    (function () {
        var toggle = document.getElementById('tr-secondary-kw-toggle');
        var fields = document.getElementById('tr-secondary-kw-fields');

        if (toggle && fields) {
            toggle.addEventListener('change', function () {
                fields.classList.toggle('tr-secondary-kw__fields--visible', toggle.checked);
            });
        }
    })();

    /**
     * Debounce function
     */
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func.apply(this, args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

});