/**
 * ProRank SEO Bulk Edit Integration
 *
 * Handles quick edit prefill from data attributes and real-time character counting.
 */
(function($) {
    'use strict';

    /**
     * Quick edit prefill from column data attributes
     */
    $('#the-list').on('click', '.editinline', function() {
        var $row = $(this).closest('tr');
        var postId = $row.attr('id').replace('post-', '');

        // Get values from data attributes set in PHP display methods
        var $titleSpan = $row.find('.column-prorank_seo_title .meta-text');
        var $descSpan = $row.find('.column-prorank_seo_desc .meta-text');
        var $keywordBadge = $row.find('.prorank-keyword-badge.set');
        var $inlineState = $row.find('.prorank-inline-seo-state');

        var title = $titleSpan.data('full-value') || '';
        var desc = $descSpan.data('full-value') || '';
        var keyword = $keywordBadge.length ? $keywordBadge.attr('title') || $keywordBadge.text().trim() : '';
        var canonical = $inlineState.data('canonical-url') || '';
        var robots = String($inlineState.data('meta-robots') || '').split(',').filter(Boolean);

        // Wait for WordPress to render the quick edit row
        setTimeout(function() {
            var $editRow = $('#edit-' + postId);

            if ($editRow.length) {
                // Prefill the fields
                $editRow.find('input[name="prorank_focus_keyword"]').val(keyword);
                $editRow.find('input[name="prorank_seo_title"]').val(title).trigger('input');
                $editRow.find('textarea[name="prorank_seo_description"]').val(desc).trigger('input');
                $editRow.find('input[name="prorank_seo_canonical_url"]').val(canonical);
                $editRow.find('input[name="prorank_meta_robots[]"]').prop('checked', false);
                robots.forEach(function(robot) {
                    $editRow.find('input[name="prorank_meta_robots[]"][value="' + robot + '"]').prop('checked', true);
                });
            }
        }, 50);
    });

    /**
     * Real-time character counter for quick edit fields
     */
    $(document).on('input', '.prorank-quick-edit-fields input[name="prorank_seo_title"]', function() {
        updateCharCount($(this), 60);
    });

    $(document).on('input', '.prorank-quick-edit-fields textarea[name="prorank_seo_description"]', function() {
        updateCharCount($(this), 160);
    });

    /**
     * Update character count display
     *
     * @param {jQuery} $input The input or textarea element.
     * @param {number} max Maximum recommended characters.
     */
    function updateCharCount($input, max) {
        var len = $input.val().length;
        var $counter = $input.siblings('.prorank-char-counter');

        if (!$counter.length) {
            $counter = $('<span class="prorank-char-counter"></span>');
            $input.after($counter);
        }

        $counter.text(len + '/' + max);
        $counter.removeClass('warning over');

        if (len > max) {
            $counter.addClass('over');
        } else if (len > max * 0.8) {
            $counter.addClass('warning');
        }
    }

    /**
     * Initialize character counters when quick edit fields are added
     */
    $(document).on('DOMNodeInserted', function(e) {
        var $target = $(e.target);

        if ($target.hasClass('inline-edit-row') || $target.find('.prorank-quick-edit-fields').length) {
            // Initialize character counters
            $target.find('.prorank-quick-edit-fields input[name="prorank_seo_title"]').each(function() {
                updateCharCount($(this), 60);
            });
            $target.find('.prorank-quick-edit-fields textarea[name="prorank_seo_description"]').each(function() {
                updateCharCount($(this), 160);
            });
        }
    });

    /**
     * Initialize bulk edit page helpers
     */
    $(function() {
        initBulkEditPage();
    });

    /**
     * Set up live feedback for the bulk edit page.
     */
    function initBulkEditPage() {
        var $page = $('.prorank-bulk-edit-page');
        if (!$page.length) {
            return;
        }

        $page.find('.prorank-bulk-edit-field[data-max]').each(function() {
            updateBulkField($(this));
        });

        $page.on('input', '.prorank-bulk-input', function() {
            var $field = $(this).closest('.prorank-bulk-edit-field');
            if ($field.data('max')) {
                updateBulkField($field);
            }
        });
    }

    /**
     * Update progress bar, badge, and count for a bulk edit field.
     *
     * @param {jQuery} $field Field wrapper.
     */
    function updateBulkField($field) {
        var $input = $field.find('.prorank-bulk-input');
        if (!$input.length) {
            return;
        }

        var val = $input.val() || '';
        var len = $.trim(val).length;
        var max = parseInt($field.data('max'), 10) || 0;
        var optimalMin = parseInt($field.data('optimalMin'), 10) || 0;
        var optimalMax = parseInt($field.data('optimalMax'), 10) || max;
        var acceptableMin = parseInt($field.data('acceptableMin'), 10) || 0;
        var acceptableMax = parseInt($field.data('acceptableMax'), 10) || max;

        var $bar = $field.find('.prorank-progress-bar');
        var $fill = $bar.find('.progress-fill');
        if (!$bar.length || !$fill.length || max <= 0) {
            return;
        }

        var percent = Math.min(100, (len / max) * 100);
        $fill.css('width', percent + '%');

        var $count = $field.find('.prorank-char-count');
        if ($count.length) {
            $count.text(len + '/' + max);
        }

        $bar.removeClass('good warning over empty');
        if (len === 0) {
            $bar.addClass('empty');
        } else if (len < acceptableMin || len > acceptableMax) {
            $bar.addClass('over');
        } else if (len >= optimalMin && len <= optimalMax) {
            $bar.addClass('good');
        } else {
            $bar.addClass('warning');
        }

    }

})(jQuery);
