import { Component } from '@angular/core';
import { treeVisualizerService } from './tree-visualizer.service';
import { SiteTreeservice } from './SiteBuilderGrid/SiteTree.service';
import { ActivatedRoute } from '@angular/router';



@Component({
  selector: 'app-tree-visualizer',
  templateUrl: './tree-visualizer.component.html',
  styleUrls: ['./tree-visualizer.component.scss']
})
export class TreeVisualizerComponent {

  activeTab: 'sitemap' | 'wireframe' = 'sitemap';
  showPopup: boolean = false;
  inputJson: string = `{
    "Login": {
        "Navbar": {},
        "Header Section": "Login form...",
        "Footer": {}
    },
    "Sign Up": {
        "Navbar": {},
        "Header Section": "Create account...",
        "Feature Section": "Get started with a new icard",
        "Children": {
            "Add Icard": {
                "Navbar": {},
                "Header Section": "Add Icard detail",
                "Feature Section": "Enter details to add an icard"
            },
            "Upload Excel": {
                "Navbar": {},
                "Header Section": "Upload student data",
                "Feature Section": "Upload excel file for student data"
            }
        }
    },
    "Icard Details": {
        "Navbar": {},
        "Header Section": "View Icard details",
        "Feature Section": "Enter icard detail to view"
    },
    "Excel Upload": {
        "Navbar": {},
        "Header Section": "Upload excel file for icard data",
        "Feature Section": "Upload excel file and convert it"
    },
    "Icard Template": {
        "Navbar": {},
        "Header Section": "Select Icard template",
        "Feature Section": "Choose a template to replace with uploaded data"
    }
}`;
  treeData: any = null;
  rawInputText: string = `make a website , where we can login , sign up.
inside that there is a menu of icard where we can add a icard detail iacardname, description
after click this icard inside we upload excel of student data, icard template, after click convert it fetch all data of excel and replace the key value of icard template..`;
  id: number;

  constructor(private treeService: treeVisualizerService,
    private siteTreeService: SiteTreeservice,
    private route: ActivatedRoute,


  ) { }

  ngOnInit(): void {

    this.id = this.route.snapshot.params['id'];

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

    this.fetchTreeById(this.id);
  }

  openPopup() {
    this.showPopup = true;
  }

  convertJson() {
    try {
      const parsed = JSON.parse(this.inputJson);

      const keys = Object.keys(parsed);

      if (keys.length === 1) {
        // 🟢 Case 1: Only one root key (like: { "Login": { ... } })
        this.treeData = {
          title: keys[0],
          data: parsed[keys[0]]
        };
      } else {
        // 🔵 Case 2: Multiple root keys (like: { "Login": {...}, "Signup": {...}, ... })
        this.treeData = {
          title: 'App',
          data: {
            Children: parsed
          }
        };
      }

      console.log('✅ Final treeData:', this.treeData);
    } catch (e) {
      alert('❌ Invalid JSON format');
      console.error(e);
    }
  }

  // convertJson() {
  //   try {
  //     const parsed = JSON.parse(this.inputJson);
  //     const rootKey = Object.keys(parsed)[0];

  //     console.log(' root key  ', rootKey)
  //     this.treeData = {
  //       title: rootKey,
  //       data: parsed[rootKey]
  //     };

  //     console.log(' tree data ', this.treeData)
  //   } catch (e) {
  //     alert('Invalid JSON');
  //   }
  // }

  getSections(data: any): { title: string, description: string }[] {
    const sections: { title: string, description: string }[] = [];
    for (const key in data) {
      if (key !== 'Children' && typeof data[key] === 'string') {
        sections.push({ title: key, description: data[key] });
      }
      if (key !== 'Children' && Array.isArray(data[key])) {
        sections.push({ title: key, description: data[key].join('\n') });
      }
    }
    return sections;
  }

  getChildren(data: any): any[] {
    if (data.Children) {
      return Object.keys(data.Children).map((key) => ({
        title: key,
        data: data.Children[key]
      }));
    }
    return [];
  }

