// Global image storage
const imageStore = {
    // Stores all Base64 images with unique keys
    base64Images: {},
    
    // Static image resources
    staticImages: {
        home: 'am_card_pay_black.png',
        scan: 'am_barcode_black.png',
        printer: 'am_receipt_cart_black.png',
        settings: 'am_settings_black.png',
        mulberry: 'am_mulberry_logo_wide_color.png',
        overtec: 'am_overtec_logo_wide_color.png',
        datexpay: 'am_datexpay_logo_wide_color.png',
        citibank: 'am_bank_citibank_wide_color.png',
        nbubank: 'am_bank_nbubank_wide_color.png'
    },
    
    // Store a Base64 image and return its key
    storeBase64: function(name, base64Data) {
        const key = `${name}_${Date.now()}`;
        this.base64Images[key] = base64Data;
        return key;
    },
    
    // Retrieve a Base64 image by key
    getBase64: function(key) {
        return this.base64Images[key] || null;
    },
    
    // Get static image path
    getStaticImage: function(name) {
        return this.staticImages[name] ? `/images/drawable/${this.staticImages[name]}` : null;
    }
};

document.addEventListener('DOMContentLoaded', function() {
    console.log('[DEBUG] DOM fully loaded - initializing POS configurator');

    // Initialize form toggles and event listeners
    function initializeForm() {
        console.log('[DEBUG] Initializing form event listeners');

        // Handle logo type toggling
        document.querySelectorAll('[name="mainLogoType"], [name="footerLogoType"]').forEach(select => {
            select.addEventListener('change', function() {
                const type = this.value;
                console.log(`[DEBUG] Logo type changed to ${type}`);
                const container = this.closest('.form-group');
                
                container.querySelector('.resource-select').style.display = 
                    type === 'resource' ? 'block' : 'none';
                container.querySelector('.upload-input').style.display = 
                    type === 'base64' ? 'block' : 'none';
                
                // Clear previous selection when changing type
                if (type === 'resource') {
                    container.querySelector('.upload-input').value = '';
                } else if (type === 'base64') {
                    container.querySelector('.resource-select').value = '';
                }
            });
            // Trigger initial state
            select.dispatchEvent(new Event('change'));
        });

        // Handle image uploads (for both main logo and footer logo)
        document.querySelectorAll('.upload-input').forEach(input => {
            input.addEventListener('change', function() {
                if (!this.files[0]) {
                    console.warn('[DEBUG] No file selected for upload');
                    return;
                }
                
                const fileName = this.files[0].name;
                const inputName = this.name; // e.g. "mainLogoUpload" or "footerLogoUpload"
                console.log(`[DEBUG] Uploading ${inputName}: ${fileName}`);

                const reader = new FileReader();
                
                reader.onload = (event) => {
                    const base64Data = event.target.result;
                    console.log('[DEBUG] File read as Base64');
                    
                    // Store the image and get its key
                    const imageKey = imageStore.storeBase64(inputName, base64Data);
                    
                    // Update preview
                    const previewId = inputName.replace('Upload', 'Preview');
                    document.getElementById(previewId).src = base64Data;
                    
                    // Update hidden input with the storage key
                    const hiddenInputName = inputName.replace('Upload', 'Value');
                    let hiddenInput = document.querySelector(`input[type="hidden"][name="${hiddenInputName}"]`);
                    
                    if (!hiddenInput) {
                        hiddenInput = document.createElement('input');
                        hiddenInput.type = 'hidden';
                        hiddenInput.name = hiddenInputName;
                        this.parentNode.appendChild(hiddenInput);
                    }
                    
                    hiddenInput.value = imageKey;
                    console.log(`[DEBUG] Base64 image stored with key: ${imageKey}`);
                    
                    // Trigger form update
                    updateConfigLog();
                };
                
                reader.onerror = (error) => {
                    console.error('[ERROR] File reading failed:', error);
                };
                
                reader.readAsDataURL(this.files[0]);
            });
        });

        // Handle form changes
        document.getElementById('configForm').addEventListener('input', function() {
            updateConfigLog();
        });

        // Form submission
        document.getElementById('configForm').addEventListener('submit', function(e) {
            e.preventDefault();
            console.log('[DEBUG] Form submission started');
            
            const formData = new FormData(this);
            const config = buildConfigObject(formData);
            console.log('[DEBUG] Final configuration:', config);
            
            // Here you would typically send the config to your server
            // fetch('/save-config', { method: 'POST', body: JSON.stringify(config) })
            // .then(response => response.json())
            // .then(data => console.log('Success:', data))
            // .catch(error => console.error('Error:', error));
             fetch('/publish', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    config,
                    topic: formData.get('topic')
                })
            })
            .then(() => {
                console.log('[DEBUG] Configuration published successfully');
                alert('Configuration published successfully!');
            })
            .catch(err => {
                console.error('[ERROR] Publish failed:', err);
            });
            
            // For demo purposes, just log to console
            console.log('Configuration ready to save:', config);
            alert('Configuration saved successfully! (Check console for details)');
        });
    }

    // Build configuration object
    function buildConfigObject(formData) {
        console.group('[DEBUG] Building configuration object');
        
        const config = {
            type: "configuration",
            navItems: [],
            mainLogo: getLogoConfig(formData, 'mainLogo'),
            footerLogo: getLogoConfig(formData, 'footerLogo'),
            footerLogoVisibility: formData.get('footerLogoVisibility') === 'on',
            footerGreetingText: formData.get('footerGreetingText'),
            footerText: formData.get('footerText'),
            primaryColor: formData.get('primaryColor')
        };

        // Process navigation items
        for (let i = 0; i < 4; i++) {
            const prefix = `navItems[${i}]`;
            if (formData.get(`${prefix}[navName]`)) {
                config.navItems.push(getNavItemConfig(formData, prefix));
            }
        }

        console.groupEnd();
        return config;
    }

    function getLogoConfig(formData, prefix) {
        const type = formData.get(`${prefix}Type`);
        let value = null;
        
        if (type === 'resource') {
            value = formData.get(`${prefix}Resource`);
        } 
        else if (type === 'base64') {
            const storageKey = formData.get(`${prefix}Value`);
            value = imageStore.getBase64(storageKey);
        }
        
        console.log(`[DEBUG] ${prefix} config - type: ${type}, value: ${value ? 'exists' : 'null'}`);
        return { 
            type, 
            value,
            // Helper method to get the actual image URL
            getImageUrl: function() {
                if (this.type === 'resource') {
                    return imageStore.getStaticImage(this.value);
                } 
                else if (this.type === 'base64' && this.value) {
                    return this.value; // Already a data URL
                }
                return null;
            }
        };
    }

    function getNavItemConfig(formData, prefix) {
        return {
            navPage: formData.get(`${prefix}[navPage]`),
            navName: formData.get(`${prefix}[navName]`),
            icon: {
                type: formData.get(`${prefix}[icon][type]`),
                value: formData.get(`${prefix}[icon][value]`)
            },
            position: parseInt(formData.get(`${prefix}[position]`)) || 0,
            enabled: formData.get(`${prefix}[enabled]`) === 'on'
        };
    }

    // Update config log display
    function updateConfigLog() {
        const formData = new FormData(document.getElementById('configForm'));
        const config = buildConfigObject(formData);
        
        // Create a display-friendly version of the config
        const displayConfig = {
            ...config,
            mainLogo: {
                type: config.mainLogo.type,
                value: config.mainLogo.value ? '[...base64 data...]' : null
            },
            footerLogo: {
                type: config.footerLogo.type,
                value: config.footerLogo.value ? '[...base64 data...]' : null
            }
        };
        
        document.getElementById('configLog').value = JSON.stringify(displayConfig, null, 2);
        console.log('[DEBUG] Config log updated');
    }

    // Initialize the application
    initializeForm();
    updateConfigLog();
});