/**
 *
 * @package pawwell
 */

(function ($) {
    'use strict';

    /**
     * Toggle tag pill active state
     */
    window.toggleTag = function (el) {
        el.classList.toggle('active');
    };

    /**
     * Blog Card Fade-In Animation
     */
    function initBlogCardAnimations() {
        var cards = document.querySelectorAll('.blog-card');
        if (!cards.length) return;

        cards.forEach(function (card, index) {
            card.style.animationDelay = (index * 0.08) + 's';
        });
    }

    /**
     * Fade-in Animation
     */
    function initFadeInAnimations() {
        var fadeEls = document.querySelectorAll('.fade-in');
        if (!fadeEls.length) return;

        if ('IntersectionObserver' in window) {
            var observer = new IntersectionObserver(function (entries) {
                entries.forEach(function (entry) {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('visible');
                        observer.unobserve(entry.target);
                    }
                });
            }, { threshold: 0.1 });

            fadeEls.forEach(function (el) {
                observer.observe(el);
            });
        } else {
            // Fallback
            fadeEls.forEach(function (el) {
                el.classList.add('visible');
            });
        }
    }

    /**
     * Share Functions
     */
    window.pawwell_share_twitter = function () {
        var url = encodeURIComponent(window.location.href);
        var text = encodeURIComponent(document.title);
        window.open('https://x.com/intent/tweet?url=' + url + '&text=' + text, '_blank', 'width=600,height=400');
    };

    window.pawwell_share_linkedin = function () {
        var url = encodeURIComponent(window.location.href);
        window.open('https://www.linkedin.com/sharing/share-offsite/?url=' + url, '_blank', 'width=600,height=400');
    };

    window.pawwell_share_facebook = function () {
        var url = encodeURIComponent(window.location.href);
        window.open('https://www.facebook.com/sharer/sharer.php?u=' + url, '_blank', 'width=600,height=400');
    };

    window.pawwell_share_instagram = function () {
        var url = window.location.href;
        if (navigator.clipboard) {
            navigator.clipboard.writeText(url).then(function () {
                alert('Link copied! Share it on Instagram.');
            });
        } else {
            alert('Copy this link to share on Instagram: ' + url);
        }
    };

    window.pawwell_share_pinterest = function () {
        var url = encodeURIComponent(window.location.href);
        var description = encodeURIComponent(document.title);
        var media = '';
        var heroImg = document.querySelector('.article-hero img');
        if (heroImg) {
            media = encodeURIComponent(heroImg.src);
        }
        window.open('https://pinterest.com/pin/create/button/?url=' + url + '&description=' + description + '&media=' + media, '_blank', 'width=600,height=400');
    };

    window.pawwell_share_email = function () {
        var url = window.location.href;
        var subject = encodeURIComponent(document.title);
        var body = encodeURIComponent('Check out this article: ' + url);
        window.location.href = 'mailto:?subject=' + subject + '&body=' + body;
    };

    window.pawwell_copy_link = function (btn) {
        var url = window.location.href;
        if (navigator.clipboard) {
            navigator.clipboard.writeText(url).then(function () {
                showCopyFeedback(btn);
            });
        } else {
            var input = document.createElement('input');
            input.value = url;
            document.body.appendChild(input);
            input.select();
            document.execCommand('copy');
            document.body.removeChild(input);
            showCopyFeedback(btn);
        }
    };

    function showCopyFeedback(btn) {
        var original = btn.innerHTML;
        btn.innerHTML = '<svg viewBox="0 0 24 24" width="14" height="14"><path d="M20 6L9 17l-5-5" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg> Copied!';
        btn.style.color = 'var(--brand-accent)';
        btn.style.borderColor = 'var(--brand-accent)';
        setTimeout(function () {
            btn.innerHTML = original;
            btn.style.color = '';
            btn.style.borderColor = '';
        }, 2000);
    }

    
    function getPostIdFromURL() {
        var body = document.querySelector('body');
        var classes = body.className;
        var match = classes.match(/postid-(\d+)/);
        return match ? parseInt(match[1]) : null;
    }


    /**
     * Delegated event listeners for data-attribute triggers
     */
    function initDelegatedEvents() {
        // Share buttons
        $(document).on('click', '[data-share]', function (e) {
            e.preventDefault();
            var platform = $(this).data('share');
            if (typeof window['pawwell_share_' + platform] === 'function') {
                window['pawwell_share_' + platform]();
            }
        });

        // Tag toggle (data-toggle-tag)
        $(document).on('click', '[data-toggle-tag]', function () {
            window.toggleTag(this);
        });

        // Comment like (data-like-comment)
        $(document).on('click', '[data-like-comment]', function () {
            window.pawwell_like_comment(this);
        });
    }

    /**
     * Reading progress bar for single posts.
     */
    function initReadingProgress() {
        var bar = document.getElementById('readingProgress');
        var article = document.getElementById('articleBody');
        if (!bar || !article) {
            return;
        }
        var fill = bar.querySelector('span');

        function update() {
            var rect = article.getBoundingClientRect();
            var total = rect.height - window.innerHeight;
            var scrolled = -rect.top;
            var progress = total > 0 ? Math.min(Math.max(scrolled / total, 0), 1) : 0;
            fill.style.width = (progress * 100) + '%';
        }

        window.addEventListener('scroll', update, { passive: true });
        window.addEventListener('resize', update, { passive: true });
        update();
    }

    /**
     * Auto-generate a Table of Contents from <h2> in the article
     * and wire up scrollspy + smooth scrolling.
     */
    function initTableOfContents() {
        var tocList = document.getElementById('tocList');
        var widget = document.getElementById('tocWidget');
        if (!tocList || !widget) {
            return;
        }
        var article = document.getElementById('articleBody');
        if (!article) {
            return;
        }

        var headings = article.querySelectorAll('.article-content h2');
        if (!headings.length) {
            widget.style.display = 'none';
            return;
        }

        var links = [];
        headings.forEach(function (heading, index) {
            if (!heading.id) {
                heading.id = 'toc-heading-' + (index + 1);
            }
            var num = String(index + 1).padStart(2, '0');
            var li = document.createElement('li');
            var a = document.createElement('a');
            a.setAttribute('href', '#' + heading.id);
            a.innerHTML = '<span class="toc-num">' + num + '</span><span>' + (heading.textContent || '') + '</span>';
            a.addEventListener('click', function (e) {
                e.preventDefault();
                var top = heading.getBoundingClientRect().top + window.scrollY - 100;
                window.scrollTo({ top: top, behavior: 'smooth' });
            });
            li.appendChild(a);
            tocList.appendChild(li);
            links.push(a);
        });

        function updateScrollSpy() {
            var scrollPos = window.scrollY + 130;
            var activeIndex = -1;
            headings.forEach(function (h, i) {
                if (h.offsetTop <= scrollPos) {
                    activeIndex = i;
                }
            });
            links.forEach(function (link, i) {
                link.classList.toggle('active', i === activeIndex);
            });
        }

        window.addEventListener('scroll', updateScrollSpy, { passive: true });
        updateScrollSpy();
    }

    /**
     * Copy permalink to clipboard.
     */
    function initCopyLink() {
        var btn = document.getElementById('copyLink');
        if (!btn) {
            return;
        }
        btn.addEventListener('click', function () {
            var permalink = btn.getAttribute('data-permalink') || window.location.href;
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(permalink).then(function () {
                    showCopyFeedback(btn);
                }, function () {
                    fallbackCopy(permalink);
                    showCopyFeedback(btn);
                });
            } else {
                fallbackCopy(permalink);
                showCopyFeedback(btn);
            }
        });
    }

    function fallbackCopy(text) {
        var tmp = document.createElement('textarea');
        tmp.value = text;
        tmp.style.position = 'fixed';
        tmp.style.opacity = '0';
        document.body.appendChild(tmp);
        tmp.select();
        try {
            document.execCommand('copy');
        } catch (err) {}
        document.body.removeChild(tmp);
    }

    function showCopyFeedback(btn) {
        var original = btn.innerHTML;
        btn.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 13l4 4L19 7"/></svg>';
        btn.style.background = 'var(--terracotta)';
        btn.style.color = '#fff';
        setTimeout(function () {
            btn.innerHTML = original;
            btn.style.background = '';
            btn.style.color = '';
        }, 1800);
    }

    /**
     * Initialize on DOM ready
     */
    $(document).ready(function () {
        initBlogCardAnimations();
        initFadeInAnimations();
        initDelegatedEvents();
        initReadingProgress();
        initTableOfContents();
        initCopyLink();
    });

})(jQuery);
