import DynamicAdCompoent from "@/app/[lang]/components/molecules/DynamicAdCompoent";

// Helper to extract group ID like "content:2" from "content:2.headingcontent"
export const getGroupId = (name: string) => name.split('.')[0];

// Group content blocks by their content:X group
export const groupContentBlocks = (blocks: any) => {
  const grouped: any = {};

  blocks.forEach((block: any) => {
    const groupId = getGroupId(block.name);
    if (!grouped[groupId]) grouped[groupId] = [];
    grouped[groupId].push(block);
  });

  return grouped;
};


export const getFinalHtmlBlocks = (groupedData: any) => {
    // Sort groups by the smallest `order` in each group
  const sortedGroups = Object.entries(groupedData).sort((a: any, b: any) => {
    const orderA = Math.min(...a[1].map((i: any) => i.order));
    const orderB = Math.min(...b[1].map((i: any) => i.order));
    return orderA - orderB;
  });

  let htmlContent: any = [];
  // Generate final HTML string
  const finalHtml = sortedGroups.map(([groupId, items]: any) => {
    const prefexSnippet = items.find((i: any) => i.name.includes('prefex-snippet'));
    const heading = items.find((i: any) => i.name.includes('headingcontent'));
    const contentBlocks = items
      .filter((i: any) => !i.name.includes('headingcontent') && !i.name.includes('prefex-snippet'))
      .sort((a: any, b: any) => a.order - b.order); 
    
    const order = items[0].order;
    
    const prefexAdData = JSON.parse(prefexSnippet?.data ?? '{}');
    const adData = prefexAdData?.localizedFields?.newAdsBlock ?? null;
    const pSnippet = adData ? <DynamicAdCompoent key={"AdsSlide-"+groupId} adsData={adData} type={prefexAdData?.snippetType} /> : <></>;

    if(!htmlContent[order])
      htmlContent[order] = [];

    if(prefexSnippet?.data){
      htmlContent[order].push({type: "ad", data: adData, adType: prefexAdData?.snippetType});
    }

    if(heading?.data){
      htmlContent[order].push({ type: "heading", data: heading?.data}); // <h1 className='heading1' key={"AdsSlide-heading-"+groupId} dangerouslySetInnerHTML={{__html: heading?.data }}></h1>);
    }

    if(contentBlocks.length > 0){
      htmlContent[order].push({ type: "content",  data:contentBlocks}); // <div className='text-content text-[28px]' key={"AdsSlide-content-"+groupId} dangerouslySetInnerHTML={{__html: [...contentBlocks].map((i: any) => i.data)}}></div>);
    }

    // console.log("Order Tracking: ", {order, prefexSnippet, heading, contentBlocks, htmlContent});

    return [
      pSnippet,
      heading?.data ? <h1 className='heading1' key={"AdsSlide-heading-"+groupId} dangerouslySetInnerHTML={{__html: heading?.data }}></h1>: <></>,
      contentBlocks.length > 0 ? <div className='text-content text-[28px]' key={"AdsSlide-content-"+groupId} dangerouslySetInnerHTML={{__html: [...contentBlocks].map((i: any) => i.data)}}></div> : <></>
    ];
  });

  const htmlArray: any = [];
  htmlContent.forEach((element: any) => {
    element.forEach((content: any, index: number) => {
      //console.log({content})
        if(content.type === "ad"){
          htmlArray.push(<DynamicAdCompoent key={"AdsSlide-"+index} adsData={content.data} type={content.adType} />);
        }

        if(content.type === "heading"){
          htmlArray.push(<h1 className='heading1' key={"AdsSlide-heading-"+index} dangerouslySetInnerHTML={{__html: content?.data }}></h1>);
        }

        if(content.type === "content"){
          htmlArray.push(<div className='text-content text-[28px]' key={"AdsSlide-content-"+index} dangerouslySetInnerHTML={{__html: [...content.data].map((i: any) => i.data)}}></div>);
        }
    })
    //console.log({element});
  });
  // console.log({htmlArray});
  // console.log({htmlContent, sortedGroups});
  return htmlArray;
  // .map((Group: any, gIndex: number) => {
  //   console.log({Group, gIndex});
  //   // return Group.data.map((contentGroup: any, groupIndex: number) => {
  //   //   console.log({contentGroup, groupIndex});
  //   //   if(contentGroup.type === "ad"){
  //   //     return <DynamicAdCompoent key={"AdsSlide-"+groupIndex} adsData={contentGroup.data} type={contentGroup.adType} />
  //   //   }
  
  //   //   if(contentGroup.type === "heading"){
  //   //     return <h1 className='heading1' key={"AdsSlide-heading-"+groupIndex} dangerouslySetInnerHTML={{__html: contentGroup?.data }}></h1>
  //   //   }
  
  //   //   if(contentGroup.type === "content"){
  //   //     return <div className='text-content text-[28px]' key={"AdsSlide-content-"+groupIndex} dangerouslySetInnerHTML={{__html: [...contentGroup.data].map((i: any) => i.data)}}></div>
  //   //   }
  //   // })
  // });
  return finalHtml;
}