  generateJson() {
    console.log('genearte json start  ')

    const suffix1 = `
    🔁   You are a JSON structure generator for website page hierarchies. 
    You will return only a JSON object in a strictly hierarchical tree structure. Do not include any explanation, text, or markdown formatting like \`\`\`json — just return pure JSON only.
    Each page should be a key. For subpages like "Login", "Projects", or "New Project", nest them under a "Children" key of their parent page.
    Each page must include specific sections as keys (like "Navbar", "Header Section", "Feature Section" etc.) with either an empty object {} or a short description as the value.
    Do not return any explanation, text, or markdown formatting — only return the raw JSON object exactly in this format.
    
    ❌ Do not include:
    - Any explanation before or after the JSON
    - Any markdown formatting like \`\`\` or json
    - Any text like "Here is..." or "Please note..."
    
    ✅ Output must look like this:
    
    {
      "Home": {
        "Navbar": {},
        "Header Section": "Intro...",
        "Children": {
          "Login": {
            "Navbar": {},
            "Header Section": "Login form...",
            "Footer": {}
          }
        }
      }
    }`;


    const suffix = `You are a JSON structure generator for website page hierarchies.

You are a JSON structure generator for website UI and sitemap hierarchy.

Generate a strictly hierarchical JSON tree that represents the entire page flow of a website. The root of the tree must always be the "Home" page. All other pages (like Login, Sign Up, Projects, Dashboard, etc.) must be nested as subpages using a "Children" key under their logical parent based on the described user flow — not all pages should be flat or at root level.

Each page must include meaningful UI sections as keys — like "Navbar", "Header Section", "Feature Section", "Form Section", "Footer", etc.  
Each section must include a short and clear description of its purpose or content — to assist in frontend UI development.

Analyze the flow implied in the prompt:
- Pages that are accessed after some action (e.g., "after login", "inside a project", "upon click") must be nested as children.
- Reuse common sections like "Navbar" or "Footer" wherever needed.
- Pages like “Privacy Policy” or “Terms and Conditions” can remain at root or in Footer reference if needed.


✅ The following standard pages must always be included with detailed section-level breakdown:

- **Home**: General overview of the website, with call-to-action, features, testimonials, and a footer.
- **About**: Brief company history, mission/vision, and team member highlights.
- **Services**: List of services offered, with description, icons, or pricing cards.
- **Contact**: Contact form (name, email, message), business info, phone, map.
- **FAQ**: Accordion or expandable list of common questions and answers.
- **Blog**: List of articles or posts, with title, thumbnail, and excerpt.
- **Login**: Form section with input fields for email/username and password, login button, forgot password link.
- **Sign Up**: Form section with full name, email, password, confirm password, sign-up button.
- **Privacy Policy**: Legal text describing how user data is handled.
- **Terms and Conditions**: Legal text outlining site usage policies.

❌ Do not include:
- Any explanation before or after the JSON
- Any markdown formatting like \`\`\` or json
- Any natural language response
- Return only pure JSON — no explanation, no headings, no markdown formatting.
 

✅ Output JSON example structure should look like this:

{
  "Home": {
    "Navbar": "Top navigation with logo, links to all main pages, and call-to-action button",
    "Header Section": "Headline with subheading and call-to-action button",
    "Feature Section": "Three features highlighted with icons and descriptions",
    "Testimonial Section": "Customer reviews in carousel layout",
    "Footer": "Footer with navigation links, social icons, and legal page links",
    "Children": {
      "About": {
        "Header Section": "Intro about company mission and values",
        "Team Section": "Photos and bios of core team members"
      },
      "Services": {
        "Header Section": "List of core services offered",
        "Pricing Section": "Cards with service pricing and features"
      },
      "Contact": {
        "Header Section": "Contact form with name, email, and message fields",
        "Map Section": "Google Maps iframe showing location"
      },
      ...
    }
  },
  "Privacy Policy": {
    "Content Section": "Full legal description of data usage and user rights"
  },
  "Terms and Conditions": {
    "Content Section": "Rules and legal terms for using the site or service"
  }
}`;


    const payload = {
      query: this.rawInputText + suffix,
      conversationId: '677'
    };

    console.log(' query : ', payload.query)

    this.siteTreeService.generateJson(payload).subscribe({
      next: (res) => {

        console.log('response ', res)

        if (res && res.responseContent) {
          this.inputJson = res.responseContent;
          console.log('input json ', this.inputJson)


          // 🔁 Now call update API
          const updatePayload = {
            model: this.inputJson  // model format expected by backend
          };

          console.log('payload : ', updatePayload);
          this.siteTreeService.update(this.id, updatePayload).subscribe({
            next: (resp) => {
              console.log('✅ JSON updated on server:', resp);
            },
            error: (err) => {
              console.error('❌ Failed to update JSON on server:', err);
              alert('Update to server failed');
            }
          });
        }
      },
      error: (err) => {
        console.error('API Error:', err);
        alert('Failed to fetch JSON from API');
      }
    });
  }


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

        // Check if model key exists and has some value
        if (res && res.model) {
          try {
            // Optional: if model is already a stringified JSON
            const maybeParsed = typeof res.model === 'string' ? JSON.parse(res.model) : res.model;
            this.inputJson = JSON.stringify(maybeParsed, null, 2);
            this.convertJson(); // convert it immediately
          } 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');
      }
    });
  }


}