// wireframe-renderer.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { SiteTreeservice } from '../SiteBuilderGrid/SiteTree.service';
import { COMMON_CSS } from './common-css';
import { ToastrService } from 'ngx-toastr';


@Component({
    selector: 'app-wireframe-renderer',
    templateUrl: './wireframe-renderer.component.html',
    styleUrls: ['./wireframe-renderer.component.scss']
})
export class WireframeRendererComponent implements OnInit {
    @Input() node: any;
    @Input() title: string = '';
    commonCss: string = COMMON_CSS;



    jsonInput = '';
    id: number;


    constructor(
        private siteTreeService: SiteTreeservice,
        private route: ActivatedRoute,
        private sanitizer: DomSanitizer,
        private toastr: ToastrService,



    ) { }

    ngOnInit(): void {
        this.id = this.route.snapshot.params['id'];

        console.log(' id is :  ', this.id)

        this.fetchTreeById(this.id);
    }
    // wireframe-renderer.component.ts (add this helper method)
    getKeys(obj: any): string[] {
        return Object.keys(obj || {});
    }

    // Step 1
    fetchTreeById(id: number) {
        this.siteTreeService.getById(id).subscribe({
            next: (res) => {
                console.log('📥 Fetched from getById:', res);

                // Check if model key exists and has some value
                if (res && res.model) {
                    try {
                        // Optional: if model is already a stringified JSON
                        const maybeParsed = typeof res.model === 'string' ? JSON.parse(res.model) : res.model;
                        this.jsonInput = JSON.stringify(maybeParsed, null, 2);

                        this.generatePromptsForAllSections(this.jsonInput);
                    } catch (err) {
                        console.error('❌ Error parsing model JSON:', err);
                        alert('Model data is not valid JSON format');
                    }
                } else {
                    console.warn('⚠️ Model key not found or empty, keeping inputJson as is.');
                }
            },
            error: (err) => {
                console.error('❌ Error in getById:', err);
                // alert('Failed to fetch data from server');
            }
        });
    }
    // all prompt in one map

    allPagePrompts: Record<string, Record<string, string>> = {};
    initialGeneratedPrompts: Record<string, Record<string, string>> = {};


    // Recursively walk the tree and generate prompts for each section

    // Step 2
    async generatePromptsForAllSections(treeJsonString: string) {
        try {
            const parsedTree = JSON.parse(treeJsonString);
            await this.processPages(parsedTree);
        } catch (e) {
            // alert('❌ Invalid JSON format');
            console.error('❌ Invalid JSON format', e);
        }
    }

    // Step 3
    async processPages(treeJson: any) {

        console.log('tree is : ', treeJson)
        for (const [pageName, sections] of Object.entries(treeJson)) {

            // child page prompt map
            const sectionPrompts: Record<string, string> = {};

            if (sections['Children']) {
                // 👇 Recursively handle child pages
                console.log(' child is : ', sections['Children'])
                // this.generatePromptsForAllSections(sections['Children']);
                await this.processPages(sections['Children']); // ✅ Fix: recursive + awaited

            }

            // Loop other sections
            for (const [sectionName, sectionDescription] of Object.entries(sections)) {

                if (sectionName === 'Children') continue; // already handled

                console.log('✅ Generating prompt for:', pageName, sectionName);
                console.log('sc name  sectionDescription : ', sectionName, ' ', sectionDescription)

                const prompt = await this.generatePromptFromSection(sectionName, sectionDescription); // ✅ await
                sectionPrompts[sectionName] = prompt;
            }

            // 🧠 Store all prompts for that page
            this.allPagePrompts[pageName] = sectionPrompts;
            this.initialGeneratedPrompts[pageName] = JSON.parse(JSON.stringify(sectionPrompts)); // Deep clone

        }

        console.log('✅ FINAL PROMPT MAP:', this.allPagePrompts);

        await this.processAllPagesLiveUpdate()
    }

    get objectKeys() {
        return Object.keys;
    }


