(function () {
    'use strict';

    if (window.HerAIProvidersLoader) {
        return;
    }

    class AIProvidersLoader {
        constructor() {
            this.providers = null;
            this.configUrl = 'https://the-moment.us/apps/chatpage/remote-config/ai-providers-config.json';
            this.loadPromise = null;
            this.submitSelectors = {};
        }

        async loadProviders() {
            if (this.providers) {
                return this.providers;
            }

            if (this.loadPromise) {
                return this.loadPromise;
            }

            this.loadPromise = this._fetchProviders();
            return this.loadPromise;
        }

        async _fetchProviders() {
            try {
                const response = await fetch(this.configUrl);
                if (!response.ok) {
                    throw new Error(`Failed to load AI providers: ${response.status}`);
                }

                const config = await response.json();
                this.providers = config.providers;
                this._parseSubmitSelectors();
                
                // console.log('[AIProvidersLoader] Loaded providers:', Object.keys(this.providers));
                return this.providers;
            } catch (error) {
                console.error('[AIProvidersLoader] Failed to load providers:', error);
                this.providers = null;
                return null;
            }
        }

        _parseSubmitSelectors() {
            if (!this.providers) return;

            // Parse submit button selectors for each provider
            for (const [providerKey, provider] of Object.entries(this.providers)) {
                if (provider.sendButton && Array.isArray(provider.sendButton)) {
                    // Map domain patterns to selectors
                    const domains = this._extractDomains(provider);
                    for (const domain of domains) {
                        this.submitSelectors[domain] = provider.sendButton;
                    }
                }
            }

            // console.log('[AIProvidersLoader] Parsed submit selectors for domains:', Object.keys(this.submitSelectors));
        }

        _extractDomains(provider) {
            const domains = [];
            
            // Extract from URL if exists
            if (provider.url) {
                try {
                    const url = new URL(provider.url);
                    domains.push(url.hostname);
                } catch (e) {
                    // Invalid URL, skip
                }
            }

            // Extract from matches if exists
            if (provider.matches && Array.isArray(provider.matches)) {
                for (const match of provider.matches) {
                    // Extract domain from match pattern
                    const domainMatch = match.match(/https?:\/\/([^\/]+)/);
                    if (domainMatch) {
                        domains.push(domainMatch[1].replace('*', ''));
                    }
                }
            }

            // Add common domain mappings
            const providerDomainMap = {
                'chatgpt': ['chatgpt.com', 'chat.openai.com'],
                'claude': ['claude.ai'],
                'gemini': ['gemini.google.com', 'bard.google.com'],
                'perplexity': ['perplexity.ai'],
                'grok': ['x.com', 'twitter.com'],
                'deepseek': ['deepseek.com', 'chat.deepseek.com']
            };

            const key = provider.name?.toLowerCase() || '';
            for (const [mapKey, mapDomains] of Object.entries(providerDomainMap)) {
                if (key.includes(mapKey)) {
                    domains.push(...mapDomains);
                }
            }

            return [...new Set(domains)]; // Remove duplicates
        }

        getSubmitSelectors(hostname) {
            // Direct match
            if (this.submitSelectors[hostname]) {
                return this.submitSelectors[hostname];
            }

            // Partial match
            for (const [domain, selectors] of Object.entries(this.submitSelectors)) {
                if (hostname.includes(domain) || domain.includes(hostname)) {
                    return selectors;
                }
            }

            return [];
        }

        async findSubmitButton() {
            const hostname = window.location.hostname;
            const selectors = this.getSubmitSelectors(hostname);

            if (!selectors || selectors.length === 0) {
                // console.log('[AIProvidersLoader] No submit selectors found for:', hostname);
                
                // Claude.ai 전용 폴백 셀렉터
                if (hostname === 'claude.ai') {
                    // console.log('[AIProvidersLoader] Claude.ai 감지 - 폴백 셀렉터 시도');
                    const fallbackSelectors = [
                        'button[aria-label*="Send Message"]',
                        'button[aria-label*="Send message"]',
                        'button[aria-label*="Send"]',
                        'button:has(svg path[d*="M.5 1.163A1"])',
                        'div[role="dialog"] button[type="button"]:not([disabled])',
                        'form button[type="button"]:not([disabled])',
                        'button:has(svg):not([disabled])',
                        'button[type="button"]:last-child:not([disabled])'
                    ];
                    
                    for (const selector of fallbackSelectors) {
                        try {
                            const button = document.querySelector(selector);
                            if (button && !button.disabled) {
                                // console.log('[AIProvidersLoader] Claude.ai 폴백으로 전송 버튼 발견:', selector);
                                return button;
                            }
                        } catch (e) {
                            // Invalid selector, continue
                        }
                    }
                }
                return null;
            }

            // Try each selector
            for (const selector of selectors) {
                try {
                    const button = document.querySelector(selector);
                    if (button && !button.disabled) {
                        // console.log('[AIProvidersLoader] Found submit button with selector:', selector);
                        return button;
                    }
                } catch (e) {
                    // Invalid selector, continue
                    console.warn('[AIProvidersLoader] Invalid selector:', selector);
                }
            }

            // console.log('[AIProvidersLoader] No submit button found for hostname:', hostname);
            return null;
        }

        async clickSubmitButton() {
            const button = await this.findSubmitButton();
            if (button) {
                button.click();
                // console.log('[AIProvidersLoader] Clicked submit button');
                return true;
            }
            return false;
        }
    }

    // Initialize and expose globally
    window.HerAIProvidersLoader = new AIProvidersLoader();
    
    // Auto-load on initialization
    window.HerAIProvidersLoader.loadProviders();
})();