/**
 * Upload Asset Dropdown Manager
 * Manages two-tier asset selection for data upload section
 */

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

    // Load asset-mapping.json
    async function loadAssetMapping() {
        try {
            const response = await fetch('./js/asset-mapping.json');
            assetTypeMapping = await response.json();
            populateAssetTypeDropdown();
        } catch (error) {
            console.error('Failed to load asset mapping:', error);
        }
    }

    // Get Font Awesome icon for asset type (same as asset-type-dropdown.js)
    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;
    }

    // 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;
    }

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

        dropdownList.innerHTML = '';
        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;';

            const displayName = formatAssetTypeName(assetType);
            const iconClass = getAssetTypeIcon(assetType);

            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);
            }

            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);
        });
    }

    // Select asset type
    function selectAssetType(assetType, displayName, iconClass) {
        selectedAssetType = assetType;

        const header = document.getElementById('upload-asset-type-dropdown-header');
        header.dataset.selectedType = assetType;
        const headerSpan = header.querySelector('span');

        headerSpan.innerHTML = '';

        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);
        }

        const textSpan = document.createElement('span');
        textSpan.textContent = displayName;
        textSpan.style.cssText = 'position: relative; top: -2px;';
        headerSpan.appendChild(textSpan);

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

        // Populate asset dropdown based on selected type
        populateAssetDropdown(assetType);

        // Reset asset selection
        resetAssetSelection();
    }

    // Populate asset dropdown based on selected type
    async function populateAssetDropdown(assetType) {
        const dropdownList = document.getElementById('upload-asset-dropdown-list');
        if (!dropdownList) return;

        dropdownList.innerHTML = '';

        try {
            const assetsData = assetTypeMapping[assetType];
            if (!assetsData) return;

            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 });
                });
            }

            // 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 (same logic as activate dropdown)
                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('click', () => selectAsset(name, flags));
                item.addEventListener('mouseenter', () => item.style.background = '#3D4354');
                item.addEventListener('mouseleave', () => item.style.background = 'transparent');

                dropdownList.appendChild(item);
            }
        } catch (error) {
            console.error('Error populating asset dropdown:', error);
        }
    }

    // Select asset
    function selectAsset(assetName, flags) {
        selectedAsset = assetName;

        const header = document.getElementById('upload-asset-dropdown-header');
        const headerSpan = header.querySelector('span');

        headerSpan.innerHTML = '';

        // Add flags to header
        flags.forEach((flagCode, index) => {
            const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
            svg.setAttribute('width', '16');
            svg.setAttribute('height', '16');
            svg.setAttribute('viewBox', '0 0 16 16');
            svg.style.cssText = `width: 16px; height: 16px; border: 2px solid #3D4354; border-radius: 50%; display: inline-block; margin-left: ${index === 0 ? '0' : '-8px'}; margin-right: ${index === flags.length - 1 ? '8px' : '0'}; 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);
            headerSpan.appendChild(svg);
        });

        // Add asset name
        const textSpan = document.createElement('span');
        textSpan.textContent = assetName;
        headerSpan.appendChild(textSpan);

        // Update hidden input for form submission
        const hiddenInput = document.getElementById('selected-upload-asset');
        if (hiddenInput) {
            hiddenInput.value = assetName;
        }

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

    // Reset asset selection
    function resetAssetSelection() {
        selectedAsset = null;
        const header = document.getElementById('upload-asset-dropdown-header');
        const headerSpan = header.querySelector('span');
        headerSpan.innerHTML = 'Select asset';

        const hiddenInput = document.getElementById('selected-upload-asset');
        if (hiddenInput) {
            hiddenInput.value = '';
        }
    }

    // Setup dropdown toggles
    function setupDropdownToggles() {
        // Asset Type Dropdown Toggle
        const assetTypeHeader = document.getElementById('upload-asset-type-dropdown-header');
        const assetTypeList = document.getElementById('upload-asset-type-dropdown-list');

        if (assetTypeHeader && assetTypeList) {
            assetTypeHeader.addEventListener('click', (e) => {
                e.stopPropagation();
                const arrow = assetTypeHeader.querySelector('.dropdown-arrow');

                if (assetTypeList.style.display === 'none') {
                    assetTypeList.style.display = 'block';
                    arrow.classList.add('rotated');
                } else {
                    assetTypeList.style.display = 'none';
                    arrow.classList.remove('rotated');
                }
            });
        }

        // Asset Dropdown Toggle
        const assetHeader = document.getElementById('upload-asset-dropdown-header');
        const assetList = document.getElementById('upload-asset-dropdown-list');

        if (assetHeader && assetList) {
            assetHeader.addEventListener('click', (e) => {
                e.stopPropagation();
                const arrow = assetHeader.querySelector('.dropdown-arrow');

                if (assetList.style.display === 'none') {
                    assetList.style.display = 'block';
                    arrow.classList.add('rotated');
                } else {
                    assetList.style.display = 'none';
                    arrow.classList.remove('rotated');
                }
            });
        }

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

            if (assetHeader && assetList &&
                !assetHeader.contains(e.target) && !assetList.contains(e.target)) {
                assetList.style.display = 'none';
                assetHeader.querySelector('.dropdown-arrow').classList.remove('rotated');
            }
        });
    }

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