    jsonsuffixprompt = `Make sure the layout is clean, semantic, and responsive. Use only HTML (no CSS or JS).
                    🚫 Do NOT include:
- Any explanation, extra text, or markdown
- Code fences like \`\`\`html or \`\`\`css
- Alternative versions or comments

✅ Only return a single, production-ready, semantic HTML block.
✅ Respect image/icon placeholders using their width/height.
✅ Use clean structure with appropriate tags like <header>, <nav>, <ul>, <button>, etc.”
Only return the clean semantic HTML structure. 
❌ Do not return any inline style.
❌ Do not use position: absolute or fixed unless necessary.
✅ Use class-based layout with proper div wrapping using flexbox or CSS grid.
✅ Maintain readable, balanced structure with default flow.

HTML Only. No CSS.

✅ Output MUST be raw HTML ONLY.`;

    withoutjsonsuffixprompt = `Make sure the layout is clean, semantic, and responsive. Use only HTML (no CSS or JS).
🚫 Do NOT include:
- Any explanation or markdown formatting
- Comments or alternate versions
- Any text like “Here's the HTML...” or “Below is...”

✅ Just return a clean, single block of HTML code.
✅ Focus on layout that matches a modern UI — semantic, responsive, and readable.
✅ Use placeholders for image/icon blocks where appropriate (e.g., <div style="width:100px;height:30px;background:#ccc;"></div>)`;


    // Step 4
    generatePromptFromSection(
        sectionName: string,
        sectionDescription: string,
        headerId: number = 35,
        operationType: string = 'template 1',
    ): Promise<string> {
        return new Promise((resolve) => {
            // const fieldType = sectionName.toLowerCase().replace(/\s+/g, '').replace(/section$/, '').trim();
            const fieldType = sectionName
            .toLowerCase()
            .replace(/section$/i, '')        // remove trailing 'section'
            .replace(/\s{2,}/g, ' ')         // multiple spaces to single space
            .trim();                         // trim leading/trailing spaces
          
            this.siteTreeService.getDlf(headerId, operationType, fieldType).subscribe({
                next: (res) => {
                    try {
                        const jsonBlock = res?.javacode;
                        if (jsonBlock) {
                            const parsedJson = typeof jsonBlock === 'string' ? JSON.parse(jsonBlock) : jsonBlock;

                            // const updatedJson = this.replaceContentRecursively(parsedJson, sectionDescription);
                            const finalJsonString = JSON.stringify(parsedJson, null, 2);

                            resolve(finalJsonString);
                        } else {
                            console.warn('⛔ No JSON found, skipping.');
                            resolve('{}');
                        }
                    } catch (err) {
                        console.error('❌ JSON parse error:', err);
                        resolve('{}');
                    }
                },
                error: (err) => {
                    console.error('❌ API error:', err);
                    resolve('{}');
                }
            });
        });
    }


    // replaceContentRecursively(obj: any, replacement: string): any {
    //     if (Array.isArray(obj)) {
    //         return obj.map(item => this.replaceContentRecursively(item, replacement));
    //     } else if (typeof obj === 'object' && obj !== null) {
    //         const updated = {};
    //         for (const [key, value] of Object.entries(obj)) {
    //             // Replace specific fields if they are strings
    //             if (['description', 'text', 'label', 'title', 'subtext'].includes(key.toLowerCase()) && typeof value === 'string') {
    //                 updated[key] = replacement;
    //             } else {
    //                 updated[key] = this.replaceContentRecursively(value, replacement);
    //             }
    //         }
    //         return updated;
    //     }
    //     return obj;
    // }


    pageHtmlMap: Record<string, string> = {};
    generatedPages: { name: string, html: string }[] = [];

    pageSections: Record<string, { FullPage: SafeHtml }> = {}; // final UI map

