
import { Component, Input, OnInit, SecurityContext, ChangeDetectorRef, ViewChildren, QueryList } 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';
import * as sha256 from 'crypto-js/sha256';
import SHA256 from 'crypto-js/sha256';
import { CdkDrag, CdkDragDrop, CdkDropList, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';
import { trigger, transition, style, animate, state } from '@angular/animations';
import * as e from 'express';
import { json } from 'stream/consumers';

@Component({
    selector: 'app-wireframe-renderer',
    templateUrl: './wireframe-renderer.component.html',
    styleUrls: ['./wireframe-renderer.component.scss'],
    animations: [
    trigger('fadeIn', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate('200ms ease-out', style({ opacity: 1 }))
      ]),
      transition(':leave', [
        animate('200ms ease-in', style({ opacity: 0 }))
      ])
    ]),
    trigger('slideIn', [
      transition(':enter', [
        style({ transform: 'scale(0.9)', opacity: 0 }),
        animate('300ms ease-out', style({ transform: 'scale(1)', opacity: 1 }))
      ]),
      transition(':leave', [
        animate('200ms ease-in', style({ transform: 'scale(0.9)', opacity: 0 }))
      ])
    ]),
    trigger('buttonHover', [
      state('void', style({ transform: 'translateY(0)' })),
      state('hover', style({ transform: 'translateY(-2px)', boxShadow: '0 4px 8px rgba(0,0,0,0.2)' }))
    ]),
    trigger('focusBorder', [
      state('void', style({ borderColor: '#ccc' })),
      state('focus', style({ borderColor: '#1976d2', boxShadow: '0 0 0 2px rgba(25,118,210,0.2)' }))
    ]),
    trigger('pulseOnHover', [
      state('void', style({ backgroundColor: 'transparent' })),
      state('hover', style({ backgroundColor: 'rgba(0,0,0,0.05)' }))
    ])
  ]
})

export class WireframeRendererComponent implements OnInit {

    globalSections = [
    {
      type: 'Navbar',
      description: 'Main navigation bar for the website',
      icon: 'fas fa-bars',
      template: 'navbar'
    },
    {
      type: 'Footer',
      description: 'Website footer with links and information',
      icon: 'fas fa-shoe-prints',
      template: 'footer'
    }
  ];

  standardSections = [
    {
      type: 'Hero Header',
      description: 'Large banner section with call-to-action',
      icon: 'fas fa-flag',
      template: 'hero'
    },
    {
      type: 'CTA',
      description: 'Call-to-action section to drive conversions',
      icon: 'fas fa-bullhorn',
      template: 'cta'
    },
    {
      type: 'Features',
      description: 'Showcase product or service features',
      icon: 'fas fa-star',
      template: 'features'
    },
    {
      type: 'Pricing',
      description: 'Pricing tables and subscription plans',
      icon: 'fas fa-dollar-sign',
      template: 'pricing'
    },
    {
      type: 'Testimonials',
      description: 'Customer reviews and testimonials',
      icon: 'fas fa-quote-left',
      template: 'testimonials'
    },
    {
      type: 'Gallery',
      description: 'Image gallery or portfolio showcase',
      icon: 'fas fa-images',
      template: 'gallery'
    },
    {
      type: 'Contact',
      description: 'Contact form and information',
      icon: 'fas fa-envelope',
      template: 'contact'
    },
    {
      type: 'About',
      description: 'About us or company information section',
      icon: 'fas fa-info-circle',
      template: 'about'
    },
    {
      type: 'Services',
      description: 'Services or offerings section',
      icon: 'fas fa-cogs',
      template: 'services'
    },
    {
      type: 'Team',
      description: 'Meet the team section',
      icon: 'fas fa-users',
      template: 'team'
    }
  ];

  customSections = [
    {
      type: 'Custom 1',
      description: 'Custom section template 1',
      icon: 'fas fa-puzzle-piece',
      template: 'custom1'
    },
    {
      type: 'Custom 2',
      description: 'Custom section template 2',
      icon: 'fas fa-cube',
      template: 'custom2'
    }
  ];

    
  // Style controls
  liveStyles = {
    fontSize: '',
    fontWeight: '',
    textAlign: '',
    color: '#000000',
    background: '#ffffff'
  };

  // Data arrays
  fontSizes = ['12px', '14px', '16px', '18px', '20px', '24px', '28px'];
  fontWeights = ['normal', 'bold', 'lighter'];
  
  sectionTypes = [
    { value: 'header', label: 'Header' },
    { value: 'hero', label: 'Hero' },
    { value: 'features', label: 'Features' },
    { value: 'gallery', label: 'Gallery' },
    { value: 'pricing', label: 'Pricing' },
    { value: 'testimonials', label: 'Testimonials' },
    { value: 'contact', label: 'Contact' },
    { value: 'footer', label: 'Footer' }
  ];

    @Input() node: any;
    @Input() title: string = '';
    commonCss: string = COMMON_CSS;
    jsonInput = '';
    initialPrompt = '';
    id: number;
    allPagePrompts: Record<string, Record<string, string>> = {};
    initialGeneratedPrompts: Record<string, Record<string, string>> = {};
    promptHashCache: Record<string, string> = {};
    pageSections: Record<string, { FullPage: SafeHtml }> = {};
    sectionHtmls: Record<string, Record<string, SafeHtml>> = {};
    isLoading: boolean = true;
    sitename = '';

    sidebarCollapsed: boolean = false;

newlyGeneratedPages: string[] = [];

// Add toggle method


deployedUrl: string | null = null;
    // Added properties for grid and drag functionality
    hoveredPage: string | null = null;
    hoveredSection: string | null = null;
    scale: number = 1;
    panX: number = 0;
    panY: number = 0;
    isPanning: boolean = false;
    lastX: number = 0;
    lastY: number = 0;
    isDragging = false;
startPanPosition = { x: 0, y: 0 };
    // Edit mode properties
    editMode: boolean = false;
    editingSection: { page: string, section: string } | null = null;
    editingSectionHtml: SafeHtml | null = null;
    
    // New section modal properties
    showNewSectionModal: boolean = false;
    newSectionPage: string = '';
    newSectionName: string = '';
    newSectionType: string = '';
    newSectionDescription: string = '';
    newSectionAfter: string | null = null;

 

    sidebarOpen = false;
    // Add this property to fix template errors

  // Page and section management
  pageRenderOrder: string[] = [];
  
  // need help with all the errors 


  // Mock data - replace with your actual data structures
  navbarLinks: { [key: string]: any[] } = {};
  availablePages: { href: string, label: string }[] = [];
  selectedPageForNavbar: string = '';

 zoomLevel = 1;
  currentPageIndex = 0;
  sectionOrderMap: { [key: string]: string[] } = {};

  // Add these new properties
  draggedSection: string | null = null;
  lastDeletedSection: { page: string; section: string; content: SafeHtml } | null = null;
  gridColumns = 12;
  gridGap = 16;

    searchTerm: string = '';

  // Section arrays

  // Navbar editor properties
  showNavbarEditorModal: boolean = false;
  currentNavbarLinks: any[] = [];

  // Add custom section modal properties
  showAddCustomModal: boolean = false;
  newCustomSectionName: string = '';
  newCustomSectionDesc: string = '';
  newCustomSectionIcon: string = 'fas fa-puzzle-piece';
  


    constructor(
        private siteTreeService: SiteTreeservice,
        private route: ActivatedRoute,
        private sanitizer: DomSanitizer,
        private toastr: ToastrService,
         private cdr: ChangeDetectorRef
    ) { }

//    sectionOrderMap: Record<string, string[]> = {};

// Initialize in ngOnInit()
siteId: number = 0; // Add this property to store siteId
async ngOnInit(): Promise<void> {
  try {
    this.id = this.route.snapshot.params['id'];
    console.log('id is: ', this.id);
    this.siteId = this.id;
    
    // First fetch the tree to get expected pages
    await this.fetchTreeById(this.id);
    
    const style = document.createElement('style');
    style.textContent = COMMON_CSS;
    document.head.appendChild(style);
  } catch (err) {
    console.error('Initial load error:', err);
  }
}

/**
 * Updated checkAllExistingFilesEnhanced method
 */
private async checkAllExistingFilesEnhanced(siteName: string, expectedPages: string[]): Promise<{
  existingFiles: Record<string, string>,
  extractedContent: Record<string, { css: string, bodyHtml: string, title: string }>
}> {
  const existingFiles: Record<string, string> = {};
  const extractedContent: Record<string, { css: string, bodyHtml: string, title: string }> = {};
  const formattedSite = this.formatSiteName(siteName);
  
  console.log(`🔍 Enhanced checking for existing files in: ${formattedSite}`);
  
  // Process each expected page
  const checkPromises = expectedPages.map(async (pageName) => {
    const sanitizedPageName = this.sanitizeFilename(pageName);
    
    try {
      const rawHtml = await this.tryReadHtmlFromServer(formattedSite, sanitizedPageName);
      
      if (rawHtml && rawHtml.trim() !== '') {
        console.log(`📄 Processing raw HTML for ${pageName}:`, rawHtml.substring(0, 200) + '...');
        
        // Parse the HTML response and extract content
        const parsed = this.parseHtmlResponse(rawHtml);
        
        if (parsed) {
          // Store the complete HTML for rendering - use the original HTML if it's already complete
          let completeHtml = rawHtml;
          
          // Only create new HTML structure if the original doesn't have proper HTML tags
          if (!rawHtml.includes('<!DOCTYPE') || !rawHtml.includes('<html')) {
            completeHtml = this.createCompleteHtml(pageName, parsed.css, parsed.bodyHtml);
          }
          
          existingFiles[pageName] = completeHtml;
          extractedContent[pageName] = parsed;
          
          console.log(`✅ Found and parsed existing file: ${sanitizedPageName}`);
        } else {
          console.log(`⚠️ Failed to parse existing file: ${sanitizedPageName}`);
        }
      } else {
        console.log(`❌ File not found or empty: ${sanitizedPageName}`);
      }
    } catch (error) {
      console.error(`❌ Error checking file ${sanitizedPageName}:`, error);
    }
  });
  
  // Wait for all checks to complete
  await Promise.all(checkPromises);
  
  console.log(`📊 Found ${Object.keys(existingFiles).length} existing files with extracted content`);
  return { existingFiles, extractedContent };
}



 ngAfterViewInit() {
  this.allConnectedLists = this.dropLists.toArray();
  
  // Handle cursor changes during drag
  this.dragItems.forEach(drag => {
    drag.started.subscribe(() => {
      document.body.style.cursor = 'grabbing';
    });
    
    drag.ended.subscribe(() => {
      document.body.style.cursor = '';
    });
  });
}
allConnectedLists: CdkDropList[] = [];

@ViewChildren(CdkDropList) dropLists!: QueryList<CdkDropList>;
@ViewChildren(CdkDrag) dragItems!: QueryList<CdkDrag>;


    // Helper method to get object keys
    objectKeys(obj: any): string[] {
        return Object.keys(obj || {});
    }

    toggleSectionEditing(pageName: string, sectionKey: string, event: Event): void {
  event.stopPropagation();
  
  if (this.isCurrentSectionEditing(sectionKey)) {
    this.editingSection = null;
  } else {
    this.editingSection = { page: pageName, section: sectionKey };
  }
  
  // Force change detection
  this.cdr.detectChanges();
}

    verifyCssInSections(): void {
        // First ensure common CSS is in the head
        this.ensureCommonCssForAllSections();
        
        // Check all section previews have proper styling
        const sectionPreviews = document.querySelectorAll('.section-preview');
        let fixedCount = 0;
        
        sectionPreviews.forEach((preview: HTMLElement) => {
        // If the preview doesn't have styling class, add it
        if (!preview.classList.contains('section-preview-styled')) {
            preview.classList.add('section-preview-styled');
            fixedCount++;
        }
        
        // Check if section has already embedded CSS
        if (!preview.querySelector('style[data-section-css]')) {
            // Create a new style element specifically for this section
            const sectionStyle = document.createElement('style');
            sectionStyle.setAttribute('data-section-css', 'true');
            sectionStyle.textContent = COMMON_CSS;
            preview.insertBefore(sectionStyle, preview.firstChild);
            fixedCount++;
        }
        });
        
        // Update full page rendering for each page to ensure correct CSS
        for (const pageName of this.objectKeys(this.pageSections)) {
        this.updateFullPageHtml(pageName);
        }
        
        this.toastr.success(`CSS verification complete. Fixed ${fixedCount} sections.`);
    }

    enhanceSectionWithClasses(html: string): string {
        // Add basic container classes if missing
        if (!html.includes('class="container"') && !html.includes('class="row"')) {
            // Add container class to the first div that has no class
            html = html.replace(/<div(?!\s+class=)/i, '<div class="container"');
        }
        
        // Add section classes if it's a section without class
        if (html.includes('<section') && !html.includes('<section class=')) {
            html = html.replace(/<section/i, '<section class="content-section"');
        }
        
        return html;
    }

     // Search functionality
  onSearchChange(): void {
    // The filtering is handled in getFilteredSections method
    this.cdr.detectChanges();
  }

  getFilteredSections(sections: any[]): any[] {
    if (!this.searchTerm || this.searchTerm.trim() === '') {
      return sections;
    }
    
    const term = this.searchTerm.toLowerCase().trim();
    return sections.filter(section => 
      section.type.toLowerCase().includes(term) ||
      section.description.toLowerCase().includes(term)
    );
  }

  // Add section from template
  addSectionFromTemplate(template: any): void {
    const currentPage = this.getCurrentPageName();
    if (!currentPage) {
      this.toastr.error('No page selected. Please create a page first.');
      return;
    }

    // Create section based on template
    const sectionKey = `${template.template}Section_${Date.now()}`;
    
    // Add to page prompts
    if (!this.allPagePrompts[currentPage]) {
      this.allPagePrompts[currentPage] = {};
    }

    const sectionJson = this.createSectionJson(template);
    this.allPagePrompts[currentPage][sectionKey] = JSON.stringify(sectionJson);

    // Generate HTML for the section
    this.generateSectionHtml(currentPage, sectionKey, sectionJson);
    
    this.toastr.success(`Added ${template.type} section to ${currentPage}`);
  }

  private createSectionJson(template: any): any {
    const baseJson = {
      type: template.template,
      title: template.type,
      description: template.description,
      content: this.getDefaultContent(template.template),
      styles: {
        background: "#ffffff",
        padding: "20px"
      }
    };

    return baseJson;
  }

