/**
 * Asset Type Dropdown Manager
 * Populates asset types from asset-name-mapping.json
 */

(function() {
    let assetTypeMapping = null;
    let selectedAssetType = null;

    // Load asset-name-mapping.json
    async function loadAssetMapping() {
        try {
            const response = await fetch('./js/asset-name-mapping.json');
            assetTypeMapping = await response.json();
            
            // Flatten and expose globally for reverse lookups
            // This enables window.getOriginalAssetName() and proper display name mapping
            window.assetNameMapping = {};
            
            // Flatten currencyPairs (major and exotic)
            if (assetTypeMapping.currencyPairs) {
                if (assetTypeMapping.currencyPairs.major) {
                    Object.assign(window.assetNameMapping, assetTypeMapping.currencyPairs.major);
                }
                if (assetTypeMapping.currencyPairs.exotic) {
                    Object.assign(window.assetNameMapping, assetTypeMapping.currencyPairs.exotic);
                }
            }
            
            // Flatten other categories
            ['cryptocurrencies', 'stocks', 'indices', 'commodities'].forEach(category => {
                if (assetTypeMapping[category]) {
                    Object.assign(window.assetNameMapping, assetTypeMapping[category]);
                }
            });
            
            populateAssetTypeDropdown();
        } catch (error) {
            console.error('Failed to load asset name mapping:', error);
            window.assetNameMapping = {};
        }
    }

    // Get Font Awesome icon class for asset type
    function getAssetTypeIcon(assetType) {
        const iconMap = {
            'currencyPairs': { class: 'fa-money-bill', type: 'fas', color: '#85bb65' },
            'cryptocurrencies': { class: 'fa-bitcoin', type: 'fa-brands', color: '#f7931a' },
            'stocks': { class: 'fa-briefcase', type: 'fa-solid', color: '#ffffff' },
            'indices': { class: 'fa-chart-area', type: 'fa-solid', color: '#ffffff' },
            'commodities': { class: 'fa-coins', type: 'fas', color: '#ffd700' }
        };
        return iconMap[assetType] || null;
    }

    // Populate asset type dropdown
    function populateAssetTypeDropdown() {
        const dropdownList = document.getElementById('asset-type-dropdown-list');
        if (!dropdownList || !assetTypeMapping) return;

        dropdownList.innerHTML = '';

        // Get asset types (top-level keys)
        const assetTypes = Object.keys(assetTypeMapping);

        assetTypes.forEach(assetType => {
            const item = document.createElement('div');
            item.className = 'asset-type-item';
            item.style.cssText = 'padding: 10px; cursor: pointer; border-bottom: 1px solid #3D4354; display: flex; align-items: center; gap: 12px;';
            
            // Format display name
            const displayName = formatAssetTypeName(assetType);
            const iconClass = getAssetTypeIcon(assetType);
            
            // Create icon if available
            if (iconClass) {
                const icon = document.createElement('i');
                icon.className = `${iconClass.type} ${iconClass.class}`;
                icon.style.cssText = `width: 20px; font-size: 18px; color: ${iconClass.color};`;
                item.appendChild(icon);
            }
            
            // Create text span
            const textSpan = document.createElement('span');
            textSpan.textContent = displayName;
            item.appendChild(textSpan);
            
            item.dataset.assetType = assetType;

            item.addEventListener('click', () => selectAssetType(assetType, displayName, iconClass));
            item.addEventListener('mouseenter', () => item.style.background = '#3D4354');
            item.addEventListener('mouseleave', () => item.style.background = 'transparent');

            dropdownList.appendChild(item);
        });
    }

    // Format asset type name for display
    function formatAssetTypeName(assetType) {
        const nameMap = {
            'currencyPairs': 'Currency Pairs',
            'cryptocurrencies': 'Cryptocurrencies',
            'stocks': 'Stocks',
            'indices': 'Indices',
            'commodities': 'Commodities'
        };
        return nameMap[assetType] || assetType;
    }

    // Select asset type
    function selectAssetType(assetType, displayName, iconClass) {
        selectedAssetType = assetType;
        
        const header = document.getElementById('asset-type-dropdown-header');
        header.dataset.selectedType = assetType;
        const headerSpan = header.querySelector('span');
        
        // Clear existing content
        headerSpan.innerHTML = '';
        
        // Create icon if available
        if (iconClass) {
            const icon = document.createElement('i');
            icon.className = `${iconClass.type} ${iconClass.class}`;
            icon.style.cssText = `margin-right: 5px; font-size: 17px; color: ${iconClass.color};`;
            headerSpan.appendChild(icon);
        }
        
        // Create text node with wrapper span for positioning
        const textSpan = document.createElement('span');
        textSpan.textContent = displayName;
        textSpan.style.cssText = 'position: relative; top: -2px;';
        headerSpan.appendChild(textSpan);

        // Close dropdown
        const dropdownList = document.getElementById('asset-type-dropdown-list');
        dropdownList.style.display = 'none';
        header.querySelector('.dropdown-arrow').classList.remove('rotated');

        // Filter activate charts dropdown based on selected type
        // COMMENTED OUT: This function is redundant - populateDropdown() in app.js handles this
        // filterActivateChartsDropdown(assetType);
    }

    // Filter activate charts dropdown based on asset type
    async function filterActivateChartsDropdown(assetType) {
        console.log('🔍 filterActivateChartsDropdown called with:', assetType);
        
        if (!assetType) {
            console.error('❌ No assetType provided');
            return;
        }

        const activateDropdownList = document.getElementById('activate-dropdown-list');
        if (!activateDropdownList) {
            console.error('❌ activate-dropdown-list element not found');
            return;
        }
        console.log('✅ Found dropdown element:', activateDropdownList);
        console.log('📍 Dropdown parent:', activateDropdownList.parentElement);

        activateDropdownList.innerHTML = '';
        console.log('✅ Cleared dropdown list');

        try {
            // Load asset-mapping.json directly
            console.log('📥 Fetching asset-mapping.json...');
            const response = await fetch('./js/asset-mapping.json');
            const assetMapping = await response.json();
            console.log('✅ Loaded asset-mapping.json:', assetMapping);
            
            const assetsData = assetMapping[assetType];
            if (!assetsData) {
                console.error('❌ No data for assetType:', assetType);
                return;
            }
            console.log('✅ Assets data:', assetsData);

            // Extract asset names and flags
            let assets = [];
            if (assetType === 'currencyPairs') {
                if (assetsData.major) {
                    Object.entries(assetsData.major).forEach(([name, flags]) => {
                        assets.push({name, flags});
                    });
                }
                if (assetsData.exotic) {
                    Object.entries(assetsData.exotic).forEach(([name, flags]) => {
                        assets.push({name, flags});
                    });
                }
            } else {
                Object.entries(assetsData).forEach(([name, flags]) => {
                    assets.push({name, flags});
                });
            }
            console.log('✅ Extracted assets:', assets);

            // Populate items with flags
            for (const {name, flags} of assets) {
                const item = document.createElement('div');
                item.className = 'activate-asset-item';
                item.style.cssText = 'padding: 10px; cursor: pointer; border-bottom: 1px solid #3D4354; display: flex; align-items: center; gap: 8px;';
                
                // Generate flag SVGs
                flags.forEach((flagCode, index) => {
                    const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
                    svg.setAttribute('class', 'dropdown-flag');
                    svg.setAttribute('width', '16');
                    svg.setAttribute('height', '16');
                    svg.setAttribute('viewBox', '0 0 16 16');
                    svg.style.cssText = `width: 16px !important; height: 16px !important; border: 2px solid #3D4354 !important; border-radius: 50% !important; display: inline-block; margin-left: ${index === 0 ? '0' : '-8px'}; background: white; overflow: hidden;`;
                    const use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
                    use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', `./svg/flags.svg#flag-${flagCode}`);
                    svg.appendChild(use);
                    item.appendChild(svg);
                });

                // Add asset name
                const nameSpan = document.createElement('span');
                nameSpan.textContent = name;
                item.appendChild(nameSpan);

                item.addEventListener('mouseenter', () => item.style.background = '#3D4354');
                item.addEventListener('mouseleave', () => item.style.background = 'transparent');

                activateDropdownList.appendChild(item);
            }
            
            // Debug: Log first item HTML
            if (activateDropdownList.children.length > 0) {
                console.log('🎨 First item HTML:', activateDropdownList.children[0].innerHTML);
                console.log('🔍 First item element:', activateDropdownList.children[0]);
            }
            
            console.log('✅ Successfully populated', assets.length, 'items');
            console.log('📊 Total children in dropdown:', activateDropdownList.children.length);
            
            // Verify after 1 second that items are still there
            setTimeout(() => {
                console.log('⏰ After 1 second - children count:', activateDropdownList.children.length);
                if (activateDropdownList.children.length > 0) {
                    console.log('⏰ First item still exists:', activateDropdownList.children[0].innerHTML);
                } else {
                    console.error('❌ ITEMS WERE REMOVED!');
                }
            }, 1000);
        } catch (error) {
            console.error('❌ Error in filterActivateChartsDropdown:', error);
        }
    }

    // Setup dropdown toggle
    function setupDropdownToggle() {
        const header = document.getElementById('asset-type-dropdown-header');
        const dropdownList = document.getElementById('asset-type-dropdown-list');
        
        if (!header || !dropdownList) return;

        header.addEventListener('click', (e) => {
            e.stopPropagation();
            const arrow = header.querySelector('.dropdown-arrow');
            
            if (dropdownList.style.display === 'none') {
                dropdownList.style.display = 'block';
                arrow.classList.add('rotated');
            } else {
                dropdownList.style.display = 'none';
                arrow.classList.remove('rotated');
            }
        });

        // Close dropdown when clicking outside
        document.addEventListener('click', (e) => {
            if (!header.contains(e.target) && !dropdownList.contains(e.target)) {
                dropdownList.style.display = 'none';
                header.querySelector('.dropdown-arrow').classList.remove('rotated');
            }
        });
    }

    // Initialize
    document.addEventListener('DOMContentLoaded', () => {
        loadAssetMapping();
        setupDropdownToggle();
    });
})();
