import { createIcons, icons } from 'lucide';

/**
 * Renders the entire Sidebar UI based on state.
 * @param {HTMLElement} container - The DOM element to render into.
 * @param {object} config - The customization options (steps).
 * @param {object} state - The current app state (model selections + UI state).
 * @param {object} actions - Callbacks { onOptionSelect, onNavChange }.
 */
export function renderUI(container, config, state, actions) {
    const isMobile = window.innerWidth <= 768;
    container.innerHTML = '';

    // --- MOBILE VIEW ---
    if (isMobile) {
        // 1. Mobile Submenu (Active Section)
        if (state.ui.activeSection) {
            const sectionKey = state.ui.activeSection;
            const section = config[sectionKey];

            // Header with Back Button
            const header = document.createElement('div');
            header.className = 'mobile-submenu-header';
            header.innerHTML = `
                <button class="btn-back"><i data-lucide="chevron-left"></i></button>
                <h3>${section.name}</h3>
            `;
            header.querySelector('.btn-back').onclick = () => actions.onNavChange(null); // Go back
            container.appendChild(header);

            // Add description if it exists
            if (section.description) {
                const description = document.createElement('p');
                description.className = 'mobile-section-description';
                description.textContent = section.description;
                container.appendChild(description);
            }

            // Swatches
            const swatches = document.createElement('div');
            swatches.className = 'color-swatches';
            renderSwatches(swatches, sectionKey, section, state, actions);
            container.appendChild(swatches);

            // 2. Mobile Main Menu (List of Categories)
        } else {
            const menuList = document.createElement('div');
            menuList.className = 'mobile-menu-container';

            Object.entries(config).forEach(([key, section]) => {
                
                const btn = document.createElement('button');
                btn.className = 'mobile-menu-button';
                const iconUrl = section.icon || '';
                const cachedIcon = window.dprcuGetCachedIconUrl?.(iconUrl) || iconUrl;
                btn.innerHTML = `
                        ${cachedIcon ? `<img src="${cachedIcon}" class="step-icon-img">` : '<i data-lucide="box-select"></i>'}
                        <span>${section.name}</span>
                `;
                btn.onclick = () => actions.onNavChange(key); // Navigate to section
                menuList.appendChild(btn);
            });
            container.appendChild(menuList);
        }

        // --- DESKTOP VIEW ---
    } else {
        const desktopWrapper = document.createElement('div');
        desktopWrapper.className = 'desktop-sidebar';

        Object.entries(config).forEach(([key, section]) => {
            
            const sectionDiv = document.createElement('div');
            sectionDiv.className = 'cust-section';

            const title = document.createElement('h3');
            title.textContent = section.name;
            sectionDiv.appendChild(title);

            // Add description if it exists
            if (section.description) {
                const description = document.createElement('p');
                description.className = 'section-description';
                description.textContent = section.description;
                description.style.fontSize = '12px';
                description.style.color = '#666';
                description.style.margin = '0 0 12px 0';
                sectionDiv.appendChild(description);
            }

            const swatches = document.createElement('div');
            swatches.className = 'color-swatches';
            renderSwatches(swatches, key, section, state, actions);

            sectionDiv.appendChild(swatches);
            desktopWrapper.appendChild(sectionDiv);
        });
        container.appendChild(desktopWrapper);
    }

    try { createIcons({ icons }); } catch { }
}

/**
 * Helper to render the grid of swatches/buttons
 */
function renderSwatches(container, partKey, section, state, actions) {
    if (!section.options) return;

    section.options.forEach(option => {
        const wrapper = document.createElement('div');
        wrapper.className = 'swatch-wrapper';

        // Check if selected
        // We compare JSON strings to handle object equality
        const isSelected = JSON.stringify(state.current[partKey]) === JSON.stringify(option.value);
        if (isSelected) wrapper.classList.add('active');

        const swatch = document.createElement('div');

        if (option.type === 'object') {
            // Geometry Swatch
            swatch.className = 'logic-swatch';
            // Only fall back to section.icon if it is a real URL (not an auto-generated data URI)
            const sectionIconFallback = section.icon && !section.icon.startsWith('data:') ? section.icon : '';
            const iconUrl = option.icon || sectionIconFallback;
            const cachedIcon = window.dprcuGetCachedIconUrl?.(iconUrl) || iconUrl;
            swatch.innerHTML = cachedIcon
                ? `<img class="swatch-icon" src="${cachedIcon}">`
                : '<i data-lucide="box-select"></i>';
        } else {
            // Material Swatch
            swatch.className = 'color-swatch';
            // Option icon takes priority over texture/color
            const optIcon = option.icon || '';
            const cachedOptIcon = window.dprcuGetCachedIconUrl?.(optIcon) || optIcon;
            if (cachedOptIcon) {
                swatch.style.backgroundImage = `url(${cachedOptIcon})`;
                swatch.style.backgroundSize = 'cover';
            } else {
                // 1. Texture image (thumbnail priority, then full)
                const bgUrl = option.value.textureThumbnail || option.value.texture;
                if (bgUrl) {
                    swatch.style.backgroundImage = `url(${bgUrl})`;
                    swatch.style.backgroundSize = 'cover';
                } else if (option.value.color) {
                    // No image — show the flat color directly as the swatch background
                    swatch.style.backgroundColor = option.value.color;
                }
            }
        }

        wrapper.appendChild(swatch);

        const label = document.createElement('span');
        label.className = 'swatch-name';
        label.textContent = option.name;
        wrapper.appendChild(label);

        // Price badge
        const optPrice = parseFloat(option.price) || 0;
        if (optPrice > 0) {
            const badge = document.createElement('span');
            badge.className = 'swatch-price-badge';
            const sym = customizerData.currencySymbol || '$';
            const pos = customizerData.currencyPosition || 'left';
            const val = optPrice.toFixed(2);
            const formatted = pos === 'left' ? sym + val
                : pos === 'right' ? val + sym
                : pos === 'left_space' ? `${sym} ${val}`
                : pos === 'right_space' ? `${val} ${sym}`
                : sym + val;
            badge.textContent = `+${formatted}`;
            swatch.appendChild(badge);
        }

        // Click Handler
        wrapper.onclick = () => actions.onOptionSelect(partKey, option.value, option.type);

        container.appendChild(wrapper);
    });
}