    // Step 5 - generate html code via llm through prompt
    async processAllPagesLiveUpdate() {
        for (const [pageName, sectionMap] of Object.entries(this.allPagePrompts)) {
            const sectionHtmls: string[] = [];

            for (const [sectionName, promptText] of Object.entries(sectionMap)) {
                console.log(`🚀 Generating HTML for: ${pageName} > ${sectionName}`);

                const response = await this.generateJson({ sectionType: sectionName, jsonStructure: promptText });
                const html = response || '⚠️ No response received.';

                sectionHtmls.push(html);
            }

            // ✅ Inject common CSS once per page
            const htmlWithCss = `
        <style>${COMMON_CSS}</style>
        ${sectionHtmls.join('\n')}`;

            // ✅ Bypass Angular sanitizer
            const safeHtml: SafeHtml = this.sanitizer.bypassSecurityTrustHtml(htmlWithCss);

            this.pageSections[pageName] = { FullPage: safeHtml };
        }
    }

    // Step 6
    async generateJson(data: { jsonStructure: any, sectionType: string }): Promise<string> {
        return new Promise((resolve) => {
            try {
                const parsedJson =
                    typeof data.jsonStructure === 'string'
                        ? JSON.parse(data.jsonStructure)
                        : data.jsonStructure;

                const payload = {
                    sectionType: data.sectionType,
                    jsonStructure: parsedJson
                };

                console.log('📤 Sending to HTML API:', payload);

                this.siteTreeService.generateHtml(payload).subscribe({
                    next: (res) => {
                        console.log('✅ Response from HTML API:', res);
                        if (res && res.msg) {
                            resolve(res.msg);
                        } else {
                            resolve('⚠️ No response received from HTML API.');
                        }
                    },
                    error: (err) => {
                        console.error('❌ HTML API Error:', err);
                        resolve('⚠️ HTML API call failed.');
                    }
                });
            } catch (err) {
                console.error('❌ JSON parsing error before sending to API:', err);
                resolve('⚠️ Invalid JSON structure.');
            }
        });
    }

    // copy to clipboard
    copyToClipboard(pageName: string) {
        const fullHtml = Object.values(this.pageSections[pageName]).join('\n');
        navigator.clipboard.writeText(fullHtml).then(() => {
            alert(`📋 HTML copied for page: ${pageName}`);
        });
    }

    // dowlload as html
    downloadHtml(pageName: string) {
        const fullHtml = Object.values(this.pageSections[pageName]).join('\n');
        const blob = new Blob([fullHtml], { type: 'text/html' });
        const url = window.URL.createObjectURL(blob);

        const link = document.createElement('a');
        link.href = url;
        link.download = `${pageName}.html`;
        link.click();

        window.URL.revokeObjectURL(url);
    }


    // ✅ Call this method when user clicks "Save Files"
    uploadHtmlFiles(projId: number) {
        const pageHtmlMap: Record<string, string> = {};

        for (const [pageName, section] of Object.entries(this.pageSections)) {
            const html = section.FullPage?.toString() || '';
            pageHtmlMap[pageName] = html;
        }

        this.siteTreeService.createHtmlPages(pageHtmlMap, projId).subscribe(
            (data) => {
                console.log(data);
                if (data || data.status >= 200 && data.status <= 299) {
                    this.toastr.success("file Created");
                }
                setTimeout(() => {
                    this.ngOnInit();
                }, 500);

            }, (error) => {
                console.log(error);
                if (error.status >= 200 && error.status <= 299) {
                    this.toastr.success("file Created");
                }
                if (error.status >= 400 && error.status <= 499) {
                    this.toastr.error("Not Created");
                }
                if (error.status >= 500 && error.status <= 599) {
                    this.toastr.error("Not Created");
                }
            });
        setTimeout(() => {
            this.ngOnInit();
        }, 500);
    }


    // regenerate specific pages
    async regenerateWireframe(pageName: string) {
        const original = this.initialGeneratedPrompts[pageName];
        const current = this.allPagePrompts[pageName];

        const updatedSections: string[] = [];

        for (const section in current) {
            if (!original || original[section] !== current[section]) {
                updatedSections.push(section);
            }
        }

        if (updatedSections.length === 0) {
            alert('✅ No changes found to regenerate!');
            return;
        }

        const htmlBlocks: string[] = [];

        for (const section of updatedSections) {
            const jsonPrompt = current[section];
            const html = await this.generateJson({ jsonStructure: jsonPrompt, sectionType: section });
            htmlBlocks.push(html);

            console.log(`♻️ Regenerated section: ${pageName} > ${section}`);
        }

        // Inject only changed parts (append or replace)
        const finalHtml = `
          <style>${COMMON_CSS}</style>
          ${htmlBlocks.join('\n')}
        `;
        const safeHtml = this.sanitizer.bypassSecurityTrustHtml(finalHtml);

        this.pageSections[pageName] = { FullPage: safeHtml };
    }


