(function () {
    'use strict';

    /* ========================================
       FEATURE 1: Score Label Badge
       ======================================== */
    function addScoreLabels() {
        var ratings = document.querySelectorAll('.wpas-star-rating .rating');
        ratings.forEach(function (el) {
            var parentSpan = el.closest('span');
            if (!parentSpan || parentSpan.getAttribute('data-label')) return;
            var score = parseFloat(el.textContent);
            if (isNaN(score)) return;

            if (score >= 4.5) {
                parentSpan.setAttribute('data-label', 'Excellent');
                parentSpan.setAttribute('data-label-type', 'excellent');
            } else if (score >= 3.5) {
                parentSpan.setAttribute('data-label', 'Very Good');
                parentSpan.setAttribute('data-label-type', 'verygood');
            } else if (score >= 2.5) {
                parentSpan.setAttribute('data-label', 'Average');
                parentSpan.setAttribute('data-label-type', 'average');
            } else {
                parentSpan.setAttribute('data-label', 'Poor');
                parentSpan.setAttribute('data-label-type', 'poor');
            }
        });
    }

    /* ========================================
       FEATURE 2: Auto Verdict Engine
       ======================================== */
    function addAutoVerdict() {
        var blocks = document.querySelectorAll('.wpas-review-pros-cons-main');
        blocks.forEach(function (block) {
            if (block.querySelector('.wpas-auto-verdict')) return;

            var prosCount = block.querySelectorAll('.wpas-pc-pros-list li').length;
            var consCount = block.querySelectorAll('.wpas-pc-cons-list li').length;
            if (prosCount === 0 && consCount === 0) return;

            var verdict, verdictClass, verdictIcon;
            if (prosCount >= consCount * 2) {
                verdict = 'Highly Recommended'; verdictClass = 'wpas-verdict-excellent'; verdictIcon = '&#10003;&#10003;';
            } else if (prosCount > consCount) {
                verdict = 'Recommended'; verdictClass = 'wpas-verdict-good'; verdictIcon = '&#10003;';
            } else if (prosCount === consCount) {
                verdict = 'Mixed Reviews'; verdictClass = 'wpas-verdict-mixed'; verdictIcon = '&#8651;';
            } else {
                verdict = 'Not Recommended'; verdictClass = 'wpas-verdict-poor'; verdictIcon = '&#10007;';
            }

            var div = document.createElement('div');
            div.className = 'wpas-auto-verdict ' + verdictClass;
            div.innerHTML = '<span class="wpas-verdict-icon">' + verdictIcon + '</span>' +
                '<span class="wpas-verdict-text">' + verdict + '</span>' +
                '<span class="wpas-verdict-count">' + prosCount + ' pros vs ' + consCount + ' cons</span>';
            var section = block.querySelector('section') || block;
            section.appendChild(div);
        });
    }

    /* ========================================
       FEATURE 3: Review Freshness Indicator
       ======================================== */
    function addFreshnessIndicator() {
        var dates = document.querySelectorAll('.wpas-rst-date');
        dates.forEach(function (el) {
            if (el.querySelector('.wpas-freshness-badge')) return;
            var dateMatch = el.textContent.replace(/[^a-zA-Z0-9,\s]/g, '').trim().match(/(\w+\s+\d{4})/);
            if (!dateMatch) return;
            var reviewDate = new Date(dateMatch[1]);
            if (isNaN(reviewDate.getTime())) return;
            var diffDays = Math.floor((new Date() - reviewDate) / 86400000);

            var label, cls;
            if (diffDays <= 30) { label = 'Fresh'; cls = 'wpas-fresh-new'; }
            else if (diffDays <= 90) { label = 'Recent'; cls = 'wpas-fresh-recent'; }
            else if (diffDays <= 180) { label = 'Aging'; cls = 'wpas-fresh-aging'; }
            else { label = 'Needs Update'; cls = 'wpas-fresh-old'; }

            var badge = document.createElement('span');
            badge.className = 'wpas-freshness-badge ' + cls;
            badge.textContent = label;
            el.appendChild(badge);
        });
    }

    /* ========================================
       FEATURE 4: Reading Time Badge
       ======================================== */
    function addReadingTime() {
        var items = document.querySelectorAll('.wpas-rst-item');
        items.forEach(function (item) {
            if (item.querySelector('.wpas-reading-time')) return;
            var wordCount = (item.textContent || '').split(/\s+/).filter(function (w) { return w.length > 0; }).length;
            var minutes = Math.max(1, Math.ceil(wordCount / 200));
            var columns = item.querySelectorAll('.wp-block-column');
            if (columns.length < 2) return;

            var badge = document.createElement('div');
            badge.className = 'wpas-reading-time';
            badge.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 512 512"><path fill="currentColor" d="M256 0a256 256 0 1 1 0 512A256 256 0 1 1 256 0zM232 120V256c0 8 4 15.5 10.7 20l96 64c11 7.4 25.9 4.4 33.3-6.7s4.4-25.9-6.7-33.3L280 243.2V120c0-13.3-10.7-24-24-24s-24 10.7-24 24z"/></svg>' +
                '<span>' + minutes + ' min read</span>';
            columns[1].appendChild(badge);
        });
    }

    /* ========================================
       FEATURE 5: Score Breakdown Tooltip
       ======================================== */
    function addScoreTooltip() {
        var starBlocks = document.querySelectorAll('.wpas-star-rating-main');
        starBlocks.forEach(function (block) {
            if (block.getAttribute('data-tooltip-ready')) return;
            block.setAttribute('data-tooltip-ready', 'true');

            var ratingEl = block.querySelector('.rating');
            if (!ratingEl) return;
            var score = parseFloat(ratingEl.textContent);
            if (isNaN(score)) return;

            var percent = Math.round((score / 5) * 100);
            var label, labelClass;
            if (score >= 4.5) { label = 'Excellent'; labelClass = 'wpas-tt-excellent'; }
            else if (score >= 3.5) { label = 'Very Good'; labelClass = 'wpas-tt-verygood'; }
            else if (score >= 2.5) { label = 'Average'; labelClass = 'wpas-tt-average'; }
            else { label = 'Poor'; labelClass = 'wpas-tt-poor'; }

            var parentRow = block.closest('.wpas-rst-item');
            var productName = '';
            if (parentRow) {
                var logoImg = parentRow.querySelector('.wpas-rst-item-logo img');
                if (logoImg && logoImg.alt) productName = logoImg.alt;
            }

            var tooltip = document.createElement('div');
            tooltip.className = 'wpas-score-tooltip ' + labelClass;
            tooltip.innerHTML =
                '<div class="wpas-tt-header">' +
                    (productName ? '<div class="wpas-tt-product">' + productName + '</div>' : '') +
                    '<div class="wpas-tt-score-row">' +
                        '<span class="wpas-tt-score">' + score + '</span>' +
                        '<span class="wpas-tt-out-of">/5</span>' +
                        '<span class="wpas-tt-label">' + label + '</span>' +
                    '</div>' +
                '</div>' +
                '<div class="wpas-tt-bar-wrap">' +
                    '<div class="wpas-tt-bar-bg">' +
                        '<div class="wpas-tt-bar-fill" style="width:' + percent + '%"></div>' +
                    '</div>' +
                    '<div class="wpas-tt-bar-text">' + percent + '% score</div>' +
                '</div>' +
                '<div class="wpas-tt-breakdown">' +
                    '<div class="wpas-tt-row"><span>Stars filled</span><span>' + score + ' of 5</span></div>' +
                    '<div class="wpas-tt-row"><span>Rating</span><span>' + label + '</span></div>' +
                    '<div class="wpas-tt-row"><span>Percentile</span><span>' + percent + '%</span></div>' +
                '</div>' +
                '<div class="wpas-tt-footer">Hover out to close</div>';

            var wrapper = block.closest('.wp-block-column') || block.parentElement;
            if (wrapper) wrapper.style.position = 'relative';
            block.appendChild(tooltip);

            block.addEventListener('mouseenter', function () {
                tooltip.classList.add('wpas-tt-visible');
            });
            block.addEventListener('mouseleave', function () {
                tooltip.classList.remove('wpas-tt-visible');
            });
        });
    }

    /* ========================================
       FEATURE 6: Best For Auto Tags
       ======================================== */
    function addBestForTags() {
        var summaryBlocks = document.querySelectorAll('.wpas-review-summary-main');
        summaryBlocks.forEach(function (summary) {
            if (summary.getAttribute('data-bestfor-ready')) return;
            summary.setAttribute('data-bestfor-ready', 'true');

            var items = summary.querySelectorAll('.wpas-rst-item');
            if (items.length < 2) return;

            var products = [];
            items.forEach(function (item, index) {
                var ratingEl = item.querySelector('.wpas-star-rating .rating');
                var score = ratingEl ? parseFloat(ratingEl.textContent) : 0;
                products.push({ element: item, score: score, index: index });
            });

            var sorted = products.slice().sort(function (a, b) { return b.score - a.score; });
            var highestScore = sorted[0].score;

            products.forEach(function (product) {
                if (product.element.querySelector('.wpas-bestfor-tag')) return;

                var tags = [];

                if (product.index === 0 && product.score === highestScore && product.score >= 4.0) {
                    tags.push({ text: "Editor's Choice", cls: 'wpas-bf-editors' });
                } else if (product.score === highestScore && product.score >= 4.5 && product.index !== 0) {
                    tags.push({ text: 'Top Rated', cls: 'wpas-bf-toprated' });
                }

                if (product.score >= 4.5 && tags.length === 0) {
                    tags.push({ text: 'Highly Rated', cls: 'wpas-bf-highlyrated' });
                }

                if (product.index === products.length - 1 && product.score >= 2.5 && product.score < highestScore) {
                    tags.push({ text: 'Budget Pick', cls: 'wpas-bf-budget' });
                }

                if (product.index > 0 && product.index < products.length - 1 && product.score >= 3.5 && tags.length === 0) {
                    tags.push({ text: 'Great Alternative', cls: 'wpas-bf-alternative' });
                }

                if (product.score < 2.5 && product.score > 0 && tags.length === 0) {
                    tags.push({ text: 'Consider Others', cls: 'wpas-bf-consider' });
                }

                if (tags.length > 0) {
                    var tagContainer = document.createElement('div');
                    tagContainer.className = 'wpas-bestfor-tag-wrap';
                    tags.forEach(function (tag) {
                        var span = document.createElement('span');
                        span.className = 'wpas-bestfor-tag ' + tag.cls;
                        span.textContent = tag.text;
                        tagContainer.appendChild(span);
                    });

                    product.element.style.position = 'relative';
                    product.element.appendChild(tagContainer);
                }
            });
        });
    }

    /* ========================================
       FEATURE 7: Animated Score Counter
       ======================================== */
    function animateScoreCounters() {
        var ratings = document.querySelectorAll('.wpas-star-rating .rating');
        ratings.forEach(function (el) {
            if (el.getAttribute('data-animated')) return;
            el.setAttribute('data-animated', 'true');

            var finalScore = parseFloat(el.textContent);
            if (isNaN(finalScore)) return;

            var startAnimation = function () {
                var duration = 1500;
                var startTime = null;

                function step(timestamp) {
                    if (!startTime) startTime = timestamp;
                    var progress = Math.min((timestamp - startTime) / duration, 1);
                    var eased = 1 - Math.pow(1 - progress, 3);
                    var currentValue = finalScore * eased;
                    el.textContent = currentValue.toFixed(1);

                    if (progress < 1) {
                        requestAnimationFrame(step);
                    } else {
                        el.textContent = finalScore;
                    }
                }
                requestAnimationFrame(step);
            };

            if ('IntersectionObserver' in window) {
                var io = new IntersectionObserver(function (entries) {
                    entries.forEach(function (entry) {
                        if (entry.isIntersecting) {
                            startAnimation();
                            io.unobserve(entry.target);
                        }
                    });
                }, { threshold: 0.3 });
                io.observe(el);
            } else {
                startAnimation();
            }
        });
    }

    /* ========================================
       FEATURE 8: Copy Product Review Link
       ======================================== */
    function addCopyReviewLink() {
        var items = document.querySelectorAll('.wpas-rst-item');
        items.forEach(function (item, index) {
            if (item.querySelector('.wpas-copy-review-link')) return;

            var anchorId = 'review-product-' + (index + 1);
            item.setAttribute('id', anchorId);

            var readingTime = item.querySelector('.wpas-reading-time');
            var columns = item.querySelectorAll('.wp-block-column');
            var targetCol = columns.length >= 2 ? columns[1] : null;
            if (!targetCol) return;

            var btn = document.createElement('button');
            btn.className = 'wpas-copy-review-link';
            btn.innerHTML = '<span class="wpas-crl-icon">&#128279;</span> Copy Link';

            if (readingTime) {
                readingTime.appendChild(btn);
            } else {
                targetCol.appendChild(btn);
            }

            btn.addEventListener('click', function (e) {
                e.preventDefault();
                e.stopPropagation();
                var url = window.location.href.split('#')[0] + '#' + anchorId;
                var linkBtn = this;

                if (navigator.clipboard && window.isSecureContext) {
                    navigator.clipboard.writeText(url).then(function () {
                        showCopied(linkBtn);
                    });
                } else {
                    var ta = document.createElement('textarea');
                    ta.value = url;
                    ta.style.position = 'fixed';
                    ta.style.left = '-9999px';
                    document.body.appendChild(ta);
                    ta.select();
                    try {
                        document.execCommand('copy');
                        showCopied(linkBtn);
                    } catch (err) {
                        linkBtn.innerHTML = '<span class="wpas-crl-icon">&#10007;</span> Failed';
                    }
                    document.body.removeChild(ta);
                }
            });
        });
    }

    function showCopied(btn) {
        var originalHTML = btn.innerHTML;
        btn.innerHTML = '<span class="wpas-crl-icon">&#10003;</span> Copied!';
        btn.classList.add('wpas-crl-copied');
        setTimeout(function () {
            btn.innerHTML = originalHTML;
            btn.classList.remove('wpas-crl-copied');
        }, 2000);
    }

    /* ========================================
       FEATURE 9: Review Table of Contents
       ======================================== */
    function addReviewTOC() {
        var summaryBlocks = document.querySelectorAll('.wpas-review-summary-main');
        summaryBlocks.forEach(function (summary) {
            if (summary.querySelector('.wpas-review-toc')) return;

            var items = summary.querySelectorAll('.wpas-rst-item');
            if (items.length < 2) return;

            var tocHTML = '<div class="wpas-review-toc">';
            tocHTML += '<div class="wpas-toc-header"><span class="wpas-toc-title">Quick Navigation</span><span class="wpas-toc-count">' + items.length + ' products reviewed</span></div>';
            tocHTML += '<div class="wpas-toc-items">';

            items.forEach(function (item, index) {
                var anchorId = 'review-product-' + (index + 1);
                item.setAttribute('id', anchorId);

                var productName = '';
                var logoImg = item.querySelector('.wpas-rst-item-logo img');
                if (logoImg && logoImg.alt) productName = logoImg.alt;
                if (!productName) {
                    var urlPara = item.querySelector('.wpas-rst-url');
                    if (urlPara) productName = urlPara.textContent.replace('www.', '').replace('.com', '').trim();
                }
                if (!productName) productName = 'Product ' + (index + 1);

                var ratingEl = item.querySelector('.wpas-star-rating .rating');
                var score = ratingEl ? parseFloat(ratingEl.textContent) : 0;
                var scoreDisplay = score > 0 ? score.toFixed(1) : '--';

                var scoreClass = '';
                if (score >= 4.5) scoreClass = 'wpas-toc-excellent';
                else if (score >= 3.5) scoreClass = 'wpas-toc-good';
                else if (score >= 2.5) scoreClass = 'wpas-toc-average';
                else scoreClass = 'wpas-toc-poor';

                var posLabel = index === 0 ? '1st' : index === 1 ? '2nd' : index === 2 ? '3rd' : (index + 1) + 'th';

                tocHTML += '<a href="#' + anchorId + '" class="wpas-toc-item" data-target="' + anchorId + '">';
                tocHTML += '<span class="wpas-toc-pos">' + posLabel + '</span>';
                tocHTML += '<span class="wpas-toc-name">' + productName + '</span>';
                tocHTML += '<span class="wpas-toc-score ' + scoreClass + '">' + scoreDisplay + '</span>';
                tocHTML += '</a>';
            });

            tocHTML += '</div></div>';

            var firstItem = summary.querySelector('.wpas-rst-item');
            if (firstItem) {
                var tocDiv = document.createElement('div');
                tocDiv.innerHTML = tocHTML;
                firstItem.parentElement.insertBefore(tocDiv.firstChild, firstItem);
            }

            summary.querySelectorAll('.wpas-toc-item').forEach(function (link) {
                link.addEventListener('click', function (e) {
                    e.preventDefault();
                    var targetId = this.getAttribute('data-target');
                    var target = document.getElementById(targetId);
                    if (target) {
                        target.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        target.classList.add('wpas-toc-highlight');
                        setTimeout(function () {
                            target.classList.remove('wpas-toc-highlight');
                        }, 2000);
                    }
                });
            });
        });
    }

    /* ========================================
       RUN ALL FEATURES
       ======================================== */
    function runAll() {
        addScoreLabels();
        addAutoVerdict();
        addFreshnessIndicator();
        addReadingTime();
        addScoreTooltip();
        addBestForTags();
        animateScoreCounters();
        addCopyReviewLink();
        addReviewTOC();
    }

    /* ========================================
       INIT
       ======================================== */
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', runAll);
    } else {
        runAll();
    }

    window.addEventListener('load', function () {
        setTimeout(runAll, 1500);
        setTimeout(runAll, 3000);
    });

    // Watch for editor changes (React re-renders)
    var watchTimer;
    var observer = new MutationObserver(function () {
        clearTimeout(watchTimer);
        watchTimer = setTimeout(runAll, 800);
    });

    function startWatching() {
        var target = document.querySelector('.editor-styles-wrapper') ||
                     document.querySelector('.block-editor-block-list__layout') ||
                     document.querySelector('#editor') ||
                     document.body;
        observer.observe(target, { childList: true, subtree: true });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', startWatching);
    } else {
        startWatching();
    }

})();