// Demo Application for Form Builder
// This file contains demo-specific code and should not be part of the core library

// Example schema for demonstration
const EXAMPLE_SCHEMA = {
    "version": "0.3",
    "title": "Asset Uploader with Slides",
    "elements": [
        {
            "type": "file",
            "key": "cover",
            "label": "Изображение товара",
            "description": "Source of facts: Use only the description text and visible labels/markings in the photo. Target scene: Show the product in a real-life usage context, highlighting its purpose and benefits. Product integrity: Do not change geometry, proportions, color, texture, hardware/stitching, or functional elements.",
            "required": true,
            "accept": {
                "extensions": ["png", "jpg", "gif"],
                "mime": ["image/png", "image/jpeg", "image/gif"]
            },
            "maxSizeMB": 10
        },
        {
            "type": "files",
            "key": "assets",
            "label": "Другие изображения",
            "description": "Additional images that provide context, show different angles, or demonstrate product usage. These will be used to enhance the infographic composition.",
            "required": false,
            "accept": {
                "extensions": ["png", "jpg", "gif"],
                "mime": ["image/png", "image/jpeg", "image/gif"]
            },
            "minCount": 0,
            "maxCount": 10,
            "maxSizeMB": 5
        },
        {
            "type": "text",
            "key": "title",
            "label": "Название товара",
            "placeholder": "Введите название товара",
            "description": "The exact product name as it should appear on the infographic. Use the official product name without marketing terms or decorative elements.",
            "required": true,
            "minLength": 1,
            "maxLength": 100,
            "pattern": "^[A-Za-zА-Яа-я0-9 _*-]+$",
            "default": ""
        },
        {
            "type": "textarea",
            "key": "description",
            "label": "Описание товара",
            "placeholder": "Введите описание товара",
            "description": "Detailed product description focusing on key features, benefits, and usage scenarios. This text will be used to create compelling infographic content.",
            "required": false,
            "minLength": 0,
            "maxLength": 500,
            "pattern": "^[A-Za-zА-Яа-я0-9 ,.!?()_-]*$",
            "default": ""
        },
        {
            "type": "select",
            "key": "theme",
            "label": "Тема",
            "placeholder": "Выберите тему",
            "description": "Visual theme that determines color scheme, typography, and overall aesthetic of the generated infographic.",
            "required": true,
            "options": [
                {"value": "", "label": "Выберите тему"},
                {"value": "modern-minimal", "label": "Современный минимализм"},
                {"value": "warm-vintage", "label": "Теплый винтаж"},
                {"value": "tech-blue", "label": "Технологичный синий"},
                {"value": "nature-green", "label": "Природный зеленый"},
                {"value": "luxury-gold", "label": "Роскошный золотой"}
            ],
            "default": ""
        },
        {
            "type": "number",
            "key": "opacity",
            "label": "Прозрачность",
            "placeholder": "0.50",
            "description": "Transparency level for background elements in the infographic. Values between 0 (fully transparent) and 1 (fully opaque).",
            "required": true,
            "min": 0,
            "max": 1,
            "decimals": 2,
            "step": 0.01,
            "default": 0.50
        },
        {
            "type": "group",
            "key": "slides",
            "label": "Слайды",
            "description": "Additional slides to showcase different aspects of your product. Each slide can have its own main image and decorative elements to create a comprehensive infographic presentation.",
            "repeat": {"min": 1, "max": 5},
            "elements": [
                {
                    "type": "text",
                    "key": "title",
                    "label": "Заголовок слайда",
                    "required": true,
                    "minLength": 1,
                    "maxLength": 80,
                    "pattern": "^[A-Za-zА-Яа-я0-9 _*-]+$",
                    "default": ""
                },
                {
                    "type": "textarea",
                    "key": "body",
                    "label": "Текст слайда",
                    "required": true,
                    "minLength": 1,
                    "maxLength": 1000,
                    "pattern": "^[A-Za-zА-Яа-я0-9 ,.!?()_*-]*$",
                    "default": ""
                }
            ]
        }
    ]
};