    //   regenearte all pages
    async regenerateAllModifiedSections() {
        for (const [pageName, currentSections] of Object.entries(this.allPagePrompts)) {
            const originalSections = this.initialGeneratedPrompts[pageName] || {};
            const updatedSections: string[] = [];

            for (const sectionName in currentSections) {
                if (!originalSections[sectionName] || originalSections[sectionName] !== currentSections[sectionName]) {
                    updatedSections.push(sectionName);
                }
            }

            if (updatedSections.length === 0) {
                console.log(`✅ ${pageName} has no modified sections.`);
                continue;
            }

            const htmlBlocks: string[] = [];

            for (const section of updatedSections) {
                const jsonPrompt = currentSections[section];
                const html = await this.generateJson({ jsonStructure: jsonPrompt, sectionType: section });
                htmlBlocks.push(html);
                console.log(`♻️ Regenerated: ${pageName} > ${section}`);
            }

            const finalHtml = `
            <style>${COMMON_CSS}</style>
            ${htmlBlocks.join('\n')}
          `;

            const safeHtml = this.sanitizer.bypassSecurityTrustHtml(finalHtml);
            this.pageSections[pageName] = { FullPage: safeHtml };
        }

        alert('✅ Regeneration complete for all modified sections!');
    }


    // // Step 4
    // generatePromptFromSection(
    //     sectionName: string,
    //     sectionDescription: string,
    //     headerId: number = 35,
    //     operationType: string = 'template1'
    // ): Promise<string> {
    //     return new Promise((resolve, reject) => {
    //         const fieldType = sectionName.toLowerCase().replace(/\s+/g, '').replace(/section$/, '').trim();

    //         this.siteTreeService.getDlf(headerId, operationType, fieldType).subscribe({
    //             next: (res) => {
    //                 let prompt = `🎯 Generate ONLY the HTML structure for the following UI section. Do NOT include any explanation, markdown, or CSS.\n\n`;
    //                 prompt += `Section Name: ${sectionName}\n`;
    //                 prompt += `Description: ${sectionDescription}\n\n`;

    //                 try {
    //                     const jsonBlock = res?.javacode;
    //                     if (jsonBlock) {
    //                         prompt += `Below is the structural JSON definition of the section. Use it to map the layout and tags appropriately..\n\n`;
    //                         prompt += `JSON:\n${typeof jsonBlock === 'string' ? jsonBlock : JSON.stringify(jsonBlock, null, 2)}\n\n`;
    //                         prompt += this.jsonsuffixprompt;

    //                     } else {

    //                         prompt += `There is no structural JSON provided for this section.. Generate a reasonable HTML layout based on the description.\n\n`;
    //                         prompt += this.withoutjsonsuffixprompt;

    //                     }
    //                 } catch (err) {
    //                     prompt += `There is no structural JSON provided for this section. Use the description.`;
    //                     prompt += this.withoutjsonsuffixprompt;

    //                 }

    //                 resolve(prompt);
    //             },
    //             error: (err) => {
    //                 console.error('❌ API error:', err);
    //                 const fallbackPrompt = `🎯 Generate the HTML structure for the following section.\n\nSection Name: ${sectionName}\nDescription: ${sectionDescription}\n\nThere is no structural JSON provided for this section.` + this.withoutjsonsuffixprompt;
    //                 resolve(fallbackPrompt);
    //             }
    //         });
    //     });
    // }