  private getDefaultContent(templateType: string): any {
    const contentMap = {
      'navbar': {
        brand: 'Your Brand',
        links: [
          { text: 'Home', url: '#home' },
          { text: 'About', url: '#about' },
          { text: 'Services', url: '#services' },
          { text: 'Contact', url: '#contact' }
        ]
      },
      'footer': {
        copyright: '© 2025 Your Company. All rights reserved.',
        links: [
          { text: 'Privacy Policy', url: '#privacy' },
          { text: 'Terms of Service', url: '#terms' }
        ]
      },
      'hero': {
        title: 'Welcome to Our Amazing Service',
        subtitle: 'Transform your business with our innovative solutions',
        buttonText: 'Get Started',
        buttonUrl: '#contact'
      },
      'cta': {
        title: 'Ready to Get Started?',
        description: 'Join thousands of satisfied customers today',
        buttonText: 'Start Now',
        buttonUrl: '#signup'
      },
      'features': {
        title: 'Our Features',
        items: [
          { title: 'Feature 1', description: 'Amazing feature description' },
          { title: 'Feature 2', description: 'Another great feature' },
          { title: 'Feature 3', description: 'Yet another feature' }
        ]
      },
      'pricing': {
        title: 'Choose Your Plan',
        plans: [
          { name: 'Basic', price: '$9/month', features: ['Feature 1', 'Feature 2'] },
          { name: 'Pro', price: '$19/month', features: ['All Basic', 'Feature 3', 'Feature 4'] }
        ]
      }
    };

    return contentMap[templateType] || { text: 'Default content' };
  }

  private async generateSectionHtml(pageName: string, sectionKey: string, sectionJson: any): Promise<void> {
    try {
      const html = await this.generateJson({ 
        jsonStructure: sectionJson, 
        sectionType: sectionKey 
      });
      
      if (!this.sectionHtmls[pageName]) {
        this.sectionHtmls[pageName] = {};
      }
      
      this.sectionHtmls[pageName][sectionKey] = this.sanitizer.bypassSecurityTrustHtml(html);
      this.updateFullPageHtml(pageName);
      
    } catch (error) {
      console.error('Error generating section HTML:', error);
      this.toastr.error('Failed to generate section HTML');
    }
  }

  // Navbar Editor Methods
  showNavbarEditor(): void {
    this.showNavbarEditorModal = true;
    this.selectedNavbarPage = '';
    this.currentNavbarLinks = [];
  }

  closeNavbarEditorModal(): void {
    this.showNavbarEditorModal = false;
    this.selectedNavbarPage = '';
    this.currentNavbarLinks = [];
  }

  onNavbarPageChange(): void {
    if (this.selectedNavbarPage) {
      this.loadNavbarLinks();
    }
  }

 // Updated Navbar Editor Methods
async loadNavbarLinks(): Promise<void> {
  if (!this.selectedNavbarPage) return;

  // Clear existing links
  this.currentNavbarLinks = [];

  // Get the current page's HTML
  const pageHtml = this.pageSections[this.selectedNavbarPage]?.FullPage?.toString();
  if (!pageHtml) return;

  // Parse HTML to extract existing links
  const parser = new DOMParser();
  const doc = parser.parseFromString(pageHtml, 'text/html');
  const navLinks = doc.querySelectorAll('nav a, ul.nav-links a, .navbar a');

  // Convert NodeList to array of link objects
  this.currentNavbarLinks = Array.from(navLinks).map(link => {
    const href = link.getAttribute('href') || '';
    const isCustom = !this.availablePages.some(page => page.href === href);
    
    return {
      label: link.textContent?.trim() || 'New Link',
      href: isCustom ? 'custom' : href,
      customUrl: isCustom ? href : ''
    };
  });

  // Initialize if empty
  if (this.currentNavbarLinks.length === 0) {
    this.currentNavbarLinks.push({ 
      label: 'Home', 
      href: 'index.html', 
      customUrl: '' 
    });
  }

  // Update available pages
  this.availablePages = this.pageRenderOrder.map(page => ({
    label: page,
    href: `${page.toLowerCase().replace(/\s+/g, '-')}.html`
  }));
}

  addNavbarLink(): void {
    this.currentNavbarLinks.push({ 
      label: 'New Link', 
      href: '',
      customUrl: ''
    });
  }

  removeNavbarLink(index: number): void {
    this.currentNavbarLinks.splice(index, 1);
  }

async saveNavbarChanges(): Promise<void> {
  if (!this.selectedNavbarPage) {
    this.toastr.error('No page selected');
    return;
  }

  // Process custom URLs
  this.currentNavbarLinks.forEach(link => {
    if (link.href === 'custom' && link.customUrl) {
      link.href = link.customUrl;
    }
  });

  // Store the links
  this.navbarLinks[this.selectedNavbarPage] = [...this.currentNavbarLinks];

  // Update the actual navbar in the page HTML
  await this.updateNavbarInPage();
  
  this.toastr.success('Navbar updated successfully');
  this.closeNavbarEditorModal();
}

 private async updateNavbarInPage(): Promise<void> {
  const pageName = this.selectedNavbarPage;
  let pageHtml = this.pageSections[pageName]?.FullPage?.toString();
  if (!pageHtml) return;

  // Parse existing HTML
  const parser = new DOMParser();
  const doc = parser.parseFromString(pageHtml, 'text/html');
  
  // Find or create nav element
  let nav = doc.querySelector('nav') || doc.createElement('nav');
  nav.innerHTML = ''; // Clear existing links

  // Create new navbar structure
  const ul = doc.createElement('ul');
  ul.className = 'nav-links';
  
  this.currentNavbarLinks.forEach(link => {
    const li = doc.createElement('li');
    const a = doc.createElement('a');
    a.href = link.href;
    a.textContent = link.label;
    li.appendChild(a);
    ul.appendChild(li);
  });

  nav.appendChild(ul);
  
  // Replace or add the nav element
  const existingNav = doc.querySelector('nav');
  if (existingNav) {
    existingNav.replaceWith(nav);
  } else {
    doc.body.insertBefore(nav, doc.body.firstChild);
  }

  // Update the page HTML
  const newHtml = doc.documentElement.outerHTML;
  this.pageSections[pageName].FullPage = this.sanitizer.bypassSecurityTrustHtml(newHtml);
  
  // Update section HTML cache
  await this.generateSectionHtml(pageName, 'navbar', this.createNavbarJson());
}

private createNavbarJson(): any {
  return {
    type: 'navbar',
    title: 'Navigation Bar',
    description: 'Main website navigation',
    content: {
      links: this.currentNavbarLinks.map(link => ({
        text: link.label,
        url: link.href
      }))
    },
    styles: {
      background: "#ffffff",
      padding: "1rem"
    }
  };
}

loadProgress: number = 0;
private loadingInterval: any;

// Updated loading methods
/**
 * Enhanced loading management with progress tracking
 */
private updateLoadingProgress(progress: number, message: string): void {
  this.loadProgress = Math.min(Math.max(progress, 0), 100);
  this.loadingMessage = message;
  this.cdr.detectChanges();
  
  console.log(`📊 Loading Progress: ${progress}% - ${message}`);
}

// Add these properties to your component
loadingMessage: string = '';

// Update the showLoading method
showLoading(message?: string): void {
  this.isLoading = true;
  this.loadProgress = 0;
  this.loadingMessage = message || 'Loading...';
  
  // Clear any existing interval
  if (this.loadingInterval) {
    clearInterval(this.loadingInterval);
  }
  
  this.cdr.detectChanges();
}

// Update the hideLoading method
hideLoading(): void {
  this.isLoading = false;
  this.loadProgress = 100;
  this.loadingMessage = 'Complete!';
  
  // Clean up
  setTimeout(() => {
    if (this.loadingInterval) {
      clearInterval(this.loadingInterval);
      this.loadingInterval = null;
    }
    this.loadProgress = 0;
    this.loadingMessage = '';
    this.cdr.detectChanges();
  }, 300);
}

  // Custom Section Methods
  showAddCustomSectionModal(): void {
    this.showAddCustomModal = true;
    this.newCustomSectionName = '';
    this.newCustomSectionDesc = '';
    this.newCustomSectionIcon = 'fas fa-puzzle-piece';
  }

  closeAddCustomModal(): void {
    this.showAddCustomModal = false;
  }

  confirmAddCustomSection(): void {
    if (!this.newCustomSectionName.trim() || !this.newCustomSectionDesc.trim()) {
      this.toastr.error('Please fill in all required fields');
      return;
    }

    const newCustomSection = {
      type: this.newCustomSectionName.trim(),
      description: this.newCustomSectionDesc.trim(),
      icon: this.newCustomSectionIcon || 'fas fa-puzzle-piece',
      template: `custom_${this.newCustomSectionName.toLowerCase().replace(/\s+/g, '_')}`
    };

    this.customSections.push(newCustomSection);
    this.toastr.success(`Added custom section: ${newCustomSection.type}`);
    this.closeAddCustomModal();
  }

  deleteCustomSection(event: Event, section: any): void {
    event.stopPropagation();
    
    if (confirm(`Are you sure you want to delete the "${section.type}" custom section?`)) {
      const index = this.customSections.findIndex(s => s.type === section.type);
      if (index > -1) {
        this.customSections.splice(index, 1);
        this.toastr.success(`Deleted custom section: ${section.type}`);
      }
    }
  }

  // Additional Features
  showDeployedUrl(): void {
    if (this.deployedUrl) {
      window.open(this.deployedUrl, '_blank');
    } else {
      this.toastr.info('No deployed URL available yet. Please build the wireframe first.');
    }
  }

  // Override the existing selectNavbar method to use the new modal
  selectNavbar(pageName: string): void {
    this.selectedNavbarPage = pageName;
    this.showNavbarEditor();
  }

    isSectionEditable(page: string, section: string): boolean {
        return this.editingSection?.page === page && 
            this.editingSection?.section === section;
    }
    saveSectionChanges(pageName: string, sectionKey: string, html: string): void {
// Remove temporary style tags
    const cleanedHtml = html.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, '');

    // this.sectionHtmls[pageName][sectionKey] = 
    //     this.sanitizer.bypassSecurityTrustHtml(cleanedHtml);

      this.sectionHtmls[pageName][sectionKey] = cleanedHtml;

    this.updateFullPageHtml(pageName);
    this.toastr.success(`Updated section: ${sectionKey}`);
    }

    // Step 1: Get data from tree by ID
fetchTreeById(id: number) {
  this.showLoading('Loading website structure...');
  this.siteTreeService.getById(id).subscribe({
    next: async (res) => {
      console.log('📥 Fetched from getById:', res);
      
      if (res && res.model) {
        try {
          this.id = id;
          this.siteId = res.siteId || id; // Store siteId for API calls
          this.initialPrompt = res.prompt;
          
          const maybeParsed = typeof res.model === 'string' ? JSON.parse(res.model) : res.model;
          this.jsonInput = JSON.stringify(maybeParsed, null, 2);
          this.sitename = res.name;
          this.deployedUrl = res.deployedUrl;

          this.dividePagesToExistingOrNew(this.jsonInput, this.sitename);
          this.updateLoadingProgress(20, 'Model data loaded successfully');
          await this.generateMissingPagesWithAI(this.missingPages, this.jsonInput);

          // Start the enhanced processing flow
          // await this.processAllPagesWithExistingCheck(this.jsonInput);
        } catch (err) {
          console.error('❌ Error parsing model JSON:', err);
          this.toastr.error('Model data is not valid JSON format');
          this.hideLoading();
        }
      } else {
        console.warn('⚠️ Model key not found or empty');
        this.hideLoading();
      }
    },
    error: (err) => {
      console.error('❌ Error in getById:', err);
      this.toastr.error('Failed to load website data');
      this.hideLoading();
    }
  });
}

 /* Step 2: Process all pages with existing file checking
 */
async processAllPagesWithExistingCheck(treeJsonString: string) {
  try {
    const parsedTree = JSON.parse(treeJsonString);
    const allExpectedPages = Object.keys(parsedTree);
    
    this.updateLoadingProgress(10, `Checking ${allExpectedPages.length} existing pages...`);
    
    // Check for existing files
    const existingPagesData = await this.checkAllExistingPages(allExpectedPages);
    
    this.updateLoadingProgress(40, 'Processing page structure...');
    
    // Process the tree structure and generate prompts
    await this.generatePromptsForAllPages(parsedTree, existingPagesData);
    
    this.updateLoadingProgress(70, 'Generating missing pages...');
    
    // Generate HTML for missing pages
    await this.generateHtmlForMissingPages();
    
    this.updateLoadingProgress(90, 'Saving new pages...');
    
    // Save newly generated pages
    await this.saveNewlyGeneratedPages();
    
    this.updateLoadingProgress(100, 'Complete!');
    setTimeout(() => this.hideLoading(), 500);
    
  } catch (e) {
    console.error('❌ Invalid JSON format', e);
    this.toastr.error('Invalid JSON format');
    this.hideLoading();
  }
}

/**
 * Step 3: Check all existing pages
 */
private async checkAllExistingPages(expectedPages: string[]): Promise<Map<string, {css: string, bodyHtml: string, title: string}>> {
  const existingPagesData = new Map<string, {css: string, bodyHtml: string, title: string}>();
  
  const checkPromises = expectedPages.map(async (pageName) => {
    try {
      const response = await this.checkSinglePage(pageName);
      if (response) {
        const parsedData = this.parseHtmlResponse(response);
        if (parsedData) {
          existingPagesData.set(pageName, parsedData);
          console.log(`✅ Found existing page: ${pageName}`);
        }
      }
    } catch (error) {
      console.log(`❌ Page not found: ${pageName}`);
    }
  });
  
  await Promise.all(checkPromises);
  
  console.log(`📊 Found ${existingPagesData.size} existing pages out of ${expectedPages.length}`);
  return existingPagesData;
}


 /* Check single page existence
 */
private async checkSinglePage(pageName: string): Promise<string | null> {
  const sanitizedPageName = this.sanitizeFilename(pageName);
  
  console.log(sanitizedPageName)
  return new Promise((resolve) => {
    this.siteTreeService.readPages(this.sitename, sanitizedPageName).subscribe({
      next: (response) => {
        if (response && response.trim() !== '' && !response.includes('❌ File not found')) {
          resolve(response);
        } else {
          resolve(null);
        }
      },
      error: (err) => {
        console.log(`Page ${pageName} not found:`, err);
        resolve(null);
      }
    });
  });
}

/**
 * Step 4: Generate prompts for all pages and load existing ones
 */
private async generatePromptsForAllPages(treeJson: any, existingPagesData: Map<string, any>) {
  this.newlyGeneratedPages = []; // Reset the tracking array
  
  for (const [pageName, sections] of Object.entries(treeJson)) {
    if (!this.pageRenderOrder.includes(pageName)) {
      this.pageRenderOrder.push(pageName);
    }
    
    this.sectionOrderMap[pageName] = this.sectionOrderMap[pageName] || [];
    
    // Check if page exists
    if (existingPagesData.has(pageName)) {
      // Load existing page
      const pageData = existingPagesData.get(pageName);
      const completeHtml = this.createCompleteHtml(pageName, pageData.css, pageData.bodyHtml);
      
      this.pageSections[pageName] = {
        FullPage: this.sanitizer.bypassSecurityTrustHtml(completeHtml)
      };
      
      // Initialize section HTML storage for existing pages
      this.sectionHtmls[pageName] = {};
      this.allPagePrompts[pageName] = {};
      
      console.log(`✅ Loaded existing page: ${pageName}`);
    } else {
      // Generate prompts for missing page
      await this.generatePromptsForMissingPage(pageName, sections);
      this.newlyGeneratedPages.push(pageName);
      console.log(`📝 Will generate new page: ${pageName}`);
    }
  }
}