// DOM element references for demo app
const el = {
    schemaInput: document.getElementById('schemaInput'),
    schemaErrors: document.getElementById('schemaErrors'),
    applySchemaBtn: document.getElementById('applySchemaBtn'),
    resetSchemaBtn: document.getElementById('resetSchemaBtn'),
    prettySchemaBtn: document.getElementById('prettySchemaBtn'),
    downloadSchemaBtn: document.getElementById('downloadSchemaBtn'),
    formContainer: document.getElementById('formContainer'),
    formErrors: document.getElementById('formErrors'),
    submitBtn: document.getElementById('submitBtn'),
    saveDraftBtn: document.getElementById('saveDraftBtn'),
    clearFormBtn: document.getElementById('clearFormBtn'),
    outputJson: document.getElementById('outputJson'),
    copyOutputBtn: document.getElementById('copyOutputBtn'),
    downloadOutputBtn: document.getElementById('downloadOutputBtn'),
    shareUrlBtn: document.getElementById('shareUrlBtn'),
    prefillInput: document.getElementById('prefillInput'),
    loadPrefillBtn: document.getElementById('loadPrefillBtn'),
    copyTemplateBtn: document.getElementById('copyTemplateBtn'),
    prefillErrors: document.getElementById('prefillErrors'),
    urlInfo: document.getElementById('urlInfo'),
    // Readonly demo elements
    readonlySchemaInput: document.getElementById('readonlySchemaInput'),
    applyReadonlyBtn: document.getElementById('applyReadonlyBtn'),
    clearReadonlyBtn: document.getElementById('clearReadonlyBtn'),
    readonlyErrors: document.getElementById('readonlyErrors'),
    readonlyDemoContainer: document.getElementById('readonlyDemoContainer')
};

// Utility functions (using FormBuilder.pretty)
function pretty(obj) {
    return FormBuilder.pretty(obj);
}

function showError(element, message) {
    if (element) {
        element.textContent = message;
        element.classList.remove('hidden');
    }
}

function clearError(element) {
    if (element) {
        element.textContent = '';
        element.classList.add('hidden');
    }
}

