/**
 * ==========================================================================
 * TWITTER DIGEST - APPLICATION
 * Main JavaScript for the Twitter Digest app
 *
 * Features:
 * - Theme detection (dark/light mode)
 * - Staggered content animations
 * - External link handling
 * - Expandable feedback form
 * ==========================================================================
 */

(function() {
    'use strict';

    /* ======================================================================
       CONFIGURATION
       Global settings and constants
       ====================================================================== */

    const CONFIG = {
        // Selectors
        selectors: {
            contentItem: '.content-item',
            animationSection: '[data-animation-section]',
            externalLink: 'a[href^="http"]',
            feedback: '[data-feedback]',
            feedbackTrigger: '[data-feedback-trigger]',
            feedbackContent: '[data-feedback-content]',
            feedbackTextarea: '.feedback__textarea',
            feedbackCancel: '[data-feedback-cancel]'
        },

        // CSS classes
        classes: {
            expanded: 'is-expanded',
            open: 'is-open'
        },

        // Timing
        timing: {
            focusDelay: 300 // ms delay before focusing textarea
        }
    };


    /* ======================================================================
       THEME SYSTEM
       Auto-detects system preference and listens for changes
       ====================================================================== */

    const ThemeManager = {
        /**
         * Initialize theme detection
         */
        init() {
            const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

            // Apply initial theme (before tweets render)
            this.applyTheme(mediaQuery.matches, false);

            // Listen for system theme changes
            mediaQuery.addEventListener('change', (e) => this.applyTheme(e.matches, true));
        },

        /**
         * Apply theme to document and Twitter embeds
         * @param {boolean} isDark - Whether dark mode is active
         * @param {boolean} reloadTweets - Whether to reload Twitter widgets
         */
        applyTheme(isDark, reloadTweets = false) {
            const theme = isDark ? 'dark' : 'light';

            // Update document theme
            document.documentElement.dataset.theme = theme;

            // Update Twitter meta tag
            const twitterThemeMeta = document.querySelector('meta[name="twitter:widgets:theme"]');
            if (twitterThemeMeta) {
                twitterThemeMeta.setAttribute('content', theme);
            }

            // Update all Twitter blockquotes with data-theme attribute
            const tweetBlockquotes = document.querySelectorAll('blockquote.twitter-tweet');
            tweetBlockquotes.forEach(blockquote => {
                blockquote.setAttribute('data-theme', theme);
            });

            // Reload Twitter widgets if they've already been rendered
            if (reloadTweets && typeof twttr !== 'undefined' && twttr.widgets) {
                // Find all tweet containers
                const tweetContainers = document.querySelectorAll('.tweet-container');

                tweetContainers.forEach(container => {
                    // Get stored tweet URL
                    const tweetUrl = container.getAttribute('data-tweet-url');
                    if (!tweetUrl) return;

                    // Clear container contents (removes rendered iframe)
                    container.innerHTML = '';

                    // Recreate the blockquote with new theme
                    const blockquote = document.createElement('blockquote');
                    blockquote.className = 'twitter-tweet';
                    blockquote.setAttribute('data-theme', theme);

                    const link = document.createElement('a');
                    link.href = tweetUrl;
                    blockquote.appendChild(link);

                    container.appendChild(blockquote);
                });

                // Reload all widgets
                twttr.widgets.load();

                console.log(`[Theme] Switched to ${theme} mode, reloading ${tweetContainers.length} tweets...`);
            }
        },

        /**
         * Get current theme
         * @returns {string} Current theme ('dark' or 'light')
         */
        getCurrentTheme() {
            return document.documentElement.dataset.theme || 'light';
        },

        /**
         * Toggle theme manually
         */
        toggle() {
            const isDark = this.getCurrentTheme() === 'dark';
            this.applyTheme(!isDark, true);
        }
    };


    /* ======================================================================
       ANIMATION SYSTEM
       Assigns staggered animation delays based on DOM order
       ====================================================================== */

    const AnimationManager = {
        /**
         * Initialize animations for content items
         */
        init() {
            const items = document.querySelectorAll(CONFIG.selectors.contentItem);
            const sections = document.querySelectorAll(CONFIG.selectors.animationSection);

            if (sections.length > 0) {
                // Section-based: reset index for each section
                this.initSectionAnimations(sections, items);
            } else {
                // Global: sequential index across entire page
                this.initGlobalAnimations(items);
            }
        },

        /**
         * Initialize section-based animations
         * @param {NodeList} sections - Animation section containers
         * @param {NodeList} allItems - All content items
         */
        initSectionAnimations(sections, allItems) {
            // Animate items within sections
            sections.forEach(section => {
                const sectionItems = section.querySelectorAll(CONFIG.selectors.contentItem);
                sectionItems.forEach((item, index) => {
                    this.setAnimationIndex(item, index);
                });
            });

            // Handle items outside sections
            let globalIndex = 0;
            allItems.forEach(item => {
                if (!item.closest(CONFIG.selectors.animationSection)) {
                    this.setAnimationIndex(item, globalIndex);
                    globalIndex++;
                }
            });
        },

        /**
         * Initialize global animations (no sections)
         * @param {NodeList} items - Content items to animate
         */
        initGlobalAnimations(items) {
            items.forEach((item, index) => {
                this.setAnimationIndex(item, index);
            });
        },

        /**
         * Set animation index CSS variable on element
         * @param {HTMLElement} element - Element to animate
         * @param {number} index - Animation index
         */
        setAnimationIndex(element, index) {
            element.style.setProperty('--animation-index', index);
        }
    };


    /* ======================================================================
       EXTERNAL LINKS
       Opens external links in new tabs with security attributes
       ====================================================================== */

    const ExternalLinkManager = {
        /**
         * Initialize external link handling
         */
        init() {
            const links = document.querySelectorAll(CONFIG.selectors.externalLink);

            links.forEach(link => {
                // Skip if it's an internal anchor or same-origin link
                if (this.isExternalLink(link)) {
                    link.setAttribute('target', '_blank');
                    link.setAttribute('rel', 'noopener noreferrer');
                }
            });
        },

        /**
         * Check if a link is external
         * @param {HTMLAnchorElement} link - Link element to check
         * @returns {boolean} True if link is external
         */
        isExternalLink(link) {
            try {
                const url = new URL(link.href);
                return url.origin !== window.location.origin;
            } catch (e) {
                return false;
            }
        }
    };


    /* ======================================================================
       FEEDBACK FORM
       Expandable feedback form with keyboard support
       ====================================================================== */

    const FeedbackManager = {
        // Store references to elements
        elements: {
            container: null,
            trigger: null,
            content: null,
            textarea: null,
            cancelBtn: null
        },

        /**
         * Initialize feedback form functionality
         */
        init() {
            const container = document.querySelector(CONFIG.selectors.feedback);
            if (!container) return;

            // Cache element references
            this.elements = {
                container,
                trigger: container.querySelector(CONFIG.selectors.feedbackTrigger),
                content: container.querySelector(CONFIG.selectors.feedbackContent),
                textarea: container.querySelector(CONFIG.selectors.feedbackTextarea),
                cancelBtn: container.querySelector(CONFIG.selectors.feedbackCancel)
            };

            if (!this.elements.trigger || !this.elements.content) return;

            this.bindEvents();
        },

        /**
         * Bind event listeners
         */
        bindEvents() {
            const { trigger, cancelBtn, textarea } = this.elements;

            // Toggle on trigger click
            trigger.addEventListener('click', () => this.toggle());

            // Cancel button
            if (cancelBtn) {
                cancelBtn.addEventListener('click', () => this.close());
            }

            // Keyboard shortcut: Cmd/Ctrl + Enter submits form naturally
            if (textarea) {
                textarea.addEventListener('keydown', (e) => {
                    if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
                        const form = textarea.closest('form');
                        if (form && typeof form.requestSubmit === 'function') {
                            e.preventDefault();
                            form.requestSubmit();
                        }
                    }
                    // Escape to close
                    if (e.key === 'Escape') {
                        this.close();
                    }
                });
            }
        },

        /**
         * Toggle feedback form open/closed
         */
        toggle() {
            const isOpen = this.elements.content.classList.contains(CONFIG.classes.open);

            if (isOpen) {
                this.close();
            } else {
                this.open();
            }
        },

        /**
         * Open feedback form
         */
        open() {
            const { trigger, content, textarea } = this.elements;

            trigger.classList.add(CONFIG.classes.expanded);
            content.classList.add(CONFIG.classes.open);

            // Focus textarea after animation
            if (textarea) {
                setTimeout(() => textarea.focus(), CONFIG.timing.focusDelay);
            }
        },

        /**
         * Close feedback form
         */
        close() {
            const { trigger, content, textarea } = this.elements;

            trigger.classList.remove(CONFIG.classes.expanded);
            content.classList.remove(CONFIG.classes.open);

            // Clear textarea
            if (textarea) {
                textarea.value = '';
            }
        }
    };


    /* ======================================================================
       TWEET URL STORAGE
       Store tweet URLs for theme switching recreation
       ====================================================================== */

    const TweetManager = {
        /**
         * Store tweet URLs as data attributes before widgets render
         * This allows us to recreate tweets when switching themes
         */
        init() {
            const tweetContainers = document.querySelectorAll('.tweet-container');

            tweetContainers.forEach(container => {
                const blockquote = container.querySelector('blockquote.twitter-tweet');
                const link = blockquote?.querySelector('a[href*="twitter.com"], a[href*="x.com"]');

                if (link?.href) {
                    container.setAttribute('data-tweet-url', link.href);
                }
            });
        }
    };


    /* ======================================================================
       INITIALIZATION
       Bootstrap all modules on DOM ready
       ====================================================================== */

    function init() {
        // Store tweet URLs first (before widgets render)
        TweetManager.init();

        // Initialize all managers
        ThemeManager.init();
        AnimationManager.init();
        ExternalLinkManager.init();
        FeedbackManager.init();

        // Log initialization
        console.log('[Twitter Digest] App initialized');
    }

    // Run on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }


    /* ======================================================================
       PUBLIC API
       Expose methods for external use
       ====================================================================== */

    window.TwitterDigest = {
        theme: ThemeManager,
        tweets: TweetManager,
        animations: AnimationManager,
        feedback: FeedbackManager
    };

})();
