/**
 * Elementor frontend handler for the Grid Listing widget.
 * Handles Text Limit feature: truncates excerpt by character or word count,
 * with Show More / Show Less toggle.
 */
(function ($) {
    "use strict";

    var CaptwikiGridListingHandler = function ($scope, $) {

        var $widget = $scope.find('.captwiki-grid-listing');

        if (!$widget.length) {
            return;
        }

        // Read settings passed via data attribute from PHP
        var settings = $widget.data('widget-settings') || {};

        var textLimitEnabled = settings.text_limit === true || settings.text_limit === 'yes';
        var limitOn = settings.limit_on || 'character'; // 'character' or 'word'
        var limitCount = parseInt(settings.limit_count, 10) || 100;
        var moreText = settings.more_text || 'Read More';
        var lessText = settings.less_text || 'Read Less';

        if (!textLimitEnabled) {
            return;
        }

        /**
         * Truncate text by character count.
         *
         * @param {string} text
         * @param {number} limit
         * @return {string}
         */
        function truncateByCharacter(text, limit) {
            if (text.length <= limit) {
                return text;
            }
            // Break at last space before limit to avoid cutting a word mid-way
            var truncated = text.substring(0, limit);
            var lastSpace = truncated.lastIndexOf(' ');
            return (lastSpace > 0 ? truncated.substring(0, lastSpace) : truncated) + '...';
        }

        /**
         * Truncate text by word count.
         *
         * @param {string} text
         * @param {number} limit
         * @return {string}
         */
        function truncateByWord(text, limit) {
            var words = text.trim().split(/\s+/);
            if (words.length <= limit) {
                return text;
            }
            return words.slice(0, limit).join(' ') + '...';
        }

        // Apply truncation to every excerpt paragraph inside this widget
        $widget.find('.captwiki-text p').each(function () {

            var $p = $(this);
            var fullText = $p.text().trim();

            if (!fullText) {
                return;
            }

            var shortText;
            if (limitOn === 'word') {
                shortText = truncateByWord(fullText, limitCount);
            } else {
                shortText = truncateByCharacter(fullText, limitCount);
            }

            // Nothing to truncate
            if (shortText === fullText) {
                return;
            }

            // Build the toggle markup
            var $shortSpan = $('<span class="captwiki-excerpt-short"></span>').text(shortText);
            var $fullSpan = $('<span class="captwiki-excerpt-full" style="display:none;"></span>').text(fullText);

            var $toggle = $(
                '<a href="#" class="captwiki-read-more-toggle" aria-expanded="false"></a>'
            ).text(moreText);

            $p.empty()
                .append($shortSpan)
                .append($fullSpan)
                .append(' ')
                .append($toggle);

            // Toggle click handler
            $toggle.on('click', function (e) {
                e.preventDefault();

                var isExpanded = $toggle.attr('aria-expanded') === 'true';

                if (isExpanded) {
                    $fullSpan.hide();
                    $shortSpan.show();
                    $toggle.text(moreText).attr('aria-expanded', 'false');
                } else {
                    $shortSpan.hide();
                    $fullSpan.show();
                    $toggle.text(lessText).attr('aria-expanded', 'true');
                }
            });
        });
    };

    window.addEventListener('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/captwiki-grid-listing.default',
            CaptwikiGridListingHandler
        );
    });

})(jQuery);