function downloadFile(filename, content) {
    const blob = new Blob([content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
}

// Demo event handlers
el.applySchemaBtn.addEventListener('click', () => {
    clearError(el.schemaErrors);
    try {
        const schema = JSON.parse(el.schemaInput.value);
        const errors = FormBuilder.validateSchema(schema);
        
        if (errors.length > 0) {
            showError(el.schemaErrors, 'Schema validation errors: ' + errors.join(', '));
            return;
        }
        
        FormBuilder.renderForm(schema, {});
        el.outputJson.value = '';
        clearError(el.formErrors);
    } catch (e) {
        showError(el.schemaErrors, 'JSON parse error: ' + e.message);
    }
});

el.resetSchemaBtn.addEventListener('click', () => {
    el.schemaInput.value = pretty(EXAMPLE_SCHEMA);
    clearError(el.schemaErrors);
    FormBuilder.renderForm(EXAMPLE_SCHEMA, {});
    el.outputJson.value = '';
    el.prefillInput.value = '';
    clearError(el.prefillErrors);
});

el.prettySchemaBtn.addEventListener('click', () => {
    try {
        const parsed = JSON.parse(el.schemaInput.value);
        el.schemaInput.value = pretty(parsed);
    } catch (e) {
        showError(el.schemaErrors, 'Prettify: JSON parse error: ' + e.message);
    }
});

el.downloadSchemaBtn.addEventListener('click', () => {
    downloadFile('schema.json', el.schemaInput.value || pretty(EXAMPLE_SCHEMA));
});

el.clearFormBtn.addEventListener('click', () => {
    FormBuilder.clearForm();
    clearError(el.formErrors);
});

el.copyOutputBtn.addEventListener('click', async () => {
    try {
        await navigator.clipboard.writeText(el.outputJson.value || '');
        el.copyOutputBtn.textContent = 'Copied!';
        setTimeout(() => {
            el.copyOutputBtn.textContent = 'Copy JSON';
        }, 1000);
    } catch (e) {
        console.warn('Copy failed:', e);
    }
});

el.downloadOutputBtn.addEventListener('click', () => {
    downloadFile('form-data.json', el.outputJson.value || '{}');
});

el.shareUrlBtn.addEventListener('click', () => {
    try {
        const schema = JSON.parse(el.schemaInput.value);
        const schemaBase64 = btoa(JSON.stringify(schema));
        const url = `${window.location.origin}${window.location.pathname}?schema=${schemaBase64}`;
        navigator.clipboard.writeText(url);
        el.shareUrlBtn.textContent = 'URL Copied!';
        setTimeout(() => {
            el.shareUrlBtn.textContent = 'Share URL';
        }, 2000);
    } catch (e) {
        alert('Please apply a valid schema first');
    }
});

el.loadPrefillBtn.addEventListener('click', () => {
    clearError(el.prefillErrors);
    try {
        const pre = JSON.parse(el.prefillInput.value || '{}');
        const currentSchema = JSON.parse(el.schemaInput.value);
        FormBuilder.renderForm(currentSchema, pre);
        el.outputJson.value = '';
        clearError(el.formErrors);
    } catch (e) {
        showError(el.prefillErrors, 'JSON parse error: ' + e.message);
    }
});

el.copyTemplateBtn.addEventListener('click', () => {
    try {
        const schema = JSON.parse(el.schemaInput.value);
        const template = {};
        
        function processElements(elements, target) {
            elements.forEach(element => {
                if (element.type === 'group' && element.repeat) {
                    target[element.key] = [{}];
                    if (element.elements) {
                        processElements(element.elements, target[element.key][0]);
                    }
                } else if (element.type === 'group') {
                    target[element.key] = {};
                    if (element.elements) {
                        processElements(element.elements, target[element.key]);
                    }
                } else {
                    target[element.key] = element.default || null;
                }
            });
        }
        
        processElements(schema.elements, template);
        el.prefillInput.value = pretty(template);
    } catch (e) {
        showError(el.prefillErrors, 'Schema parse error: ' + e.message);
    }
});

// Form submission handlers
function submitFormEnhanced() {
    clearError(el.formErrors);
    
    const result = FormBuilder.getFormData();
    
    if (!result.valid) {
        showError(el.formErrors, 'Validation errors: ' + result.errors.join(', '));
        return;
    }
    
    // Convert resource IDs to file info for demo
    const processedData = JSON.parse(JSON.stringify(result.data));
    
    function replaceResourceIds(obj) {
        for (const key in obj) {
            if (typeof obj[key] === 'string' && obj[key].startsWith('res_')) {
                const meta = FormBuilder.state.resourceIndex.get(obj[key]);
                if (meta) {
                    obj[key] = {
                        resourceId: obj[key],
                        name: meta.name,
                        type: meta.type,
                        size: meta.size
                    };
                }
            } else if (Array.isArray(obj[key])) {
                obj[key].forEach(item => {
                    if (typeof item === 'string' && item.startsWith('res_')) {
                        const index = obj[key].indexOf(item);
                        const meta = FormBuilder.state.resourceIndex.get(item);
                        if (meta) {
                            obj[key][index] = {
                                resourceId: item,
                                name: meta.name,
                                type: meta.type,
                                size: meta.size
                            };
                        }
                    } else if (typeof item === 'object') {
                        replaceResourceIds(item);
                    }
                });
            } else if (typeof obj[key] === 'object' && obj[key] !== null) {
                replaceResourceIds(obj[key]);
            }
        }
    }
    
    replaceResourceIds(processedData);
    
    el.outputJson.value = pretty(processedData);
}

el.submitBtn.addEventListener('click', submitFormEnhanced);
el.saveDraftBtn.addEventListener('click', () => {
    const result = FormBuilder.getFormData();
    el.outputJson.value = pretty(result.data);
});

// Readonly demo handlers
el.applyReadonlyBtn.addEventListener('click', () => {
    clearError(el.readonlyErrors);
    try {
        const schema = JSON.parse(el.readonlySchemaInput.value);
        const errors = FormBuilder.validateSchema(schema);
        
        if (errors.length > 0) {
            showError(el.readonlyErrors, 'Schema validation errors: ' + errors.join(', '));
            return;
        }
        
        // Clear container
        el.readonlyDemoContainer.innerHTML = '';
        
        // Store original form settings
        const originalFormRoot = FormBuilder.state.formRoot;
        const originalMode = FormBuilder.state.config.readonly;
        
        try {
            // Temporarily use readonly container
            FormBuilder.setFormRoot(el.readonlyDemoContainer);
            FormBuilder.setMode('readonly');
            FormBuilder.renderForm(schema, DEFAULT_READONLY_DATA);
        } finally {
            // Restore original settings
            FormBuilder.setFormRoot(originalFormRoot);
            FormBuilder.state.config.readonly = originalMode;
        }
        
    } catch (e) {
        showError(el.readonlyErrors, 'JSON parse error: ' + e.message);
    }
});

el.clearReadonlyBtn.addEventListener('click', () => {
    el.readonlyDemoContainer.innerHTML = '<div class="text-center text-gray-500 py-8">Apply a schema to see readonly mode</div>';
    clearError(el.readonlyErrors);
});

// URL schema loading
function loadSchemaFromURL() {
    const urlParams = new URLSearchParams(window.location.search);
    const schemaParam = urlParams.get('schema');
    
    if (schemaParam) {
        try {
            const schema = JSON.parse(atob(schemaParam));
            el.schemaInput.value = pretty(schema);
            FormBuilder.renderForm(schema, {});
            el.urlInfo.classList.remove('hidden');
        } catch (e) {
            console.warn('Failed to load schema from URL:', e);
        }
    }
}

// Read-only demo functions
function downloadDemoFile(filePath, fileName) {
    console.log('downloadDemoFile called with:', filePath, fileName);
    
    // Check if we're running on a local dev server
    const isLocalDev = window.location.protocol === 'http:' && window.location.hostname === 'localhost';
    
    if (isLocalDev) {
        console.log('Running on local dev server, using fetch method');
        // Force download by fetching the file and creating a blob
        fetch(filePath)
            .then(response => {
                console.log('Fetch response:', response.ok, response.status);
                return response.blob();
            })
            .then(blob => {
                console.log('Creating download link for blob:', blob.size, 'bytes');
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = fileName;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(link.href);
                console.log('Download completed successfully');
            })
            .catch(error => {
                console.error('Fetch download failed:', error);
                simpleLinkDownload(filePath, fileName);
            });
    } else {
        console.log('Not on local dev server, using simple link method');
        simpleLinkDownload(filePath, fileName);
    }
}

function simpleLinkDownload(filePath, fileName) {
    console.log('Using simple link download:', filePath, fileName);
    const link = document.createElement('a');
    link.href = filePath;
    link.download = fileName;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    console.log('Simple link download triggered');
}

// Configure download handler for readonly demo
function setupReadonlyDemo() {
    // Set up download handler that works with local demo files
    FormBuilder.setDownloadHandler((resourceId, fileName) => {
        const demoFileMap = {
            'demo_infographic': 'images/infographic_draft.jpg',
            'demo_video': 'images/final_video.mp4'
        };
        
        const filePath = demoFileMap[resourceId] || `images/${fileName}`;
        downloadDemoFile(filePath, fileName);
    });
    
    // Set up thumbnail handler for demo (returns URL directly, not Promise)
    FormBuilder.setThumbnailHandler((resourceId) => {
        const demoFileMap = {
            'demo_infographic': 'images/infographic_draft.jpg',
            'demo_video': 'images/final_video.mp4'
        };
        
        return demoFileMap[resourceId] || null;
    });
    
    // Pre-populate demo resource metadata
    FormBuilder.state.resourceIndex.set('demo_infographic', {
        name: 'infographic_result.jpg',
        type: 'image/jpeg',
        size: 150000,
        file: null
    });
    
    FormBuilder.state.resourceIndex.set('demo_video', {
        name: 'final_video.mp4',
        type: 'video/mp4',
        size: 2500000,
        file: null
    });
}

// Default readonly schema for demo
const DEFAULT_READONLY_SCHEMA = {
    "version": "0.3",
    "title": "Результаты работы",
    "elements": [
        {
            "type": "file",
            "key": "result_image",
            "label": "Изображение результата",
            "description": "Готовая инфографика на основе загруженных данных"
        },
        {
            "type": "file", 
            "key": "result_video",
            "label": "Видео результат",
            "description": "Финальное видео презентации"
        }
    ]
};

// Default readonly data  
const DEFAULT_READONLY_DATA = {
    "result_image": "demo_infographic",
    "result_video": "demo_video"
};

function renderReadonlyDemo() {
    // Set default schema in textarea
    const textarea = document.getElementById('readonlySchemaInput');
    if (textarea && !textarea.value.trim()) {
        textarea.value = pretty(DEFAULT_READONLY_SCHEMA);
    }
}

// Initialize demo application
function initDemo() {
    // Set up the form builder for main form
    FormBuilder.setFormRoot(el.formContainer);
    
    // Set up handlers for readonly demo
    setupReadonlyDemo();
    
    // Initialize with example schema
    el.schemaInput.value = pretty(EXAMPLE_SCHEMA);
    FormBuilder.setMode('edit'); // Ensure main form is in edit mode
    FormBuilder.renderForm(EXAMPLE_SCHEMA, {});
    
    // Load schema from URL if present
    loadSchemaFromURL();
    
    // Initialize read-only demo
    setTimeout(renderReadonlyDemo, 500);
}

// Start the demo when the page loads
document.addEventListener('DOMContentLoaded', () => {
    // Wait for FormBuilder to be available
    if (typeof FormBuilder !== 'undefined') {
        initDemo();
    } else {
        // Fallback: wait a bit for scripts to load
        setTimeout(() => {
            if (typeof FormBuilder !== 'undefined') {
                initDemo();
            } else {
                console.error('FormBuilder not found!');
            }
        }, 100);
    }
});