/**
 * Generate prompts for a single missing page
 */
private async generatePromptsForMissingPage(pageName: string, sections: any) {
  const sectionPrompts: Record<string, string> = {};
  
  // Process nested children first
  if (sections['Children']) {
    // Handle nested structure if needed
    await this.processPages(sections['Children'], false);
  }
  
  // Generate prompts for each section
  for (const [sectionName, sectionDescription] of Object.entries(sections)) {
    if (sectionName === 'Children') continue;
    
    this.sectionOrderMap[pageName].push(sectionName);
    const prompt = await this.generatePromptFromSection(sectionName, sectionDescription as string);
    sectionPrompts[sectionName] = prompt;
  }
  
  this.allPagePrompts[pageName] = sectionPrompts;
  this.initialGeneratedPrompts[pageName] = { ...sectionPrompts };
}


/* Step 5: Generate HTML for missing pages only
 */
private async generateHtmlForMissingPages() {
  if (this.newlyGeneratedPages.length === 0) {
    console.log('✅ No new pages to generate');
    return;
  }
  
  const htmlGenerationTasks: Promise<void>[] = [];
  
  for (const pageName of this.newlyGeneratedPages) {
    const sectionMap = this.allPagePrompts[pageName];
    if (sectionMap) {
      htmlGenerationTasks.push(this.processPageSections(pageName, sectionMap));
    }
  }
  
  await Promise.all(htmlGenerationTasks);
  console.log(`✅ Generated HTML for ${this.newlyGeneratedPages.length} new pages`);
}


/**
 * Step 6: Save only newly generated pages
 */
private async saveNewlyGeneratedPages(): Promise<void> {
  if (this.newlyGeneratedPages.length === 0) {
    console.log('✅ No new pages to save');
    return;
  }

  const fileMap: Record<string, string> = {};

  // Prepare only newly generated pages for saving
  for (const pageName of this.newlyGeneratedPages) {
    const pageSection = this.pageSections[pageName];
    if (pageSection && pageSection.FullPage) {
      let html = pageSection.FullPage.toString();
      
      // Clean up any SafeValue content if present
      if (html.includes('SafeValue must use [property]=binding:')) {
        const parsed = this.parseHtmlResponse(html);
        if (parsed) {
          html = this.createCompleteHtml(pageName, parsed.css, parsed.bodyHtml);
        }
      }
      
      const sanitizedPageName = this.sanitizeFilename(pageName);
      fileMap[sanitizedPageName] = html;
      
      console.log(`📝 Prepared ${pageName} for saving`);
    }
  }

  if (Object.keys(fileMap).length > 0) {
    try {
      await new Promise((resolve, reject) => {
        this.siteTreeService.createHtmlfile(this.siteId, this.sitename, fileMap).subscribe({
          next: (res) => {
            console.log(`✅ Saved ${Object.keys(fileMap).length} new HTML files`);
            this.toastr.success(`Saved ${Object.keys(fileMap).length} new HTML files`);
            
            // Clear the newly generated pages list after successful save
            this.newlyGeneratedPages = [];
            resolve(res);
          },
          error: (err) => {
            console.error('❌ Error saving HTML files:', err);
            this.toastr.error('Failed to save HTML files');
            reject(err);
          }
        });
      });
    } catch (error) {
      console.error('❌ Save operation failed:', error);
    }
  }
}

/**
 * Enhanced HTML response parser
 */
private parseHtmlResponse(rawResponse: string): { css: string, bodyHtml: string, title: string } | null {
  try {
    console.log('🔍 Processing existing page HTML...');
    
    if (!rawResponse || rawResponse.trim() === '') {
      console.warn('⚠️ Empty response received');
      return null;
    }

    let htmlContent = rawResponse.trim();
    
    // Handle SafeValue wrapper if present
    if (htmlContent.includes('SafeValue must use [property]=binding:')) {
      console.log('🔧 Extracting from SafeValue wrapper...');
      
      // Extract HTML content from SafeValue
      const htmlMatches = htmlContent.match(/<html[\s\S]*?<\/html>/i) || 
                         htmlContent.match(/<body[\s\S]*?<\/body>/i);
      
      if (htmlMatches && htmlMatches[0]) {
        htmlContent = htmlMatches[0];
        console.log('✅ Extracted HTML content');
      }
    }

    // Clean up any wrapper text but keep the HTML intact
    const htmlStartIndex = htmlContent.indexOf('<');
    if (htmlStartIndex > 0) {
      htmlContent = htmlContent.substring(htmlStartIndex);
    }

    // Now parse the HTML to extract components
    return this.extractHtmlComponents(htmlContent);

  } catch (error) {
    console.error('❌ Error processing HTML:', error);
    return null;
  }
}

private extractHtmlComponents(htmlContent: string): { css: string, bodyHtml: string, title: string } | null {
  try {
    // Use DOMParser to parse the HTML
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlContent, 'text/html');
    
    // Check if parsing was successful
    if (doc.querySelector('parsererror')) {
      console.warn('⚠️ HTML parsing failed, trying alternative method');
      return this.extractHtmlComponentsManually(htmlContent);
    }

    // Extract CSS from style tags
    const styles = doc.querySelectorAll('style');
    let css = '';
    styles.forEach(style => {
      css += (style.textContent || '') + '\n';
    });

    // Extract title
    const titleElement = doc.querySelector('title');
    const title = titleElement ? titleElement.textContent || 'Untitled Page' : 'Untitled Page';

    // Extract body content
    const body = doc.querySelector('body');
    let bodyHtml = '';
    
    if (body) {
      bodyHtml = body.innerHTML;
    } else {
      // If no body tag, use everything after head or the whole content
      const head = doc.querySelector('head');
      if (head) {
        // Remove head content and get the rest
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = htmlContent;
        const headElement = tempDiv.querySelector('head');
        if (headElement) {
          headElement.remove();
        }
        bodyHtml = tempDiv.innerHTML.replace(/<\/?html[^>]*>/gi, '').replace(/<\/?body[^>]*>/gi, '').trim();
      } else {
        bodyHtml = htmlContent.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '').replace(/<title[^>]*>[\s\S]*?<\/title>/gi, '').trim();
      }
    }

    console.log(`✅ Extracted components - CSS: ${css.length} chars, Body: ${bodyHtml.length} chars, Title: ${title}`);
    
    return {
      css: css.trim(),
      bodyHtml: bodyHtml.trim(),
      title: title.trim()
    };

  } catch (error) {
    console.error('❌ Error extracting HTML components:', error);
    return this.extractHtmlComponentsManually(htmlContent);
  }
}
/**
 * Manual extraction as fallback method
 */
private extractHtmlComponentsManually(htmlContent: string): { css: string, bodyHtml: string, title: string } | null {
  try {
    console.log('🔧 Using manual extraction method...');

    // Extract CSS from style tags
    const cssMatches = htmlContent.match(/<style[^>]*>([\s\S]*?)<\/style>/gi);
    let css = '';
    if (cssMatches) {
      cssMatches.forEach(match => {
        const cssContent = match.replace(/<\/?style[^>]*>/gi, '');
        css += cssContent + '\n';
      });
    }

    // Extract title
    const titleMatch = htmlContent.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
    const title = titleMatch ? titleMatch[1].trim() : 'Untitled Page';

    // Extract body content
    let bodyHtml = '';
    const bodyMatch = htmlContent.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
    
    if (bodyMatch) {
      bodyHtml = bodyMatch[1];
    } else {
      // If no body tags, clean up and use the content
      bodyHtml = htmlContent
        .replace(/<!DOCTYPE[^>]*>/gi, '')
        .replace(/<\/?html[^>]*>/gi, '')
        .replace(/<head[^>]*>[\s\S]*?<\/head>/gi, '')
        .replace(/<\/?body[^>]*>/gi, '')
        .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
        .replace(/<title[^>]*>[\s\S]*?<\/title>/gi, '')
        .trim();
    }

    if (!bodyHtml) {
      console.warn('⚠️ No body content found');
      return null;
    }

    console.log(`✅ Manual extraction complete - CSS: ${css.length} chars, Body: ${bodyHtml.length} chars`);
    
    return {
      css: css.trim(),
      bodyHtml: bodyHtml.trim(),
      title: title
    };

  } catch (error) {
    console.error('❌ Manual extraction failed:', error);
    return null;
  }
}


// Helper method for fragment extraction
private extractFromFragment(fragment: HTMLElement, originalHtml: string): { css: string, bodyHtml: string, title: string } {
  const styles = fragment.querySelectorAll('style');
  let css = '';
  styles.forEach(style => {
    css += (style.textContent || '') + '\n';
  });

  return {
    css: css.trim(),
    bodyHtml: fragment.innerHTML || originalHtml,
    title: 'Parsed Fragment'
  };
}

// Emergency parsing method
private emergencyParse(rawContent: string): { css: string, bodyHtml: string, title: string } | null {
  // Try to extract any content that looks like HTML
  const cssMatch = rawContent.match(/<style[^>]*>([\s\S]*?)<\/style>/gi);
  const css = cssMatch ? cssMatch.join('\n') : '';
  
  const titleMatch = rawContent.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
  const title = titleMatch ? titleMatch[1] : 'Emergency Parse';
  
  // Remove style and title tags, use rest as body
  let bodyHtml = rawContent
    .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
    .replace(/<title[^>]*>[\s\S]*?<\/title>/gi, '')
    .replace(/<!DOCTYPE[^>]*>/gi, '')
    .replace(/<html[^>]*>/gi, '')
    .replace(/<\/html>/gi, '')
    .replace(/<head[^>]*>[\s\S]*?<\/head>/gi, '')
    .replace(/<body[^>]*>/gi, '')
    .replace(/<\/body>/gi, '')
    .trim();

  if (!bodyHtml) {
    return null;
  }

  return { css: css.trim(), bodyHtml, title: title.trim() };
}


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

    isCurrentSectionEditing(sectionKey: string): boolean {
  const currentPage = this.getCurrentPageName();
  return this.editingSection?.page === currentPage && 
         this.editingSection?.section === sectionKey;
}
    // Step 3

    // 🔄 Maintain strict page and section render order
    missingHtmlPages: string[] = [];
/**
 * Enhanced page processing with proper loading management
 */
async processPages(treeJson: any, forceRegenerate = false) {
  console.log('🚀 Starting enhanced page processing...');
  this.showLoading('Analyzing existing pages...');
  
  this.missingHtmlPages = [];
  const allExpectedPages = Object.keys(treeJson);
  this.updateLoadingProgress(10, `Checking ${allExpectedPages.length} pages...`);
  
  // Enhanced existing file checking
  if (!forceRegenerate) {
    const { existingFiles, extractedContent } = await this.checkAllExistingFilesEnhanced(this.sitename, allExpectedPages);
    
    if (Object.keys(existingFiles).length > 0) {
      console.log(`🎉 Found ${Object.keys(existingFiles).length} existing files. Loading them...`);
      this.updateLoadingProgress(30, 'Loading existing pages...');
      
      // Load existing files
      for (const [pageName, html] of Object.entries(existingFiles)) {
        if (!this.pageRenderOrder.includes(pageName)) {
          this.pageRenderOrder.push(pageName);
        }
        
        this.pageSections[pageName] = {
          FullPage: this.sanitizer.bypassSecurityTrustHtml(html)
        };
        
        // Initialize section order map
        this.sectionOrderMap[pageName] = this.sectionOrderMap[pageName] || [];
        
        // Store extracted content for potential editing
        if (extractedContent[pageName]) {
          // You can store this for future section editing if needed
          // this.extractedPageContent[pageName] = extractedContent[pageName];
        }
      }
      
      this.updateLoadingProgress(50, 'Identifying missing pages...');
      
      // Identify missing pages
      const missingPages = allExpectedPages.filter(page => !existingFiles[page]);
      
      if (missingPages.length === 0) {
        console.log('✅ All pages found! No generation needed.');
        this.updateLoadingProgress(100, 'All pages loaded successfully!');
        setTimeout(() => this.hideLoading(), 500);
        return;
      } else {
        console.log(`📝 Processing ${missingPages.length} missing pages:`, missingPages);
        this.updateLoadingProgress(60, `Generating ${missingPages.length} missing pages...`);
        await this.processMissingPagesEnhanced(treeJson, missingPages);
        return;
      }
    }
  }
  
  // If no existing files found or forceRegenerate is true
  console.log('📝 No existing files found. Processing all pages...');
  this.updateLoadingProgress(20, 'Generating all pages...');
  await this.processAllPagesEnhanced(treeJson);
}

/**
 * Enhanced processing for missing pages only
 */
private async processMissingPagesEnhanced(treeJson: any, missingPages: string[]) {
  const totalPages = missingPages.length;
  let processedPages = 0;
  
  for (const pageName of missingPages) {
    if (!treeJson[pageName]) continue;
    
    this.updateLoadingProgress(
      60 + (processedPages / totalPages) * 30, 
      `Generating page: ${pageName}...`
    );
    
    const sections = treeJson[pageName];
    
    if (!this.pageRenderOrder.includes(pageName)) {
      this.pageRenderOrder.push(pageName);
    }
    
    this.sectionOrderMap[pageName] = this.sectionOrderMap[pageName] || [];
    this.missingHtmlPages.push(pageName);
    
    const sectionPrompts: Record<string, string> = {};
    
    // Process nested children first
    if (sections['Children']) {
      await this.processPages(sections['Children'], false);
    }
    
    // Generate prompts for missing sections
    for (const [sectionName, sectionDescription] of Object.entries(sections)) {
      if (sectionName === 'Children') continue;
      
      this.sectionOrderMap[pageName].push(sectionName);
      const prompt = await this.generatePromptFromSection(sectionName, sectionDescription as string);
      sectionPrompts[sectionName] = prompt;
    }
    
    this.allPagePrompts[pageName] = sectionPrompts;
    this.initialGeneratedPrompts[pageName] = { ...sectionPrompts };
    
    processedPages++;
  }
  
  if (this.missingHtmlPages.length > 0) {
    this.updateLoadingProgress(90, 'Finalizing generated pages...');
    await this.processAllPagesLiveUpdateEnhanced();
  } else {
    this.updateLoadingProgress(100, 'Processing complete!');
    setTimeout(() => this.hideLoading(), 500);
  }
}

/**
 * Enhanced processing for all pages
 */
