import xmlbuilder from 'xmlbuilder';
import { productSitemapXml } from './product-sitemap';
import { baseUrl, web_url } from '../constants/urls';
import { staticpageSitemapXml } from './staticpage-sitemap';
import { categoriesSitemapXml } from './categories-sitemap';
// import { categorySitemapXml } from './category-sitemap';
import * as CommonAPi from "../pages/api/common";
export async function indexSitemapXml() {
      const productsPage = await CommonAPi.getRequest(`${baseUrl}/api/generate-sitemap?type=products-list&page=1`).then((res)=>{
    
        return res?.data?.data?.last_page
})

const ITEMS_PER_BATCH = 10
const totalBatches = Math.ceil(productsPage / ITEMS_PER_BATCH);
  const xml = await staticpageSitemapXml();
  const xml1 = await productSitemapXml();
  const xml2 = await categoriesSitemapXml();
  function handleSitemapClick(element:any) {
    const loc = element.querySelector('loc').textContent;
    // Perform the desired action when a sitemap link is clicked, e.g., navigate to the specified URL
    window.location.href = loc;
  }
  const root = xmlbuilder.create('sitemapindex', { version: '1.0', encoding: 'UTF-8' })
    .att('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');

   

  // Add references to your individual sitemaps here
  root.ele('sitemap').ele('loc', `${web_url}/api/sitemap/staticpage`).up()
  // const linkElement = root.ele('link', `${web_url}/staticPage-sitemap.xml`);
  root.ele('sitemap').ele('loc', `${web_url}/api/sitemap/categories`).up()
  for (let index = 0; index < totalBatches; index++) {
    root.ele('sitemap').ele('loc', `${web_url}/api/sitemap/products/${index+1}`).up()
    
  }
  // const linkElement1 = root.ele('link', `${web_url}/categories-sitemap.xml`);
  // root.ele('sitemap').ele('loc', `${web_url}/api/sitemap/products1`).up()
  // root.ele('sitemap').ele('loc', `${web_url}/api/sitemap/products2`).up()
  // root.ele('sitemap').ele('loc', `${web_url}/api/sitemap/products3`).up()
  // root.ele('sitemap').ele('loc', `${web_url}/api/sitemap/products4`).up()
  // root.ele('sitemap').ele('loc', `${web_url}/api/sitemap/products5`).up()
  // const linkElement2 = root.ele('link', `${web_url}/products-sitemap.xml`);
  // root.ele('sitemap').ele('loc', 'https://indispare.com/products-sitemap.xml').up();
  
//   root.ele('sitemap').ele('loc', 'https://indispare.com/categories-sitemap.xml').up();

  return root.end({ pretty: true });
}
