/**
 * AI Digest - Main Application
 * Handles theme detection, animations, favicon loading, external links, and feedback
 */

(function() {
    'use strict';

    // ==========================================================================
    // ANIMATION SYSTEM
    // Automatically assigns staggered animation delays based on DOM order
    // ==========================================================================

    function initAnimations() {
        const items = document.querySelectorAll('.content-item');
        const sections = document.querySelectorAll('[data-animation-section]');

        if (sections.length > 0) {
            // Section-based: reset index for each section
            sections.forEach(section => {
                const sectionItems = section.querySelectorAll('.content-item');
                sectionItems.forEach((item, index) => {
                    item.style.setProperty('--animation-index', index);
                });
            });

            // Handle items outside sections
            let globalIndex = 0;
            items.forEach(item => {
                if (!item.closest('[data-animation-section]')) {
                    item.style.setProperty('--animation-index', globalIndex);
                    globalIndex++;
                }
            });
        } else {
            // Global: sequential index across entire page
            items.forEach((item, index) => {
                item.style.setProperty('--animation-index', index);
            });
        }
    }

    // ==========================================================================
    // FAVICON LOADING
    // Tries domain's favicon.ico first, then DuckDuckGo as fallback
    // ==========================================================================

    function loadSingleFavicon(img, domain, displaySize) {
        const directUrl = `https://${domain}/favicon.ico`;
        const ddgUrl = `https://icons.duckduckgo.com/ip3/${domain}.ico`;

        img.width = displaySize;
        img.height = displaySize;

        // Chain: try direct → DDG
        img.onerror = () => {
            img.onerror = null;
            img.src = ddgUrl;
        };

        img.src = directUrl;
    }

    function loadFavicons() {
        // Auto-source favicons from parent link href for card elements
        const cards = document.querySelectorAll('.card--link[href], .card--featured[href], .card--ph[href]');

        cards.forEach(card => {
            const img = card.querySelector('.card__favicon');
            if (!img || !card.href) return;

            try {
                const domain = new URL(card.href).hostname;
                const displaySize = img.dataset.size || 18;
                loadSingleFavicon(img, domain, displaySize);
            } catch (e) {
                // Invalid URL, use fallback
                img.src = FAVICON_FALLBACK;
            }
        });

        // Handle explicit data-favicon attributes (if any)
        document.querySelectorAll('[data-favicon]').forEach(img => {
            try {
                const domain = new URL(img.dataset.favicon).hostname;
                const displaySize = img.dataset.size || 16;
                loadSingleFavicon(img, domain, displaySize);
            } catch (e) {
                // Invalid URL, use fallback
                img.src = FAVICON_FALLBACK;
            }
        });
    }

    // ==========================================================================
    // EXTERNAL LINKS
    // Opens all external links in new tab with security attributes
    // ==========================================================================

    function initExternalLinks() {
        document.querySelectorAll('a[href^="http"]').forEach(link => {
            link.setAttribute('target', '_blank');
            link.setAttribute('rel', 'noopener noreferrer');
        });
    }

    // ==========================================================================
    // FEEDBACK BOX
    // Expandable feedback form with event delegation
    // ==========================================================================

    function initFeedback() {
        const feedbackContainer = document.querySelector('[data-feedback]');
        if (!feedbackContainer) return;

        const trigger = feedbackContainer.querySelector('[data-feedback-trigger]');
        const content = feedbackContainer.querySelector('[data-feedback-content]');
        const textarea = feedbackContainer.querySelector('.feedback__textarea');
        const cancelBtn = feedbackContainer.querySelector('[data-feedback-cancel]');
        const submitBtn = feedbackContainer.querySelector('[data-feedback-submit]');

        if (!trigger || !content) return;

        function openFeedback() {
            trigger.classList.add('is-expanded');
            content.classList.add('is-open');
            setTimeout(() => textarea?.focus(), 300);
        }

        function closeFeedback() {
            trigger.classList.remove('is-expanded');
            content.classList.remove('is-open');
            if (textarea) textarea.value = '';
        }

        function submitFeedback() {
            const feedback = textarea?.value.trim();

            if (feedback) {
                // TODO: Replace with actual API call
                console.log('Feedback submitted:', feedback);
                alert("Thanks! I'll adjust for tomorrow.");
                closeFeedback();
            } else {
                textarea?.focus();
            }
        }

        // Event listeners
        trigger.addEventListener('click', () => {
            if (content.classList.contains('is-open')) {
                closeFeedback();
            } else {
                openFeedback();
            }
        });

        cancelBtn?.addEventListener('click', closeFeedback);
        submitBtn?.addEventListener('click', submitFeedback);

        // Submit on Cmd/Ctrl + Enter
        textarea?.addEventListener('keydown', (e) => {
            if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
                e.preventDefault();
                submitFeedback();
            }
        });
    }

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

    function initTheme() {
        const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

        function applyTheme(isDark) {
            document.documentElement.dataset.theme = isDark ? 'dark' : 'light';
        }

        // Apply initial theme
        applyTheme(mediaQuery.matches);

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

    // ==========================================================================
    // INITIALIZATION
    // ==========================================================================

    function init() {
        initTheme();
        initAnimations();
        loadFavicons();
        initExternalLinks();
        initFeedback();
    }

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

})();