    // // Step 6
    //     async generateJson(data): Promise<string> {
    //         return new Promise((resolve, reject) => {
    //             console.log('genearte json start  ')
    //             const payload = {
    //                 query: data.message,
    //                 conversationId: '677'
    //             };
    //             console.log(' query : ', payload.query)
    //             this.siteTreeService.generateJson(payload).subscribe({
    //                 next: (res) => {
    //                     console.log('response ', res)
    //                     if (res && res.responseContent) {
    //                         resolve(res.responseContent);
    //                     } else {
    //                         resolve('⚠️ No response received.');
    //                     }
    //                 },
    //                 error: () => resolve('⚠️ LLaMA API failed.')

    //             });
    //         });
    //     }
    // pageSections: Record<string, Record<string, string>> = {}; // { pageName: { sectionName: html } }

    // async processAllPagesLiveUpdate() {
    //     for (const [pageName, sectionMap] of Object.entries(this.allPagePrompts)) {
    //         if (!this.pageSections[pageName]) {
    //             this.pageSections[pageName] = {};
    //         }

    //         let sectionHtmls: string[] = [];

    //         for (const [sectionName, promptText] of Object.entries(sectionMap)) {
    //             console.log(`🚀 Sending: [${pageName} > ${sectionName}]`);

    //             const response = await this.generateJson({ message: promptText });
    //             const html = response || '⚠️ No response received.';

    //             sectionHtmls.push(html); // collect all HTMLs

    //             // ✅ LIVE update for UI
    //             //         const htmlWithCss = `
    //             //   <style>${COMMON_CSS}</style>
    //             //   ${html}`;

    //             // this.pageSections[pageName][sectionName] = htmlWithCss;
    //             this.pageSections[pageName][sectionName] = html;
    //         }


    //     }
    // }

    // async processAllPagesWithLlama() {
    //     for (const [pageName, sectionMap] of Object.entries(this.allPagePrompts)) {
    //         const sectionHtmls: Record<string, string> = {};

    //         for (const [sectionName, promptText] of Object.entries(sectionMap)) {
    //             console.log(`⚡ Sending to LLaMA: [${pageName} > ${sectionName}]`);

    //             const llamaResponse = await this.generateJson({ message: promptText });
    //             sectionHtmls[sectionName] = llamaResponse || '⚠️ No response';
    //         }

    //         // Combine all sections into one page HTML
    //         const fullPageHtml = Object.entries(sectionHtmls)
    //             .map(([sectionName, html]) => `<!-- ${sectionName} -->\n${html}`)
    //             .join('\n\n');

    //         // Save this complete page in key-value store
    //         this.pageHtmlMap[pageName] = fullPageHtml;

    //         // ✅ Show in UI
    //         this.generatedPages.push({ name: pageName, html: fullPageHtml });

    //         console.log(`✅ Page generated: ${pageName}`);
    //     }
    // }

    // generatedPrompt: string = ''; // ✅ Declare here
    // 
    // generatePromptFromSection(
    //     sectionName: string,
    //     sectionDescription: string,
    //     headerId: number = 35,
    //     operationType: string = 'template1'
    // ) {
    //     const fieldType = sectionName.toLowerCase().replace(/\s+/g, '');

    //     this.siteTreeService.getDlf(headerId, operationType, fieldType).subscribe({
    //         next: (res) => {
    //             console.log('📥 Fetched from dlf:', res);

    //             if (res) {
    //                 try {
    //                     const jsonBlock = res.javacode;
    //                     let prompt = `🎯 Generate the HTML structure for the following section.\n\n`;
    //                     prompt += `Section Name: ${sectionName}\n`;
    //                     prompt += `Description: ${sectionDescription}\n\n`;

    //                     if (jsonBlock) {
    //                         prompt += `Below is the structural JSON definition of the section. Use this structure to map your HTML.\n\n`;
    //                         prompt += `JSON:\n${typeof jsonBlock === 'string' ? jsonBlock : JSON.stringify(jsonBlock, null, 2)}\n\n`;
    //                     } else {
    //                         prompt += `No structural JSON is available for this section. Generate a reasonable HTML layout based on the description.\n\n`;
    //                     }

    //                     prompt += `Make sure the layout is clean, semantic, and responsive. Use only HTML (no CSS or JS).`;