private async processAllPagesEnhanced(treeJson: any) {
  const allPages = Object.keys(treeJson);
  const totalPages = allPages.length;
  let processedPages = 0;
  
  for (const [pageName, sections] of Object.entries(treeJson)) {
    this.updateLoadingProgress(
      20 + (processedPages / totalPages) * 50, 
      `Processing page: ${pageName}...`
    );
    
    if (!this.pageRenderOrder.includes(pageName)) {
      this.pageRenderOrder.push(pageName);
    }
    
    this.sectionOrderMap[pageName] = this.sectionOrderMap[pageName] || [];
    this.missingHtmlPages.push(pageName);
    
    const sectionPrompts: Record<string, string> = {};
    
    // Process nested children first
    if (sections['Children']) {
      await this.processPages(sections['Children'], false);
    }
    
    // Generate prompts for all sections
    for (const [sectionName, sectionDescription] of Object.entries(sections)) {
      if (sectionName === 'Children') continue;
      
      this.sectionOrderMap[pageName].push(sectionName);
      const prompt = await this.generatePromptFromSection(sectionName, sectionDescription);
      sectionPrompts[sectionName] = prompt;
    }
    
    this.allPagePrompts[pageName] = sectionPrompts;
    this.initialGeneratedPrompts[pageName] = { ...sectionPrompts };
    
    processedPages++;
  }
  
  if (this.missingHtmlPages.length > 0) {
    this.updateLoadingProgress(70, 'Generating HTML content...');
    await this.processAllPagesLiveUpdateEnhanced();
  } else {
    this.updateLoadingProgress(100, 'Processing complete!');
    setTimeout(() => this.hideLoading(), 500);
  }
}

/**
 * Enhanced live update processing with proper file saving
 */
async processAllPagesLiveUpdateEnhanced() {
  const htmlGenerationTasks: Promise<void>[] = [];
  const totalTasks = this.pageRenderOrder.length;
  let completedTasks = 0;

  // Process pages in order
  for (const pageName of this.pageRenderOrder) {
    const sectionMap = this.allPagePrompts[pageName];
    if (!sectionMap) {
      console.warn(`⚠️ No section map found for page: ${pageName}`);
      continue;
    }
    
    const task = this.processPageSectionsEnhanced(pageName, sectionMap).then(() => {
      completedTasks++;
      this.updateLoadingProgress(
        70 + (completedTasks / totalTasks) * 20, 
        `Generated ${completedTasks}/${totalTasks} pages...`
      );
    });
    
    htmlGenerationTasks.push(task);
  }

  await Promise.all(htmlGenerationTasks);

  // Save only newly generated pages
  this.updateLoadingProgress(95, 'Saving generated pages...');
  await this.saveNewlyGeneratedPages();
  
  this.updateLoadingProgress(100, 'All pages loaded successfully!');
  setTimeout(() => this.hideLoading(), 500);
}

/**
 * Enhanced page section processing with proper HTML wrapping
 */
async processPageSectionsEnhanced(pageName: string, sectionMap: Record<string, string>) {
  if (!sectionMap || typeof sectionMap !== 'object') {
    console.warn(`⚠️ Skipping ${pageName} because sectionMap is invalid:`, sectionMap);
    return;
  }

  const sectionHtmls: string[] = [];
  this.sectionHtmls[pageName] = {};

  const htmlTasks = Object.entries(sectionMap).map(async ([sectionName, jsonPrompt]) => {
    const html = await this.generateJson({ sectionType: sectionName, jsonStructure: jsonPrompt });
    sectionHtmls.push(html);
    
    // Store individual section HTML
    this.sectionHtmls[pageName][sectionName] = html;
  });

  await Promise.all(htmlTasks);

  // Create complete HTML structure for the page
  const completeHtml = this.createCompleteHtml(pageName, COMMON_CSS, sectionHtmls.join('\n'));
  
  const safeHtml = this.sanitizer.bypassSecurityTrustHtml(completeHtml);
  this.pageSections[pageName] = { FullPage: safeHtml };
}








    
    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>)`;

    // Generate prompt from section
   async generatePromptFromSection(
        sectionName: string,
        sectionDescription: string,
        headerId: number = 35,
        operationType: string = 'template 1'
    ): Promise<string> {
        return new Promise((resolve) => {
            const fieldType = sectionName.toLowerCase().replace(/section$/i, '').trim();

            // this.siteTreeService.getDlf(headerId, operationType, fieldType).subscribe({
               this.siteTreeService.getDesignLibrary( operationType, fieldType).subscribe({

                next: async (res) => {
                    try {
                        // const jsonBlock = res?.javacode;
                        const jsonBlock = res?.htmljson;

                        if (!jsonBlock) return resolve('{}');

                        console.log(' base json is ...',jsonBlock);
                        const baseJson = typeof jsonBlock === 'string' ? JSON.parse(jsonBlock) : jsonBlock;
                        const baseJsonString = JSON.stringify(baseJson, null, 2);


                        const enhancedPrompt = `
                        ${baseJsonString}

                        You are building a website with the following context:
                        ${this.initialPrompt}

                        Your task is to write rich, engaging content for the "${sectionName}" section, which is represented by the above JSON structure.

                        🛠️ Instructions:
                        - Replace only the \`"text"\` fields in the JSON with relevant, marketing-oriented content based on the website's purpose.
                        - Maintain the exact same structure and element types.
                        - Content should be clear, modern, and compelling — suitable for a real-world product.

                        🚫 Do NOT include:
                        - Any explanation, commentary, or markdown
                        - Any prefix like "Here is the updated JSON"
                        - Any additional fields or elements not present in the original JSON
                       - Do NOT wrap the output in code blocks (like \`\`\`json or \`\`\`) or use any markdown formatting.

                        ✅ Output Requirement:
                        Return raw JSON only — nothing else.
                        `;

                        const hash = sha256(enhancedPrompt).toString();

                        if (this.promptHashCache[hash]) {
                            return resolve(this.promptHashCache[hash]);
                        }

                        const enhanced = await this.callAi(enhancedPrompt);

                        console.log('enhanced prmpt ',enhanced);
                        this.promptHashCache[hash] = enhanced;

                        // resolve(baseJsonString);
                        resolve(this.promptHashCache[hash]);
                    } catch (err) {
                        console.error('❌ JSON parse error:', err);
                        resolve('{}');
                    }
                },
                error: () => resolve('{}')
            });
        });
    }
    // Process all pages live update
    async processAllPagesLiveUpdate() {
        const htmlGenerationTasks: Promise<void>[] = [];

        // for (const [pageName, sectionMap] of Object.entries(this.allPagePrompts)) {
        //     htmlGenerationTasks.push(this.processPageSections(pageName, sectionMap));
        // }
        for (const pageName of this.pageRenderOrder) {
            console.log(' process page is : ', pageName);
            const sectionMap = this.allPagePrompts[pageName];
            if (!sectionMap) {
                console.warn(`⚠️ No section map found for page: ${pageName}`);
                continue;
            }
            htmlGenerationTasks.push(this.processPageSections(pageName, sectionMap));
        }

        await Promise.all(htmlGenerationTasks);

        // ✅ Now save the newly generated pages only
       const fileMap: Record<string, string> = {};
        const formattedSiteName = this.formatSiteName(this.sitename);

        for (const pageName of this.missingHtmlPages) {
        const html = this.pageSections[pageName]?.FullPage?.toString() || '';
        if (html) {
            const sanitizedPageName = this.sanitizeFilename(pageName);
            fileMap[sanitizedPageName] = html;
        }
        }

        if (Object.keys(fileMap).length > 0) {
        this.siteTreeService.createHtmlfile(this.siteId, formattedSiteName, fileMap).subscribe({
            next: (res) => {
                this.toastr.success(`Saved ${Object.keys(fileMap).length} new HTML files`);
                              
                this.hideLoading();
            },
            error: (err) => {
                this.toastr.error('Failed to save HTML files');
                console.error('❌ Error saving html:', err);
              
                this.hideLoading();
            }
            
            });
        }
      
     
    }
    nextPage(): void {
  if (this.currentPageIndex < this.pageRenderOrder.length - 1) {
    this.currentPageIndex++;
    this.resetZoom();
  }
}

previousPage(): void {
  if (this.currentPageIndex > 0) {
    this.currentPageIndex--;
    this.resetZoom();
  }
}


    // Process page sections
    async processPageSections(pageName: string, sectionMap: Record<string, string>) {
       
        if (!sectionMap || typeof sectionMap !== 'object') {
            console.warn(`⚠️ Skipping ${pageName} because sectionMap is invalid:`, sectionMap);
            return;
        }
        const sectionHtmls: string[] = [];
        this.sectionHtmls[pageName] = {};
    
        const htmlTasks = Object.entries(sectionMap).map(async ([sectionName, jsonPrompt]) => {
            const html = await this.generateJson({ sectionType: sectionName, jsonStructure: jsonPrompt });
            sectionHtmls.push(html);
            
            // Store individual section HTML
            // this.sectionHtmls[pageName][sectionName] = this.sanitizer.bypassSecurityTrustHtml(html);
            this.sectionHtmls[pageName][sectionName] = html
            console.log("Processing Html in process page "+sectionHtmls)
        });
    
        await Promise.all(htmlTasks);
    
        // Make sure the CSS is injected properly with !important flags
        const finalHtml = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>${pageName}</title>
            <style>
                ${COMMON_CSS}
                
                html, body {
                    margin: 0 !important;
                    padding: 0 !important;
                    min-height: 100% !important;
                    width: 100% !important;
                    font-family: 'Segoe UI', sans-serif !important;
                }
            
            </style>
        </head>
        <body>
        
                ${sectionHtmls.join('\n')}
            
        </body>
        </html>`;
        
        const safeHtml = this.sanitizer.bypassSecurityTrustHtml(finalHtml);
        this.pageSections[pageName] = { FullPage: safeHtml };
    }

    // Add these methods to your WireframeRendererComponent class



/**
 * Create complete HTML structure with CSS and body content
 */
private createCompleteHtml(pageName: string, css: string, bodyHtml: string): string {
  return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${pageName}</title>
    <style>
${css}

/* Additional common styles */
${COMMON_CSS}

html, body {
    margin: 0 !important;
    padding: 0 !important;
    min-height: 100% !important;
    width: 100% !important;
    font-family: 'Segoe UI', sans-serif !important;
}
    </style>
</head>
<body>
${bodyHtml}
</body>
</html>`;
}

private async loadExistingPageForRendering(pageName: string, rawHtml: string): Promise<void> {
  try {
    console.log(`🔄 Loading existing page for rendering: ${pageName}`);
    
    // Parse the existing HTML
    const parsed = this.parseHtmlResponse(rawHtml);
    
    if (parsed) {
      // Create properly structured HTML for rendering
      const completeHtml = this.createCompleteHtml(pageName, parsed.css, parsed.bodyHtml);
      
      // Store for rendering with proper sanitization
      this.pageSections[pageName] = {
        FullPage: this.sanitizer.bypassSecurityTrustHtml(completeHtml)
      };
      
      // Initialize section storage
      this.sectionHtmls[pageName] = {};
      this.allPagePrompts[pageName] = {};
      
      // Add to render order if not present
      if (!this.pageRenderOrder.includes(pageName)) {
        this.pageRenderOrder.push(pageName);
      }
      
      // Initialize section order map
      this.sectionOrderMap[pageName] = this.sectionOrderMap[pageName] || [];
      
      console.log(`✅ Successfully loaded existing page: ${pageName}`);
    } else {
      console.error(`❌ Failed to parse existing page: ${pageName}`);
    }
  } catch (error) {
    console.error(`❌ Error loading existing page ${pageName}:`, error);
  }
}
/**
 * Updated createHtmlFiles method with proper error handling
 */



