export function generateTkinterCode(json: any): string {

    let width = 500;
    let height = 400;
    let title = 'Form';
    
    // GrapesJS Wrapper data
    if (json && json.pages && json.pages[0] && json.pages[0].frames) {
        const wrapper = json.pages[0].frames[0].component;
        if (wrapper && wrapper.attributes) {
            if (wrapper.attributes['data-width']) width = wrapper.attributes['data-width'];
            if (wrapper.attributes['data-height']) height = wrapper.attributes['data-height'];
            if (wrapper.attributes['data-title']) title = wrapper.attributes['data-title'];
        }
    }

    let pythonCode = `import tkinter as tk\n\nroot = tk.Tk()\nroot.title('${title}')\nroot.geometry('${width}x${height}')\n\n`;

    let widgetCounter = 0;

    function processComponent(component: any, parentName: string) {
        const attrs = component.attributes || {};
        const type = attrs['data-tk-type'];
        
        if (!type) {
            if (component.components) {
                component.components.forEach((child: any) => processComponent(child, parentName));
            }
            return;
        }

        widgetCounter++;
        const widgetName = `${type.toLowerCase()}_${widgetCounter}`;
        
        // 1. КОНСТРУКТОР 
        let optionsParts = [parentName];
        
        let text = attrs['data-text'];
        if (!text) text = component.traits?.find((t: any) => t.name === 'text')?.value;

        const noTextTypes = ['Entry', 'Canvas', 'Listbox', 'Text', 'Frame'];
        if (!noTextTypes.includes(type) && text) optionsParts.push(`text="${text}"`);

        if (attrs['data-bg']) optionsParts.push(`bg="${attrs['data-bg']}"`);
        if (attrs['data-fg']) optionsParts.push(`fg="${attrs['data-fg']}"`);

        const optionsStr = optionsParts.join(', ');
        if (type === 'Frame') {
            pythonCode += `${widgetName} = tk.Frame(${optionsStr}, relief="groove", borderwidth=2)\n`;
        } else {
            pythonCode += `${widgetName} = tk.${type}(${optionsStr})\n`;
        }

        // 2. ГЕОМЕТРИЯ (Place)
        const x = attrs['data-x'] || 0;
        const y = attrs['data-y'] || 0;
        const w = attrs['data-width'];
        const h = attrs['data-height'];

        let placeParts = [`x=${x}`, `y=${y}`];
        if (w) placeParts.push(`width=${w}`);
        if (h) placeParts.push(`height=${h}`);
        pythonCode += `${widgetName}.place(${placeParts.join(', ')})\n`;

        // 3. КОНТЕНТ
        if (type === 'Entry' && text) pythonCode += `${widgetName}.insert(0, "${text}")\n`;
        if (type === 'Text' && text) {
            const safeText = text.replace(/\n/g, '\\n');
            pythonCode += `${widgetName}.insert("1.0", "${safeText}")\n`;
        }
        if (type === 'Listbox' && attrs['data-items']) {
            const items = attrs['data-items'].split('\n');
            items.forEach((item: string) => { if(item.trim()) pythonCode += `${widgetName}.insert(tk.END, "${item}")\n`; });
        }

        // 4. РЕКУРСИЯ
        if (component.components) {
            component.components.forEach((child: any) => processComponent(child, widgetName));
        }
        pythonCode += "\n";
    }

    if (json && json.pages && json.pages[0] && json.pages[0].frames) {
        const rootComponents = json.pages[0].frames[0].component.components;
        if (rootComponents) {
            rootComponents.forEach((comp: any) => processComponent(comp, 'root'));
        }
    }

    pythonCode += "\nroot.mainloop()";
    return pythonCode;
}