    //                     // 🔧 Save it to a field or emit from here
    //                     this.generatedPrompt = prompt;

    //                 } catch (error) {
    //                     console.error('❌ Error generating prompt:', error);
    //                     this.generatedPrompt = '⚠️ Failed to generate prompt due to JSON error.';
    //                 }
    //             } else {
    //                 console.warn('⚠️ Model key not found or empty.');
    //                 this.generatedPrompt = `⚠️ No JSON model found. Please try again.`;
    //             }
    //         },
    //         error: (err) => {
    //             console.error('❌ Error got during :', err);
    //             let prompt = `🎯 Generate the HTML structure for the following section.\n\n`;
    //             prompt += `Section Name: ${sectionName}\n`;
    //             prompt += `Description: ${sectionDescription}\n\n`;


    //             prompt += `No structural JSON is available for this section. Generate a reasonable HTML layout based on the description.\n\n`;


    //             prompt += `Make sure the layout is clean, semantic, and responsive. Use only HTML (no CSS or JS).`;

    //             // 🔧 Save it to a field or emit from here
    //             this.generatedPrompt = prompt;

    //             // alert('Failed to fetch data from server!');
    //         }
    //     });
    // }


    // generatePromptsForAllSections(treeJson: any) {

    //     for (const [pageName, sections] of Object.entries(treeJson)) {
    //         const sectionPrompts: Record<string, string> = {};

    //         for (const [sectionName, sectionDescription] of Object.entries(sections)) {
    //             if (sectionName === 'Children') {

    //                 // Recursively process child pages
    //                 const children = sections['Children'];

    //                 console.log(' child is : ', children)

    //                 const childPrompts = this.generatePromptsForAllSections(children);
    //                 Object.assign(this.allPagePrompts, childPrompts);
    //             } else {

    //                 console.log('sc name  sectionDescription : ', sectionName, ' ', sectionDescription)

    //                 this.generatePromptFromSection(sectionName, sectionDescription);
    //                 sectionPrompts[sectionName] = this.generatedPrompt;
    //             }
    //         }

    //         this.allPagePrompts[pageName] = sectionPrompts;
    //     }

    //     console.log(' all page prompt is :', this.allPagePrompts);

    // }



    // dynamic prompt generation
    // generatePromptFromSection(
    //     sectionName: string,
    //     sectionDescription: string,
    //     headerId: number = 35,
    //     operationType: string = 'template1'
    // ) {

    //     const fieldType = sectionName.toLowerCase().replace(/\s+/g, '');
    //     this.siteTreeService.getDlf(headerId, operationType, fieldType).subscribe({
    //         next: (res) => {
    //             console.log('📥 Fetched from dlf:', res);

    //             // Check if model key exists and has some value
    //             if (res && res.javacode) {


    //                 try {

    //                     const jsonBlock = res?.javaCode;

    //                     let prompt = `🎯 Generate the HTML structure for the following section.\n\n`;
    //                     prompt += `Section Name: ${sectionName}\n`;
    //                     prompt += `Description: ${sectionDescription}\n\n`;

    //                     if (jsonBlock) {
    //                         prompt += `Below is the structural JSON definition of the section. Use this structure to map your HTML.\n\n`;
    //                         prompt += `JSON:\n${typeof jsonBlock === 'string' ? jsonBlock : JSON.stringify(jsonBlock, null, 2)}\n\n`;
    //                     } else {
    //                         prompt += `No structural JSON is available for this section. Generate a reasonable HTML layout based on the description.\n\n`;
    //                     }

    //                     prompt += `Make sure the layout is clean, semantic, and responsive. Use only HTML (no CSS or JS).`;

    //                     return prompt;

    //                 } catch (error) {
    //                     console.error('Error generating prompt:', error);
    //                     return '⚠️ Failed to generate prompt due to API error.';
    //                 }
    //             } else {
    //                 console.warn('⚠️ Model key not found or empty, keeping inputJson as is.');
    //             }
    //         },
    //         error: (err) => {
    //             console.error('❌ Error got:', err);
    //             alert('Failed to fetch data from Server!');
    //         }
    //     });

    // }



}