createHtmlFiles() {
  const pageHtmlMap: Record<string, string> = {};
  
  for (const [pageName, section] of Object.entries(this.pageSections)) {
    let html = section.FullPage?.toString() || '';
    
    // Clean SafeValue if present and parse properly
    if (html.includes('SafeValue must use [property]=binding:')) {
      const parsed = this.parseHtmlResponse(html);
      if (parsed) {
        html = this.createCompleteHtml(pageName, parsed.css, parsed.bodyHtml);
      }
    }
    
    // Ensure we have valid HTML
    if (!html.includes('<!DOCTYPE') && !html.includes('<html')) {
      // If it's just body content, wrap it properly
      html = this.createCompleteHtml(pageName, COMMON_CSS, html);
    }
    
    const sanitizedPageName = this.sanitizeFilename(pageName);
    pageHtmlMap[sanitizedPageName] = html;
  }

  console.log('📁 Saving all pages:', Object.keys(pageHtmlMap));
  
  this.siteTreeService.createHtmlfile(this.siteId, this.sitename, pageHtmlMap).subscribe({
    next: (data) => {
      console.log('✅ All files saved:', data);
      this.toastr.success(`Saved ${Object.keys(pageHtmlMap).length} HTML files`);
    },
    error: (error) => {
      console.error('❌ Error saving files:', error);
      if (error.status >= 200 && error.status <= 299) {
        this.toastr.success("Files created successfully");
      } else {
        this.toastr.error("Failed to create files");
      }
    }
  });
}
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;

            // Check for empty or invalid parsed JSON
            const isEmpty = !parsedJson || Object.keys(parsedJson).length === 0;

            if (isEmpty) {
                // 🧠 Use AI to generate HTML based on sectionType
                // ⬇️ Use sectionType + this.initialPrompt to create a better prompt
                const aiPrompt = `
                Generate a clean, responsive HTML layout for the "${data.sectionType}" section of a modern website.
                Use the following context as guidance for structure and styling:
                "${this.initialPrompt}"
                Ensure the section includes relevant semantic HTML, good visual hierarchy, and wireframe-friendly placeholder content.
                Please return ONLY the HTML code, without wrapping it in triple backticks (\`\`\`) or specifying "html" or any language tag. Just pure HTML content — no explanation or comments..
                `.trim();

                 console.log('✅ json is empty now call ai to generate html :', aiPrompt);

                
                this.callAi(aiPrompt).then((aiHtml) => {
                    console.log('✅ AI HTML generated via prompt:', aiHtml);
                    resolve(aiHtml);
                }).catch((err) => {
                    console.error('❌ AI generation failed:', err);
                    resolve('⚠️ AI generation failed.');
                });
            } else {
                // Normal flow — parsed JSON exists, call HTML API
                const payload = {
                    sectionType: data.sectionType,
                    jsonStructure: parsedJson
                };

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

                this.siteTreeService.generateHtml(parsedJson).subscribe({
                    next: (res) => {
                        console.log('✅ Response from HTML API:', res);
                        if (res && res.msg) {
                            console.log("CHECKING DEPLOYED URL ", res.deployedUrl);
                            this.deployedUrl = res.deployedUrl;
                            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 HTML to clipboard
    copyToClipboard(pageName: string) {
        const fullHtml = this.pageSections[pageName].FullPage.toString();
        navigator.clipboard.writeText(fullHtml).then(() => {
        this.toastr.success(`HTML copied for page: ${pageName}`);
        });
    }

// downloadHtml(pageName: string) {
//   // Make sure we're using the sections in the correct order
//   console.log(pageName, ' downloading ..')
//   const orderedSectionKeys = this.sectionOrderMap[pageName] || this.getSectionKeys(pageName);
  
//   // Update the sectionHtmls order to match orderedSectionKeys
//   const reorderedSectionHtmls: Record<string, SafeHtml> = {};
//   for (const sectionKey of orderedSectionKeys) {
//     if (this.sectionHtmls[pageName][sectionKey]) {
//       reorderedSectionHtmls[sectionKey] = this.sectionHtmls[pageName][sectionKey];
//     }
//   }
//   console.log('📦 Original sectionHtmls:', this.sectionHtmls[pageName]);
//   console.log('📦 Section order:', orderedSectionKeys);
//   console.log('📦 FullPage HTML:', this.pageSections[pageName]?.FullPage);

//   this.sectionHtmls[pageName] = reorderedSectionHtmls;
  
//   console.log('page data ',reorderedSectionHtmls)
//   // Now update the full page HTML with correct order
//   // this.updateFullPageHtml(pageName);
  
//   // const fullHtml = this.pageSections[pageName].FullPage.toString();
//   const fullHtml = this.pageSections[pageName].FullPage; // must be plain string

//  if (!fullHtml || typeof fullHtml !== 'string' || fullHtml.trim() === '') {
//   alert(`⚠️ No content available for page "${pageName}". Please generate HTML first.`);
//   console.error('❌ FullPage content missing or empty for:', pageName);
//   return;
// }
//   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);
// }
    // Upload HTML files
   
   


   downloadHtml(pageName: string) {
  console.log(pageName, ' downloading ..');

  const fullHtml = this.pageSections[pageName]?.FullPage;

  if (!fullHtml || typeof fullHtml !== 'string' || fullHtml.trim() === '') {
    alert(`⚠️ No content available for page "${pageName}". Please generate HTML first.`);
    console.error('❌ FullPage content missing or empty for:', pageName);
    return;
  }

  console.log('📦 FullPage HTML:', fullHtml);

  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);
}

    buildWireframe(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.deployProj(projId,pageHtmlMap).subscribe(
            (data) => {
                console.log(data);
                if (data || data.status >= 200 && data.status <= 299) {
                    this.toastr.success("Deploying Start..");
                }
                // setTimeout(() => {
                //     this.ngOnInit();
                // }, 500);
            }, (error) => {
                console.log(error);
                if (error.status >= 200 && error.status <= 299) {
                    this.toastr.success("Files Created Successfully");
                }
                if (error.status >= 400 && error.status <= 499) {
                    this.toastr.error("Files Not Created");
                }
                if (error.status >= 500 && error.status <= 599) {
                    this.toastr.error("Server Error");
                }
            });
    }

    


// Update your helper methods
private formatSiteName(name: string): string {
  return name
    .replace(/([a-z])([A-Z])/g, '$1_$2') // Convert camelCase to snake_case
    .replace(/\s+/g, '_') // Replace spaces with underscores
    .toLowerCase();
}

private sanitizeFilename(filename: string): string {
  return filename
    .replace(/\s+/g, '_') // Replace spaces with underscores
    .replace(/[^a-zA-Z0-9_]/g, '') // Remove special chars except underscores
    .toLowerCase();
}


private async tryReadHtmlFromServer(siteName: string, pageName: string): Promise<string | null> {
  const formattedSite = this.formatSiteName(siteName);
  const sanitizedPage = this.sanitizeFilename(pageName);

  return new Promise((resolve) => {
    this.siteTreeService.readPages(formattedSite, sanitizedPage).subscribe({
      next: (res) => {
        if (res === '' || res == null || res.includes('❌ File not found')) {
          resolve(null);
        } else {
          resolve(res);
        }
      },
      error: (err) => {
        if (err.status === 404) {
          resolve(null);
        } else {
          console.error('Error in readPages:', err);
          resolve(null);
        }
      }
    });
  });
}


async recreateWireframe() {
    this.toastr.info('⏳ Recreating all wireframes...');

    // Clear existing HTML and prompts
    this.pageSections = {};
    this.sectionHtmls = {};
    this.missingHtmlPages = [];

    // Reprocess everything
    await this.processPages(JSON.parse(this.jsonInput)); // regenerate prompts

    this.toastr.success('✅ Recreated all wireframes and saved HTML files.');
}




    // Regenerate specific wireframe
    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) {
        this.toastr.info('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 });
        
        // Add CSS to the HTML
        const htmlWithCss = this.applyCssToSectionHtml(html, pageName, section);
        htmlBlocks.push(htmlWithCss);
        
        // Update individual section HTML
        this.sectionHtmls[pageName][section] = this.sanitizer.bypassSecurityTrustHtml(htmlWithCss);
    
        console.log(`♻️ Regenerated section: ${pageName} > ${section}`);
        }
    
        // Create the final HTML with CSS properly included
        const finalHtml = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>${pageName}</title>
        <style>
            ${COMMON_CSS}
        </style>
        </head>
        <body>
        ${htmlBlocks.join('\n')}
        </body>
        </html>`;
        
        const safeHtml = this.sanitizer.bypassSecurityTrustHtml(finalHtml);
        this.pageSections[pageName] = { FullPage: safeHtml };
        
        // Ensure CSS is applied to DOM elements
        setTimeout(() => {
        this.verifyCssInSections();
        }, 100);
        
        this.toastr.success(`Regenerated ${updatedSections.length} sections for ${pageName}`);
    }
    

    // Regenerate all modified sections
    async regenerateAllModifiedSections() {
        let totalModified = 0;
        
        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;
            }

            totalModified += updatedSections.length;
            const htmlBlocks: string[] = [];

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

            const finalHtml = `<style>${COMMON_CSS}</style>\n${htmlBlocks.join('\n')}`;
            const safeHtml = this.sanitizer.bypassSecurityTrustHtml(finalHtml);
            this.pageSections[pageName] = { FullPage: safeHtml };
        }

        if (totalModified > 0) {
            this.toastr.success(`Regenerated ${totalModified} sections across all pages`);
        } else {
            this.toastr.info('No modified sections found');
        }
    }

    // Call ai
    async callAi(data, attempt = 1): Promise<string> {
    return new Promise((resolve) => {
        console.log(`📡 Call LLM - Attempt ${attempt}`);

        const payload = {
            query: data,
            conversationId: '677'
        };

        this.siteTreeService.callGemini(payload).subscribe({
            next: (res) => {
                console.log('✅ LLM Response:', res);
                if (res && res.responseContent) {
                    resolve(res.responseContent);
                } else {
                    resolve('⚠️ No response received.');
                }
            },
            error: async (err) => {
                console.error(`❌ LLaMA API Error (Attempt ${attempt}):`, err);

                // Check if it's a 429 (Too Many Requests)
                if ( attempt < 3) {
                    console.log(`⏳ Waiting 10s before retrying...`);
                    await new Promise(r => setTimeout(r, 10000));
                    const retryResult = await this.callAi(data, attempt + 1);
                    resolve(retryResult);
                } else {
                    resolve('❌ LLM API failed after retries.');
                }
            }
        });
    });
}

    // Style properties
    activeEditTarget: string | null = null;
    // liveStyles = {
    //     background: '',
    //     color: '',
    //     fontSize: '',
    //     padding: '',
    //     margin: '',
    //     fontWeight: '',
    //     textAlign: '',
    // };

    // Select editable element
    selectEditable(pageName: string) {
        this.activeEditTarget = pageName;
    }

    // Apply live styles
    applyLiveStyles() {
        const target = document.querySelector(`[data-target='${this.activeEditTarget}']`) as HTMLElement;
        if (target) {
            Object.keys(this.liveStyles).forEach((prop) => {
                if (this.liveStyles[prop]) {
                    target.style[prop] = this.liveStyles[prop];
                }
            });
        }
        this.toastr.success(`Style updated for: ${this.activeEditTarget}`);
    }

    // Track raw edits
    rawEdits: Record<string, string> = {};

    // Style map
    selectedElementSelector = '';
    styleMap: Record<string, any> = {
        'hero-header': { 'background': '#fdfdfd', 'text-align': 'center' },
        'btn-filled': { 'background': '#000', 'color': '#fff' },
        'hero-heading': { 'font-size': '36px', 'font-weight': 'bold' },
    };

    // Get all CSS selectors
    getAllCssSelectors(): string[] {
        return Object.keys(this.styleMap);
    }

    // Apply CSS from map
    applyCssFromMap() {
        this.updateLiveStyles();
    }

    applyCssToSectionHtml(html: string, pageName: string, sectionKey: string): string {
        // First check if HTML already contains CSS
        if (html.includes('<style') && html.includes('data-section-css="true"')) {
        return html; // CSS already exists
        }
        
        // Add CSS to HTML
        const cssBlock = `<style data-section-css="true">
        ${COMMON_CSS}
        /* Section-specific styles */
        .section-${pageName}-${sectionKey} * {
            box-sizing: border-box;
        }
        </style>`;
        
        // Insert CSS at the beginning of the HTML content
        return cssBlock + html;
    }

    ensureCommonCssForAllSections(): void {
        // Remove any existing CSS injection
        const existingStyles = document.querySelectorAll('style[data-common-css]');
        existingStyles.forEach(style => style.remove());
        
        // Create a new style element with the COMMON_CSS
        const styleEl = document.createElement('style');
        styleEl.setAttribute('data-common-css', 'true');
        styleEl.textContent = COMMON_CSS;
        document.head.appendChild(styleEl);
        
        // Add inline styles to make sure section previews display properly
        const additionalStyle = document.createElement('style');
        additionalStyle.setAttribute('data-section-preview-styles', 'true');
        additionalStyle.textContent = `
        .section-preview {
            position: relative;
            width: 100%;
            background: #fff;
            padding: 8px;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            overflow: hidden;
            min-height: 50px;
        }
        .section-preview-wrapper {
            width: 100%;
            position: relative;
        }
        .section-preview[contenteditable="true"] {
            outline: 2px solid #007bff;
            min-height: 100px;
        }
        `;
        document.head.appendChild(additionalStyle);
        
        this.toastr.success('CSS applied to all sections');
    }
    

    // Update live styles
    updateLiveStyles() {
        const styleSheetId = 'dynamic-css-style';
        let styleEl = document.getElementById(styleSheetId) as HTMLStyleElement;

        if (!styleEl) {
            styleEl = document.createElement('style');
            styleEl.id = styleSheetId;
            document.head.appendChild(styleEl);
        }

        let css = '';
        for (const selector in this.styleMap) {
            css += `.${selector} {`;
            for (const prop in this.styleMap[selector]) {
                css += `${prop}: ${this.styleMap[selector][prop]};`;
            }
            css += '}';
        }

        styleEl.innerHTML = css;
    }

    // Edit event handler
    onEdit(pageName: string, event: any) {
        const newHtml = event.target.innerHTML;
        this.pageSections[pageName]['FullPage'] = this.sanitizer.bypassSecurityTrustHtml(newHtml);
    }

    // Apply style to selection
    applyStyleToSelection() {
        const selection = window.getSelection();
        if (!selection || selection.rangeCount === 0) return;
    
        const range = selection.getRangeAt(0);
        const selectedText = range.extractContents();
    
        const span = document.createElement('span');
    
        // Apply styles
        if (this.liveStyles.color) span.style.color = this.liveStyles.color;
        if (this.liveStyles.background) span.style.backgroundColor = this.liveStyles.background;
        if (this.liveStyles.fontSize) span.style.fontSize = this.liveStyles.fontSize;
        if (this.liveStyles.fontWeight) span.style.fontWeight = this.liveStyles.fontWeight;
        if (this.liveStyles.textAlign) span.style.textAlign = this.liveStyles.textAlign;
        span.appendChild(selectedText);
    
        range.insertNode(span);
        selection.removeAllRanges();
    }
    
    // NEW METHODS FOR GRID AND DRAG FUNCTIONALITY
    
    // Get section keys for a page
    getSectionKeys(pageName: string): string[] {
        if (!this.allPagePrompts[pageName]) return [];
        return Object.keys(this.allPagePrompts[pageName]);
    }
    
    // Get sections data for drag/drop
    getSectionsData(pageName: string): string[] {
        return this.getSectionKeys(pageName);
    }
    
    // Get HTML for a specific section
    // In your component class
    getSectionHtml(pageName: string, sectionKey: string): SafeHtml {
        if (this.sectionHtmls[pageName]?.[sectionKey]) {
        const html = this.sectionHtmls[pageName][sectionKey];
        // Wrap with a div that has a unique class for this section
        // Add scoped CSS directly inside each section
        const safeHtml = `
            <div class="section-preview-wrapper section-${pageName}-${sectionKey}">
            <style scoped data-section-css="true">
                ${COMMON_CSS}
                /* Additional section-specific styles */
                .section-${pageName}-${sectionKey} * {
                box-sizing: border-box;
                }
            </style>
            ${html}
            </div>
        `;
       this.hideLoading();
        return this.sanitizer.bypassSecurityTrustHtml(safeHtml);
        }
        this.showLoading();
        return this.sanitizer.bypassSecurityTrustHtml('<div>Section loading...</div>');
    }
    
    
    // Show page tools
    showPageTools(pageName: string) {
        this.hoveredPage = pageName;
    }


    
    // Hide page tools
    hidePageTools(pageName: string) {
        if (this.hoveredPage === pageName) {
            setTimeout(() => {
                if (this.hoveredPage === pageName) {
                    this.hoveredPage = null;
                }
            }, 300);
        }
    }
    
    // Show section tools
    showSectionTools(pageName: string, sectionKey: string) {
        this.hoveredSection = sectionKey;
    }
    
    // Hide section tools
    hideSectionTools() {
        setTimeout(() => {
            this.hoveredSection = null;
        }, 300);
    }
    
    // Handle page drop
   // In component class
onPageDrop(event: CdkDragDrop<string[]>) {
  if (event.previousContainer === event.container) {
    // Reorder pages array
    moveItemInArray(this.pageRenderOrder, event.previousIndex, event.currentIndex);
    
    // Update section order map to maintain relationships
    const newOrder = [...this.pageRenderOrder];
    this.pageRenderOrder = [];
    setTimeout(() => this.pageRenderOrder = newOrder);
    
    // Force update section mappings
    this.sectionOrderMap = {...this.sectionOrderMap};
    this.cdr.detectChanges();
  }
}


    
    
// Modified drop handler
onSectionDrop(event: CdkDragDrop<string[]>, pageName?: string): void {
  const targetPage = pageName || this.getCurrentPageName();
  const sourceArray = this.getPageSections(targetPage);
  
  if (event.previousContainer === event.container) {
    // Reordering within the same page
    moveItemInArray(sourceArray, event.previousIndex, event.currentIndex);
  } else {
    // Moving between pages - need to handle cross-page moves
    const sourcePageSections = event.previousContainer.data;
    const targetPageSections = event.container.data;
    
    transferArrayItem(
      sourcePageSections,
      targetPageSections,
      event.previousIndex,
      event.currentIndex
    );
  }
  
  this.cdr.detectChanges();
}

getPageSections(pageName: string): string[] {
  if (this.sectionHtmls[pageName]) {
    return Object.keys(this.sectionHtmls[pageName]);
  }
  return [];
}

// Set current page focus
setCurrentPage(index: number): void {
  this.currentPageIndex = index;
  this.cdr.detectChanges();
}

// Copy specific page to clipboard
// copyPageToClipboard(pageName?: string): void {
//   const pageToSelect = pageName || this.getCurrentPageName();
//   const html = this.mapofPageAndHtmlBody[pageToSelect];
  
//   if (html) {
//     navigator.clipboard.writeText(html).then(() => {
//       this.toastr.success(`${pageToSelect} copied to clipboard!`);
//     }).catch(() => {
//       this.toastr.error('Failed to copy to clipboard');
//     });
//   }
// }
copyPageToClipboard(pageName?: string): void {
  const pageToSelect = pageName || this.getCurrentPageName();
  const html = this.mapofPageAndHtmlBody?.[pageToSelect] || this.pageSections?.[pageToSelect]?.FullPage;

  if (html && typeof html === 'string' && html.trim() !== '') {
    navigator.clipboard.writeText(html).then(() => {
      this.toastr.success(`${pageToSelect} copied to clipboard!`);
    }).catch((err) => {
      console.error('❌ Clipboard error:', err);
      this.toastr.error('Failed to copy to clipboard');
    });
  } else {
    console.warn(`⚠️ No HTML content found for: ${pageToSelect}`);
    this.toastr.error(`Nothing to copy for page "${pageToSelect}"`);
  }
}






getAllSectionLists(): HTMLElement[] {
  return Array.from(document.querySelectorAll('.connected-sections')) as HTMLElement[];
}
  
    
    
    // Zoom control methods
 
 zoomIn() {
        this.scale = Math.min(this.scale + 0.1, 2);
        this.zoomLevel = this.scale;
        this.cdr.detectChanges();
    }

    zoomOut() {
        this.scale = Math.max(this.scale - 0.1, 0.3);
        this.zoomLevel = this.scale;
        this.cdr.detectChanges();
    }



    selectedNavbarPage: string = '';
    // navbarLinks: Record<string, { label: string, href: string }[]> = {};
    // availablePages: { label: string, href: string }[] = [];

    // Select Navbar Section

    // Extract links from navbar HTML
    extractNavbarLinks(pageName: string, html: string) {

        console.log('extracting navbar ..')

        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = html;

        const navLinks = Array.from(tempDiv.querySelectorAll('nav a, ul[class*="nav"] a, ul[class*="menu"] a') );
        // const navLinks = Array.from(tempDiv.querySelectorAll('.nav-1-nav-links a'));

        this.navbarLinks[pageName] = navLinks.map(link => ({
            label: link.textContent?.trim() || '',
            href: link.getAttribute('href') || '#'
        }));

        // Also prepare available pages list
        this.availablePages = Object.keys(this.pageSections).map(p => ({
            label: p,
            href: `${p.replace(/\s+/g, '-').toLowerCase()}.html`
        }));
    }

    // Add new link
    // addLink(pageName: string) {
    //     this.navbarLinks[pageName].push({ label: '', href: '#' });
    // }

    // // Remove a link
    // removeLink(pageName: string, index: number) {
    //     this.navbarLinks[pageName].splice(index, 1);
    // }

      toggleSidebar() {
    this.sidebarCollapsed = !this.sidebarCollapsed;
    this.updateGridLayout();
  }

   private updateGridLayout() {
    setTimeout(() => {
      const canvas = document.querySelector('.canvas-main-area') as HTMLElement;
      if (canvas) {
        canvas.style.transition = 'margin 0.3s ease';
        canvas.style.marginLeft = this.sidebarCollapsed ? '0' : '300px';
      }
    }, 50);
  }

  

    // Export project as JSON file
    exportProject(): void {
        const exportData = {
            sitename: this.sitename,
            jsonInput: this.jsonInput,
            allPagePrompts: this.allPagePrompts,
            sectionHtmls: this.sectionHtmls,
            pageSections: this.pageSections,
            sectionOrderMap: this.sectionOrderMap,
            pageRenderOrder: this.pageRenderOrder,
        };
        const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `${this.sitename || 'project'}.json`;
        link.click();
        window.URL.revokeObjectURL(url);
        this.toastr.success('Project exported as JSON');
    }

    // Import project from JSON file
    importProject(): void {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.json,application/json';
        input.onchange = async (event: any) => {
            const file = event.target.files[0];
            if (!file) return;
            const reader = new FileReader();
            reader.onload = async (e: any) => {
                try {
                    const data = JSON.parse(e.target.result);
                    this.sitename = data.sitename || '';
                    this.jsonInput = data.jsonInput || '';
                    this.allPagePrompts = data.allPagePrompts || {};
                    this.sectionHtmls = data.sectionHtmls || {};
                    this.pageSections = data.pageSections || {};
                    this.sectionOrderMap = data.sectionOrderMap || {};
                    this.pageRenderOrder = data.pageRenderOrder || [];
                    this.toastr.success('Project imported successfully');
                    // Optionally, re-render or trigger change detection
                    await this.processAllPagesLiveUpdate();
                } catch (err) {
                    this.toastr.error('Failed to import project: Invalid JSON');
                }
            };
            reader.readAsText(file);
        };
        input.click();
    }

    // Toggle preview mode (simple implementation)
    previewMode(): void {
        this.sidebarOpen = false;
        this.toastr.info('Preview mode toggled');
    }

    // Apply Changes to navbar
    // applyNavbarChanges(pageName: string): void {
    //     const links = this.navbarLinks[pageName] || [];
    //     const originalHtml = this.pageSections[pageName].FullPage.toString();
        
    //     // Create parser with sanitization
    //     const parser = new DOMParser();
    //     const doc = parser.parseFromString(originalHtml, 'text/html');
        
    //     // Update all nav menus
    //     const navMenus = doc.querySelectorAll('ul.nav-1, nav ul');
    //     navMenus.forEach(ul => {
    //     ul.innerHTML = '';
    //     links.forEach(link => {
    //         const li = doc.createElement('li');
    //         const a = doc.createElement('a');
    //         a.setAttribute('href', this.sanitizer.sanitize(SecurityContext.URL, link.href) || '#');
    //         a.textContent = this.sanitizer.sanitize(SecurityContext.HTML, link.label) || 'Link';
    //         li.appendChild(a);
    //         ul.appendChild(li);
    //     });
    //     });
    
    //     // Serialize and sanitize
    //     const updatedHtml = doc.documentElement.innerHTML;
    //     this.pageSections[pageName].FullPage = this.sanitizer.bypassSecurityTrustHtml(updatedHtml);
    //     this.toastr.success('Navbar updated successfully');
    // }

    resetZoom() {
    this.zoomLevel = 1;
  }
    
    // Get transform CSS for pan and zoom
    getTransform(): string {
        return `scale(${this.scale}) translate(${this.panX}px, ${this.panY}px)`;
    }
    
    // Pan methods
    startPan(event: MouseEvent): void {
  this.isDragging = true;
  this.startPanPosition = { x: event.clientX, y: event.clientY };
  event.preventDefault();
}


doPan(event: MouseEvent): void {
  if (!this.isDragging) return;
  
  const deltaX = event.clientX - this.startPanPosition.x;
  const deltaY = event.clientY - this.startPanPosition.y;
  
  this.panX += deltaX;
  this.panY += deltaY;
  
  this.startPanPosition = { x: event.clientX, y: event.clientY };
  this.cdr.detectChanges();
}

endPan(): void {
  this.isDragging = false;
}
    
    // Edit section
    editSection(pageName: string, sectionKey: string) {
        this.editMode = true;
        this.editingSection = { page: pageName, section: sectionKey };
        
        // Get the HTML for this section
        const sectionHtml = this.sectionHtmls[pageName][sectionKey];
        this.editingSectionHtml = sectionHtml;
    }
    
    // Save section edit
    saveSectionEdit() {
        if (!this.editingSection) return;
        
        const { page, section } = this.editingSection;
        const element = document.querySelector('.editable-html') as HTMLElement;
        
        if (element) {
            const newHtml = element.innerHTML;
            
            // Update the section HTML
            this.sectionHtmls[page][section] = this.sanitizer.bypassSecurityTrustHtml(newHtml);
            
            // Update the full page HTML
            this.updateFullPageHtml(page);
            
            this.toastr.success(`Updated section: ${section}`);
            this.closeEditMode();
        }
    }
    
    // Handle section edit
    onSectionEdit(event: any) {
        // This is handled in saveSectionEdit
    }
// copyPageToClipboard(): void {
//   const currentPage = this.getCurrentPageName();
//   const html = this.pageSections[currentPage]?.FullPage?.toString() || '';
//   navigator.clipboard.writeText(html).then(() => {
//     this.toastr.success(`Copied ${currentPage} to clipboard`);
//   });
// }

// downloadCurrentPage(): void {
//   const currentPage = this.getCurrentPageName();
//   this.downloadHtml(currentPage);
// }

// Update existing download method
      handleDirectContentEdit(event: Event, page: string, section: string) {
    const target = event.target as HTMLElement;
    const content = target.innerHTML;
    this.sectionHtmls[page][section] = this.sanitizer.bypassSecurityTrustHtml(content);
    this.updateFullPageHtml(page);
  }
    
    // Close edit mode
    closeEditMode() {
        this.editMode = false;
        this.editingSection = null;
        this.editingSectionHtml = null;
    }
    
    // Update full page HTML after section edits
    // Update section handling with better sanitization
    private updateFullPageHtml(pageName: string): void {
        const sectionHtmls: string[] = [];
        
        for (const sectionKey of this.getSectionKeys(pageName)) {
        const html = this.sectionHtmls[pageName][sectionKey];
        if (html) {
            // Ensure each section has CSS applied properly
            const htmlWithCss = this.applyCssToSectionHtml(html.toString(), pageName, sectionKey);
            sectionHtmls.push(htmlWithCss);
        }
        }
    
        // Create a more robust HTML document with CSS properly isolated
        const finalHtml = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>${pageName}</title>
        <style id="common-styles">
            ${COMMON_CSS}
            /* Additional page-specific rules */
            body {
            margin: 0 !important;
            padding: 0 !important;
            font-family: 'Segoe UI', sans-serif !important;
            }
            .page-wrapper {
            width: 100%;
            max-width: 100%;
            overflow-x: hidden;
            }
            /* Ensure section content is styled properly */
            .section-content {
            position: relative;
            width: 100%;
            }
        </style>
        </head>
        <body>
        <div class="page-wrapper">
            ${sectionHtmls.join('\n')}
        </div>
        <script>
            // Simple script to ensure styles are applied
            document.addEventListener('DOMContentLoaded', function() {
            // Force a repaint to ensure styles are applied
            document.body.style.display = 'none';
            setTimeout(function() { document.body.style.display = ''; }, 10);
            });
        </script>
        </body>
        </html>`;
        
        this.pageSections[pageName] = {
        FullPage: this.sanitizer.bypassSecurityTrustHtml(finalHtml)
        };
    }

    // Add this to initialize the current page


getPageTransform(): string {
  return `scale(${this.scale})`;
}

    refreshAllSectionCSS(): void {
        // Refresh CSS in all section previews
        for (const pageName of this.objectKeys(this.pageSections)) {
        for (const sectionKey of this.getSectionKeys(pageName)) {
            const html = this.sectionHtmls[pageName][sectionKey];
            if (html) {
            // Re-apply CSS to the section HTML
            const htmlWithCss = this.applyCssToSectionHtml(html.toString(), pageName, sectionKey);
            this.sectionHtmls[pageName][sectionKey] = this.sanitizer.bypassSecurityTrustHtml(htmlWithCss);
            }
        }
        
        // Update the full page HTML
        this.updateFullPageHtml(pageName);
        }
        
        // Ensure CSS is applied to the DOM
        this.ensureCommonCssForAllSections();
        
        // this.toastr.success('Refreshed CSS for all sections');
    }
    
    // Remove section
    removeSection(pageName: string, sectionKey: string) {
        if (confirm(`Are you sure you want to remove the ${sectionKey} section?`)) {
            // Remove from data structures
            delete this.allPagePrompts[pageName][sectionKey];
            delete this.sectionHtmls[pageName][sectionKey];
            
            // Update the full page HTML
            this.updateFullPageHtml(pageName);
            
            // this.toastr.success(`Removed section: ${sectionKey}`);
        }
    }

    // Modal state for new page
    showNewPageModal: boolean = false;

    // Track current page index for navigation and actions
    // currentPageIndex: number = 0;

    // Used for new page creation
    newPageName: string = '';

    // Add a new page (shows modal)
    addNewPage(): void {
        this.showNewPageModal = true;
        this.newPageName = '';
    }

    // Close the new page modal
    closeNewPageModal(): void {
        this.showNewPageModal = !this.showNewPageModal;
        this.newPageName = '';
    }

    // Confirm adding a new page
    confirmAddNewPage(): void {
        if (!this.newPageName.trim()) {
            this.toastr.error('Please enter a page name');
            return;
        }
        if (this.pageRenderOrder.includes(this.newPageName)) {
            this.toastr.error('Page name already exists');
            return;
        }
        this.pageRenderOrder.push(this.newPageName);
        this.allPagePrompts[this.newPageName] = {};
        this.sectionHtmls[this.newPageName] = {};
        this.pageSections[this.newPageName] = { FullPage:''};
        this.sectionOrderMap[this.newPageName] = [];
        this.closeNewPageModal();
        this.toastr.success(`Added new page: ${this.newPageName}`);
    }

    // Duplicate the current page
    duplicateCurrentPage(): void {
        const currentPage = this.getCurrentPage();
        if (!currentPage) {
            this.toastr.error('No page selected to duplicate');
            return;
        }
        let newPageName = currentPage + '_Copy';
        let count = 1;
        while (this.pageRenderOrder.includes(newPageName)) {
            newPageName = `${currentPage}_Copy${count++}`;
        }
        // Deep clone all structures
        this.pageRenderOrder.push(newPageName);
        this.allPagePrompts[newPageName] = JSON.parse(JSON.stringify(this.allPagePrompts[currentPage]));
        this.sectionHtmls[newPageName] = JSON.parse(JSON.stringify(this.sectionHtmls[currentPage]));
        this.pageSections[newPageName] = { FullPage: this.pageSections[currentPage].FullPage };
        this.sectionOrderMap[newPageName] = [...(this.sectionOrderMap[currentPage] || [])];
        this.toastr.success(`Duplicated page: ${currentPage}`);
    }

    // Delete the current page
    deleteCurrentPage(): void {
        const currentPage = this.getCurrentPage();
        if (!currentPage) {
            this.toastr.error('No page selected to delete');
            return;
        }
        if (this.pageRenderOrder.length === 1) {
            this.toastr.error('At least one page must remain');
            return;
        }
        if (confirm(`Are you sure you want to delete the page "${currentPage}"?`)) {
            // Remove from all structures
            this.pageRenderOrder = this.pageRenderOrder.filter(p => p !== currentPage);
            delete this.allPagePrompts[currentPage];
            delete this.sectionHtmls[currentPage];
            delete this.pageSections[currentPage];
            delete this.sectionOrderMap[currentPage];
            // Adjust currentPageIndex if needed
            if (this.currentPageIndex >= this.pageRenderOrder.length) {
                this.currentPageIndex = this.pageRenderOrder.length - 1;
            }
            this.toastr.success(`Deleted page: ${currentPage}`);
        }
    }

    getGridSize(): string {
  // Example: returns a 20px grid, adjust as needed
  return `translate(${this.panX}px, ${this.panY}px) scale(${this.scale})`;
}

    // Add a new section to the current page
   addNewSectionToCurrentPage() {
    const page = this.getCurrentPageName();
    if (!page) return;

    const newSection = `section-${Date.now()}`;
    this.sectionOrderMap[page] = [...(this.sectionOrderMap[page] || []), newSection];
    this.sectionHtmls[page][newSection] = this.sanitizer.bypassSecurityTrustHtml('<div>New Section</div>');
    this.cdr.detectChanges();
  }
    // Get the transform for the grid (alias for getTransform)
   getGridTransform(): string {
  return `translate(${this.panX}px, ${this.panY}px) scale(${this.scale})`;
}

deleteSection(page: string, section: string) {
    this.lastDeletedSection = {
      page,
      section,
      content: this.sectionHtmls[page][section]
    };
    
    this.sectionOrderMap[page] = this.sectionOrderMap[page].filter(s => s !== section);
    delete this.sectionHtmls[page][section];
    this.cdr.detectChanges();
  }

// Add this method to fix template errors



// Add this method to your component
getCurrentPageSections(): string[] {
  const currentPage = this.getCurrentPageName();
  return currentPage ? 
    this.sectionOrderMap[currentPage] || Object.keys(this.sectionHtmls[currentPage] || {}) 
    : [];
}

// Also add this helper method if missing
getCurrentPageName(): string {
  return this.pageRenderOrder[this.currentPageIndex] || '';
}
    // Handle mouse wheel for zooming
    onWheel(event: WheelEvent): void {
        if (event.ctrlKey || event.metaKey) {
            event.preventDefault();
            if (event.deltaY < 0) {
                this.zoomIn();
            } else {
                this.zoomOut();
            }
        }
    }

    // Get the current page name
    getCurrentPage(): string | null {
  if (this.pageRenderOrder.length === 0) return null;
  this.currentPageIndex = Math.min(this.currentPageIndex, this.pageRenderOrder.length - 1);
  return this.pageRenderOrder[this.currentPageIndex];
}

// Update the canvas transform methods


    // Detect if the device is mobile (simple check)
    get isMobile(): boolean {
        return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }
    
    // Open new section modal
    addNewSection(pageName: string, afterSection: string = null) {
        this.showNewSectionModal = true;
        this.newSectionPage = pageName;
        this.newSectionAfter = afterSection;
        this.newSectionName = '';
        this.newSectionType = '';
        this.newSectionDescription = '';
    }
    
    // Cancel adding new section
    cancelAddSection() {
        this.showNewSectionModal = false;
        this.newSectionName = '';
        this.newSectionType = '';
        this.newSectionDescription = '';
    }

     undoDelete() {
    if (this.lastDeletedSection) {
      const { page, section, content } = this.lastDeletedSection;
      this.sectionOrderMap[page].push(section);
      this.sectionHtmls[page][section] = content;
      this.lastDeletedSection = null;
      this.cdr.detectChanges();
    }
  }
    
    // Confirm adding new section
    async confirmAddSection() {
        if (!this.newSectionName || !this.newSectionType) {
            this.toastr.error('Please fill out all required fields');
            return;
        }
        
        const sectionKey = `${this.newSectionType}Section`;
        
        // Create empty JSON structure for the new section
        const emptyJson = {
            "type": this.newSectionType,
            "title": "New " + this.newSectionType.charAt(0).toUpperCase() + this.newSectionType.slice(1),
            "description": this.newSectionDescription || "Add description here",
            "content": [],
            "styles": {
                "background": "#ffffff",
                "padding": "20px"
            }
        };
        
        // Add to allPagePrompts
        if (!this.allPagePrompts[this.newSectionPage]) {
            this.allPagePrompts[this.newSectionPage] = {};
        }
        
        // Insert at the correct position if afterSection is specified
        if (this.newSectionAfter) {
            const sectionKeys = this.getSectionKeys(this.newSectionPage);
            const afterIndex = sectionKeys.indexOf(this.newSectionAfter);
            
            if (afterIndex !== -1) {
                const newOrder: Record<string, string> = {};
                let inserted = false;
                
                sectionKeys.forEach((key, index) => {
                    newOrder[key] = this.allPagePrompts[this.newSectionPage][key];
                    
                    if (index === afterIndex) {
                        // Insert the new section after this one
                        newOrder[sectionKey] = JSON.stringify(emptyJson);
                        inserted = true;
                    }
                });
                
                if (!inserted) {
                    newOrder[sectionKey] = JSON.stringify(emptyJson);
                }
                
                this.allPagePrompts[this.newSectionPage] = newOrder;
            } else {
                this.allPagePrompts[this.newSectionPage][sectionKey] = JSON.stringify(emptyJson);
            }
        } else {
            this.allPagePrompts[this.newSectionPage][sectionKey] = JSON.stringify(emptyJson);
        }
        
        // Initialize section HTML structure if needed
        if (!this.sectionHtmls[this.newSectionPage]) {
            this.sectionHtmls[this.newSectionPage] = {};
        }
        
        // Generate HTML for the new section
        const html = await this.generateJson({ 
            jsonStructure: JSON.stringify(emptyJson), 
            sectionType: sectionKey 
        });
        
        // Store section HTML
        this.sectionHtmls[this.newSectionPage][sectionKey] = this.sanitizer.bypassSecurityTrustHtml(html);
        
        // Update full page HTML
        this.updateFullPageHtml(this.newSectionPage);
        
        this.toastr.success(`Added new ${this.newSectionType} section`);
        this.showNewSectionModal = false;
        this.newSectionName = '';
        this.newSectionType = '';
        this.newSectionDescription = '';
    }


    missingPages:string[] = [];
    existingPages:string[] = [];

   async dividePagesToExistingOrNew(jsonOutput: string, siteName: string) {
  let parseJson = JSON.parse(jsonOutput);

  // Extract pages in the exact order they appear in JSON
  function extractPagesInOrder(obj: any): string[] {
    let pages: string[] = [];
    for (const [key, value] of Object.entries(obj)) {
      pages.push(key);
      if (value && typeof value === 'object' && value['Children']) {
        pages = pages.concat(extractPagesInOrder(value['Children']));
      }
    }
    return pages;
  }

  // Get pages in original JSON order
  let orderedPages = extractPagesInOrder(parseJson);
  console.log('Pages in JSON order:', orderedPages);

  this.existingPages = [];
  this.missingPages = [];

  // Check existence while maintaining order
  for (const page of orderedPages) {
    const exists = await this.checkIfPageExists(siteName, page);
    if (exists) {
      this.existingPages.push(page);
    } else {
      this.missingPages.push(page);
    }
  }

  console.log('Missing Pages:', this.missingPages);
  console.log('Existing Pages:', this.existingPages);
  
  this.showLoading('Loading existing and missing pages...');
  this.updateLoadingProgress(10, 'Fetching existing pages...');

  await this.mapOfExistingPagesWithHtmlCss(this.existingPages);

  this.updateLoadingProgress(50, 'Generating missing pages...');
  await this.generateMissingPagesWithAI(this.missingPages, jsonOutput);

  this.updateLoadingProgress(90, 'Finalizing UI...');
  
  // Clear and rebuild pageRenderOrder in JSON order
  // Replace your current page ordering logic with:
      this.pageRenderOrder = [];
      for (const page of orderedPages) { // orderedPages maintains JSON order
        if (this.mapofPageAndHtmlBody[page]) {
          this.pageSections[page] = { FullPage: this.mapofPageAndHtmlBody[page] };
          this.pageRenderOrder.push(page);
        }
      }

  console.log('Final pageRenderOrder:', this.pageRenderOrder);

  this.updateLoadingProgress(100, 'All pages loaded!');
  setTimeout(() => this.hideLoading(), 500);
  this.cdr.detectChanges();
}

createPageOrderFromJson(jsonInput: string): string[] {
  try {
    const parsedJson = JSON.parse(jsonInput);
    const orderedPages: string[] = [];
    
    // Recursively traverse JSON to maintain order
    function traverseInOrder(obj: any) {
      Object.keys(obj).forEach(key => {
        orderedPages.push(key);
        if (obj[key] && obj[key]['Children']) {
          traverseInOrder(obj[key]['Children']);
        }
      });
    }
    
    traverseInOrder(parsedJson);
    return orderedPages;
  } catch (error) {
    console.error('Error parsing JSON for page order:', error);
    return [];
  }
}

    async checkIfPageExists(siteName: string, pageName: string): Promise<boolean> {
     
      return new Promise((resolve) => {
        this.siteTreeService.readPages(this.formatSiteName(siteName),  this.sanitizeFilename(pageName)).subscribe({
          next: (response) => {
            // Adjust this check based on your API's actual response
            if (response && (response.exists || (typeof response === 'string' && response.trim() !== '' && !response.includes('❌ File not found')))) {
              console.log(`Page "${this.sanitizeFilename(pageName)}" exists in site "${this.formatSiteName(siteName)}"`);
              resolve(true);
            } else {
              console.log(`Page "${this.sanitizeFilename(pageName)}" does not exist in site "${this.formatSiteName(siteName)}"`);
              resolve(false);
            }
          },
          error: (error) => {
            console.error(`Error checking page "${pageName}" in site "${siteName}":`, error);
            resolve(false);
          }
        });
      });
    }

    mapofPageAndHtmlBody: Record<string, string> = {};


async mapOfExistingPagesWithHtmlCss(existingPages: string[]): Promise<void> {
  this.mapofPageAndHtmlBody = {};
  
  // Create promises for all page requests
  const pagePromises = existingPages.map(page => {
    return new Promise<void>((resolve, reject) => {
      this.siteTreeService.readPages(this.formatSiteName(this.sitename), this.sanitizeFilename(page)).subscribe({
        next: (response) => {
          if (typeof response === 'string') {
            let htmlBody: string = response;
            // Remove Angular SafeValue wrapper if present
            const safeValueIndex = htmlBody.indexOf('<!DOCTYPE');
            if (htmlBody.includes('SafeValue must use [property]=binding:') && safeValueIndex !== -1) {
              htmlBody = htmlBody.substring(safeValueIndex);
            }
            
            this.mapofPageAndHtmlBody[page] = htmlBody;
            
            // Calculate sectionHtmls for existing pages
            this.calculateSectionHtmlsForExistingPage(page, htmlBody);
            
            console.log(`Page "${page}" HTML extracted successfully.`);
            resolve();
          } else {
            reject(new Error(`Invalid response for page ${page}`));
          }
        },
        error: (error) => {
          console.error(`Error reading page "${page}":`, error);
          reject(error);
        }
      });
    });
  });

  // Wait for all pages to load
  try {
    await Promise.all(pagePromises);
    console.log('All existing pages loaded:', this.mapofPageAndHtmlBody);
  } catch (error) {
    console.error('Error loading some pages:', error);
  }
}

// New method to calculate sectionHtmls for existing pages
calculateSectionHtmlsForExistingPage(pageName: string, htmlContent: string): void {
  // Initialize if not exists
  if (!this.sectionHtmls[pageName]) {
    this.sectionHtmls[pageName] = {};
  }
  
  // Parse HTML to extract sections (you might need to adjust this based on your HTML structure)
  const parser = new DOMParser();
  const doc = parser.parseFromString(htmlContent, 'text/html');
  
  // Extract sections based on your HTML structure - adjust selectors as needed
  const sections = doc.querySelectorAll('[data-section]');
  sections.forEach(section => {
    const sectionName = section.getAttribute('data-section');
    if (sectionName) {
      this.sectionHtmls[pageName][sectionName] = this.sanitizer.bypassSecurityTrustHtml(section.outerHTML);
    }
  });
  
  // If no sections found, create a default "FullPage" section
  if (Object.keys(this.sectionHtmls[pageName]).length === 0) {
    this.sectionHtmls[pageName]['FullPage'] = this.sanitizer.bypassSecurityTrustHtml(htmlContent);
  }
}
    async generateMissingPagesWithAI(missingPages: string[], jsonInput: string): Promise<void> {
  if (!missingPages.length) {
    this.toastr.info('No missing pages to generate');
    return;
  }
  if (!jsonInput) {
    this.toastr.error('No JSON input found for site structure.');
    return;
  }

  let parsedJson: any;
  try {
    parsedJson = typeof jsonInput === 'string' ? JSON.parse(jsonInput) : jsonInput;
  } catch (err) {
    this.toastr.error('Invalid JSON input.');
    return;
  }

  // Helper to recursively get all page definitions (including nested Children)
  function getPageDefinitions(obj: any): Record<string, any> {
    let pages: Record<string, any> = {};
    for (const [key, value] of Object.entries(obj)) {
      pages[key] = value;
      if (value && typeof value === 'object' && value['Children']) {
        Object.assign(pages, getPageDefinitions(value['Children']));
      }
    }
    return pages;
  }

  const allPagesDef = getPageDefinitions(parsedJson);
  console.log('All Pages Definitions:', allPagesDef);

  // Create all pages first, then save them
  let pagesToSave = new Map<string, string>();

  let sanitizedPageName = '';

  for (const pageName of missingPages) {
    
    const pageDef = allPagesDef[pageName];
    if (!pageDef) continue;

    // Get all sections for this page (excluding Children)
    const sectionEntries = Object.entries(pageDef).filter(([k]) => k !== 'Children');
    const sectionHtmls: string[] = [];
    this.sectionHtmls[pageName] = {};
    this.allPagePrompts[pageName] = {};

    

    for (const [sectionName, sectionDescription] of sectionEntries) {
      // Generate prompt for section, passing the full jsonInput as context
      const prompt = await this.generatePromptFromSection(sectionName, sectionDescription as string);
      this.allPagePrompts[pageName][sectionName] = prompt;

      // Generate HTML for section
      const html = await this.generateJson({ sectionType: sectionName, jsonStructure: prompt });
      this.sectionHtmls[pageName][sectionName] = html;
      sectionHtmls.push(html);
    }

    sanitizedPageName = this.sanitizeFilename(pageName);

    // Combine all section HTMLs and CSS for the page
    const finalHtml = this.createCompleteHtml(sanitizedPageName, COMMON_CSS, sectionHtmls.join('\n'));

    this.pageSections[pageName] = { FullPage: finalHtml };
    this.mapofPageAndHtmlBody[pageName] = finalHtml;
    
    // Add to the batch for saving
    // pagesToSave.map(pageName: finalHtml.toString());

    pagesToSave.set(pageName, finalHtml.toString());

    // Instead of saving all pages at once, save each page individually
    for (const [pageName, html] of pagesToSave.entries()) {
       
      const pageObj: Record<string, string> = { [pageName]: html };
    // Ensure the page name is sanitized
      await new Promise<void>((resolve) => {
        this.siteTreeService.createHtmlfile(this.siteId, this.sitename, pageObj).subscribe({
          next: (response) => {
            console.log(`Page "${pageName}" created successfully.`);
            this.toastr.success(`Generated and saved page: ${pageName}`);
            resolve();
          },
          error: (error) => {
            console.error(`Error creating page "${pageName}":`, error);
            this.toastr.error(`Failed to save generated page: ${pageName}`);
            resolve();
          }
        });
      });
    }

  }

  // Save all pages at once after they're all created
  // if (pagesToSave.size > 0) {
  //   this.siteTreeService.createHtmlfile(this.siteId, this.sitename, pagesToSave).subscribe({
  //     next: (response) => {
  //       console.log('All pages created successfully:', Array.from(pagesToSave.keys()));
  //       this.toastr.success(`Generated and saved ${pagesToSave.size} pages successfully.`);
  //     },
  //     error: (error) => {
  //       console.error('Error creating pages:', error);
  //       this.toastr.error('Failed to save some generated pages.');
  //     }
  //   });
  // }

  console.log('Map of All Pages with HTML:', this.mapofPageAndHtmlBody);
  this.toastr.success('Generated all missing pages with AI.');
  this.cdr.detectChanges();
}
    

    toggleViewMode(): void {
  // Toggle between grid and single-page view
  this.isGridView = !this.isGridView;
}

// Add this property to your component
isGridView: boolean = false; // Set to true for grid, false for single page
    

   
}






                        // const enhancedPrompt = `
                        // 🎯 Enhance the content of this section using the following context.
                        
                        // 🧠 Instructions:
                        // - You are given an existing JSON structure for a UI section.
                        // - Your job is to update ONLY the content-related fields like "text", "title", "label", "description", and "placeholder".
                        // - You must NOT change the structure, hierarchy, tags, keys, class names, or styling values.
                        // - You must NOT add or remove any keys or elements.
                        // - You must return ONLY the updated JSON structure in valid format.
                        
                        // 📄 Page Prompt:
                        // "${this.initialPrompt}"
                        
                        // 📦 Section Name:
                        // "${sectionName}"
                        
                        // 📘 Section Description:
                        // "${sectionDescription}"
                        
                        // 📌 Existing JSON (modify this only):
                        // ${baseJsonString}
                        
                        // 🚫 Do NOT include:
                        // - Any explanation, commentary, or markdown
                        // - Any prefix like "Here is the updated JSON"
                        // - Any new elements that were not already present
                        
                        // ✅ Output Requirement:
                        // Only return the updated JSON structure — nothing else.`;

                        
//     async processPageSections(pageName: string, sectionMap: Record<string, string>) {
//   // Initialize section order map
//   this.sectionOrderMap[pageName] = this.sectionOrderMap[pageName] || [];
  
//   // Clear existing sections
//   this.sectionHtmls[pageName] = {};

//   const htmlTasks = Object.entries(sectionMap).map(async ([sectionName, jsonPrompt]) => {
//     const html = await this.generateJson({ sectionType: sectionName, jsonStructure: jsonPrompt });
    
//     // Store with proper ordering
//     this.sectionOrderMap[pageName].push(sectionName);
//     this.sectionHtmls[pageName][sectionName] = this.sanitizer.bypassSecurityTrustHtml(html);
//   });

//   await Promise.all(htmlTasks);
  
//   // Update full page HTML with all sections
//   this.updateFullPageHtml(pageName);
// }

    // Generate JSON to HTML
    // 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:', parsedJson);

    //             this.siteTreeService.generateHtml(parsedJson).subscribe({
    //                 next: (res) => {
    //                     console.log('✅ Response from HTML API:', res);
    //                     if (res && res.msg) {
    //                         console.log("CHECKING DEPLOYED URL ",res.deployedUrl)
    //                         this.deployedUrl = res.deployedUrl;
    //                         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.');
    //         }
    //     });
    // }

    
/*
///// commited code //// download 
// Download HTML
    downloadHtml(pageName: string) {
    const sectionOrder = this.sectionOrderMap[pageName] || Object.keys(this.sectionHtmls[pageName] || {});
    let fullHtml = '';

    for (const sectionName of sectionOrder) {
        const html = this.sectionHtmls[pageName]?.[sectionName];
        if (html) {
            fullHtml += html + '\n\n';
        }
    }
        // const fullHtml = Object.values(this.pageSections[pageName]).join('\n');

        const finalHtml = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>${pageName}</title>
            <style>
                ${COMMON_CSS}
                
                html, body {
                    margin: 0 !important;
                    padding: 0 !important;
                    min-height: 100% !important;
                    width: 100% !important;
                    font-family: 'Segoe UI', sans-serif !important;
                }
            
            </style>
        </head>
        <body>
                ${fullHtml}
        </body>
        </html>`;
        
    // const fullHtml = Object.values(this.pageSections[pageName]).join('\n');
    const blob = new Blob([finalHtml], { 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);
    }
*/ 







// // 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';
// import * as sha256 from 'crypto-js/sha256';
// import SHA256 from 'crypto-js/sha256';



// @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 = '';
//     initialPrompt = '';
//     id: number;
//     allPagePrompts: Record<string, Record<string, string>> = {};
//     initialGeneratedPrompts: Record<string, Record<string, string>> = {};
//     promptHashCache: Record<string, string> = {};
//     pageSections: Record<string, { FullPage: SafeHtml }> = {};


//     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 get  data from that id
//     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 {

//                         this.initialPrompt = res.prompt;

//                         // 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

//     // 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, 'sectionc name and   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>)`;



//     async generatePromptFromSection(
//         sectionName: string,
//         sectionDescription: string,
//         headerId: number = 35,
//         operationType: string = 'template 1'
//     ): Promise<string> {
//         return new Promise((resolve) => {
//             const fieldType = sectionName.toLowerCase().replace(/section$/i, '').trim();

//             this.siteTreeService.getDlf(headerId, operationType, fieldType).subscribe({
//                 next: async (res) => {
//                     try {
//                         const jsonBlock = res?.javacode;
//                         if (!jsonBlock) return resolve('{}');

//                         const baseJson = typeof jsonBlock === 'string' ? JSON.parse(jsonBlock) : jsonBlock;
//                         const baseJsonString = JSON.stringify(baseJson, null, 2);

//                         const enhancedPrompt = `
//                         🎯 Enhance the content of this section using the following context.
                        
//                         🧠 Instructions:
//                         - You are given an existing JSON structure for a UI section.
//                         - Your job is to update ONLY the content-related fields like "text", "title", "label", "description", and "placeholder".
//                         - You must NOT change the structure, hierarchy, tags, keys, class names, or styling values.
//                         - You must NOT add or remove any keys or elements.
//                         - You must return ONLY the updated JSON structure in valid format.
                        
//                         📄 Page Prompt:
//                         "${this.initialPrompt}"
                        
//                         📦 Section Name:
//                         "${sectionName}"
                        
//                         📘 Section Description:
//                         "${sectionDescription}"
                        
//                         📌 Existing JSON (modify this only):
//                         ${baseJsonString}
                        
//                         🚫 Do NOT include:
//                         - Any explanation, commentary, or markdown
//                         - Any prefix like "Here is the updated JSON"
//                         - Any new elements that were not already present
                        
//                         ✅ Output Requirement:
//                         Only return the updated JSON structure — nothing else.
//                         `;


//                         const hash = sha256(enhancedPrompt).toString();

//                         if (this.promptHashCache[hash]) {
//                             return resolve(this.promptHashCache[hash]);
//                         }

//                         // const enhanced = await this.callLlm(enhancedPrompt);
//                         // this.promptHashCache[hash] = enhanced;

//                         resolve(baseJsonString);
//                     } catch (err) {
//                         console.error('❌ JSON parse error:', err);
//                         resolve('{}');
//                     }
//                 },
//                 error: () => resolve('{}')
//             });
//         });
//     }

//     cachedPromptHashes: Record<string, Record<string, string>> = {};
//     sectionHtmls: Record<string, Record<string, string>> = {};

//     // Step 1 - Generate SHA-256 Hash

//     getPromptHash(prompt: string): string {
//         return SHA256(prompt).toString();
//     }


//     // Step 2 - Enhance per section with Hash Check + LLM call in Parallel

//     async processAllPagesLiveUpdate() {
//         const htmlGenerationTasks: Promise<void>[] = [];

//         for (const [pageName, sectionMap] of Object.entries(this.allPagePrompts)) {
//             htmlGenerationTasks.push(this.processPageSections(pageName, sectionMap));
//         }

//         await Promise.all(htmlGenerationTasks);
//     }

//     async processPageSections(pageName: string, sectionMap: Record<string, string>) {
//         const sectionHtmls: string[] = [];

//         const htmlTasks = Object.entries(sectionMap).map(async ([sectionName, jsonPrompt]) => {
//             const html = await this.generateJson({ sectionType: sectionName, jsonStructure: jsonPrompt });
//             sectionHtmls.push(html);
//         });

//         await Promise.all(htmlTasks);

//         const finalHtml = `<style>${COMMON_CSS}</style>\n${sectionHtmls.join('\n')}`;
//         const safeHtml = this.sanitizer.bypassSecurityTrustHtml(finalHtml);

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



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

//     // 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 6
//     async callLlm(data): Promise<string> {
//         return new Promise((resolve, reject) => {
//             console.log('call Llm Start ')
//             const payload = {
//                 query: data,
//                 conversationId: '677'
//             };
//             console.log(' query : ', payload.query)
//             this.siteTreeService.callLlm(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.')

//             });
//         });
//     }

//     activeEditTarget: string | null = null;
//     liveStyles = {
//         background: '',
//         color: '',
//         fontSize: '',
//         padding: '',
//         margin: '',
//         fontWeight:'',
//         textAlign:'',
//     };

//     selectEditable(pageName: string) {
//         this.activeEditTarget = pageName;
//     }

//     applyLiveStyles() {
//         const target = document.querySelector(`[data-target='${this.activeEditTarget}']`) as HTMLElement;
//         if (target) {
//             Object.keys(this.liveStyles).forEach((prop) => {
//                 if (this.liveStyles[prop]) {
//                     target.style[prop] = this.liveStyles[prop];
//                 }
//             });
//         }
//         this.toastr.success(`🎨 Style updated for: ${this.activeEditTarget}`);
//     }

//     // 🔁 Track raw edits
//     rawEdits: Record<string, string> = {};



//     selectedElementSelector = '';
//     styleMap: Record<string, any> = {
//         'hero-header': { 'background': '#fdfdfd', 'text-align': 'center' },
//         'btn-filled': { 'background': '#000', 'color': '#fff' },
//         'hero-heading': { 'font-size': '36px', 'font-weight': 'bold' },
//         // Add all classes you want to allow editing
//     };

//     getAllCssSelectors(): string[] {
//         return Object.keys(this.styleMap);
//     }


//     applyCssFromMap() {
//         this.updateLiveStyles();
//     }

//     updateLiveStyles() {
//         const styleSheetId = 'dynamic-css-style';
//         let styleEl = document.getElementById(styleSheetId) as HTMLStyleElement;

//         if (!styleEl) {
//             styleEl = document.createElement('style');
//             styleEl.id = styleSheetId;
//             document.head.appendChild(styleEl);
//         }

//         let css = '';
//         for (const selector in this.styleMap) {
//             css += `.${selector} {`;
//             for (const prop in this.styleMap[selector]) {
//                 css += `${prop}: ${this.styleMap[selector][prop]};`;
//             }
//             css += '}';
//         }

//         styleEl.innerHTML = css;
//     }

//     onEdit(pageName: string, event: any) {
//         const newHtml = event.target.innerHTML;
//         this.pageSections[pageName]['FullPage'] = this.sanitizer.bypassSecurityTrustHtml(newHtml);
//     }

//     applyStyleToSelection() {
//         const selection = window.getSelection();
//         if (!selection || selection.rangeCount === 0) return;
    
//         const range = selection.getRangeAt(0);
//         const selectedText = range.extractContents();
    
//         const span = document.createElement('span');
    
//         // Apply styles
//         if (this.liveStyles.color) span.style.color = this.liveStyles.color;
//         if (this.liveStyles.background) span.style.backgroundColor = this.liveStyles.background;
//         if (this.liveStyles.fontSize) span.style.fontSize = this.liveStyles.fontSize;
//         if (this.liveStyles.fontWeight) span.style.fontWeight = this.liveStyles.fontWeight;
//         if (this.liveStyles.textAlign) span.style.textAlign = this.liveStyles.textAlign;
//         span.appendChild(selectedText);
    
//         range.insertNode(span);
//         selection.removeAllRanges();
//       }
    
    

//     //  // Step 4
//     //  async 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: async (res) => {
//     //                 try {
//     //                     const jsonBlock = res?.javacode;
//     //                     if (!jsonBlock) {
//     //                         resolve('{}');
//     //                         return;
//     //                     }

//     //                     // console.log( fieldType , ' json is : ', jsonBlock)

//     //                     const parsedJson = typeof jsonBlock === 'string' ? JSON.parse(jsonBlock) : jsonBlock;

//     //                         // const updatedJson = this.replaceContentRecursively(parsedJson, sectionDescription);
//     //                         const formattedJson = JSON.stringify(parsedJson, null, 2);
//     //                         // 🧠 Build prompt to LLM with section info + json + full page prompt
//     // //                           // 🧠 LLM enhancement: Content update without changing structure
//     //                 const smartPrompt = `
//     //                 🔁 Enhance this JSON content while keeping the structure exactly same.

//     //                 Section Name: ${sectionName}
//     //                 Section Description: ${sectionDescription}
//     //                 Full Page Prompt: ${this.initialPrompt || ''}

//     //                 ✅ Replace or fill only content fields like: "title", "description", "text", "label", "placeholder", "heading", etc.
//     //                 ❌ Do NOT change or restructure keys, nesting, or CSS class names.
//     //                 ❌ Do NOT remove or add new blocks unless it's strictly a content array (like testimonials or FAQs).

//     //                 JSON Input:
//     //                 ${formattedJson}

//     //                 ⬇️ Return only the updated JSON with better content.
//     //                 `;


//     //                         // console.log('enhanced query ', smartPrompt);

//     // //                             // const finalJson = await this.calLlm(enhancedPrompt);
//     //                         // resolve(formattedJson);

//     //                 const enhancedJson = await this.calLlm(smartPrompt);

//     //                 // Return directly the enhanced JSON
//     //                 resolve(enhancedJson || formattedJson);

//     //                 } catch (err) {
//     //                     console.error('❌ JSON parse error:', err);
//     //                     resolve('{}');
//     //                 }
//     //             },
//     //             error: (err) => {
//     //                 console.error('❌ API error:', err);
//     //                 resolve('{}');
//     //             }
//     //         });
//     //     });
//     // }



//     // // Step 5 - generate html code via java Api 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 };
//     //     }
//     // }
//     // 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;
//     // }

//     // // 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);
//     //             }
//     //         });
//     //     });
//     // }





//     // 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!');
//     //         }
//     //     });

//     // }



// }

