import React from "react";
import { joomlaService } from "@/services/joomlaService";
import { WritersCarousel } from "@/components/home/WritersCarousel";
import { HomeBlogTabs } from "@/components/home/HomeBlogTabs";
import { HowItWorksSection } from "@/components/home/HowItWorksSection";
import { HomeServicesSlider } from "@/components/home/HomeServicesSlider";
import { ServiceOrderForm } from "@/components/home/ServiceOrderForm";
import { HeroBannerCarousel } from "@/components/home/HeroBannerCarousel";
import { HeroMobileRatingStrip } from "@/components/home/HeroMobileRatingStrip";
import { CmsVideoLightboxHydrator } from "@/components/home/CmsVideoLightboxHydrator";
import { DeferredHomeCssLoader } from "@/components/home/DeferredHomeCssLoader";

export default async function HomePage() {
  // Fetch home page data dynamically from Joomla CMS API (Article ID 1 / alias=index)
  const [homeData, orderConfig, pricing] = await Promise.all([
    joomlaService.getHomePage(),
    joomlaService.getOrderServiceConfig(),
    joomlaService.getPricingConfig(),
  ]);
  const html = homeData.articleContentHtml || "";

  const WRITERS_TOKEN = "<!-- __WRITERS_CAROUSEL__ -->";
  const BLOG_TOKEN = "<!-- __BLOG_TABS__ -->";
  const HOW_IT_WORKS_TOKEN = "<!-- __HOW_IT_WORKS__ -->";
  const SERVICES_SLIDER_TOKEN = "<!-- __SERVICES_SLIDER__ -->";
  const CALCULATOR_TOKEN = "<!-- __HOME_CALCULATOR__ -->";

  const renderContent = (rawHtml: string): React.ReactNode => {
    if (!rawHtml) return null;

    if (rawHtml.includes(CALCULATOR_TOKEN)) {
      const parts = rawHtml.split(CALCULATOR_TOKEN);
      return (
        <React.Fragment>
          {renderContent(parts[0])}
          {/* Real `.slider-section` flex row: the live seasonal banner
              carousel (`heroBannerSlides`, real CMS markup — order banner,
              video, grammar-checker promo, order banner) sits beside the
              real calculator, exactly like `homenew.scss`'s `.slider-section`
              (banner 65% / side-bar ~32%, wrap on smaller screens) — not two
              separate blocks stacked on top of each other. */}
          <section className="container slider-section">
            {homeData.heroBannerSlides && homeData.heroBannerSlides.length > 0 && (
              <HeroBannerCarousel slides={homeData.heroBannerSlides} />
            )}
            <div className="w-full lg:hidden">
              <HeroMobileRatingStrip />
            </div>
            <ServiceOrderForm
              variant="home"
              config={homeData.hero.calculator}
              orderConfig={orderConfig}
              pricing={pricing}
              title="Professional Academic Help"
              subtitle="Buy Assignment Writing Help Online"
            />
          </section>
          {renderContent(parts[1])}
        </React.Fragment>
      );
    }

    if (rawHtml.includes(SERVICES_SLIDER_TOKEN)) {
      const parts = rawHtml.split(SERVICES_SLIDER_TOKEN);
      return (
        <React.Fragment>
          {renderContent(parts[0])}
          <HomeServicesSlider />
          {renderContent(parts[1])}
        </React.Fragment>
      );
    }

    if (rawHtml.includes(WRITERS_TOKEN)) {
      const parts = rawHtml.split(WRITERS_TOKEN);
      return (
        <React.Fragment>
          {renderContent(parts[0])}
          <WritersCarousel writers={homeData.writers} />
          {renderContent(parts[1])}
        </React.Fragment>
      );
    }

    if (rawHtml.includes(HOW_IT_WORKS_TOKEN)) {
      const parts = rawHtml.split(HOW_IT_WORKS_TOKEN);
      return (
        <React.Fragment>
          {renderContent(parts[0])}
          <HowItWorksSection />
          {renderContent(parts[1])}
        </React.Fragment>
      );
    }

    if (rawHtml.includes(BLOG_TOKEN)) {
      const parts = rawHtml.split(BLOG_TOKEN);
      return (
        <React.Fragment>
          {renderContent(parts[0])}
          <HomeBlogTabs
            recentPosts={homeData.blogData?.recent}
            mostViewedPosts={homeData.blogData?.mostViewed}
          />
          {renderContent(parts[1])}
        </React.Fragment>
      );
    }

    return (
      <div
        className="home-article-body"
        dangerouslySetInnerHTML={{ __html: rawHtml }}
      />
    );
  };

  return (
    <div className="home-cms-page w-full pb-16">
      {/* `home-page.css` (raw CSS copied from the live template, no Tailwind
          directives — confirmed safe to serve as a static file) styles the
          CMS-content sections below the fold (strips, "Avail the Best",
          video blocks, blog tabs, ...), not the hero banner itself — that's
          styled entirely with Tailwind utility classes in
          `HeroBannerCarousel.tsx`/`ServiceOrderForm.tsx`, already part of
          the always-blocking `globals.css`. A normal CSS `import` here made
          this ~18KB (compressed) file render-blocking for content that
          isn't even visible in the first viewport (confirmed via
          Lighthouse: flagged among the page's render-blocking requests).
          Classic non-blocking-CSS pattern instead: the `media="print"`
          trick keeps the stylesheet inert at first load (browsers only
          block rendering on stylesheets whose `media` matches the current
          context), flipped to `media="all"` once it's actually loaded —
          that flip is `DeferredHomeCssLoader`, a tiny client component
          (`useEffect`, not a raw inline `<script>`): a `<script>` rendered
          via JSX only executes when the browser parses it as part of the
          initial server-rendered HTML, not on a client-side navigation to
          `/` (confirmed — React's own dev console flagged a plain
          `<script>` version of this with "Scripts inside React components
          are never executed when rendering on the client"), so that first
          attempt silently never re-applied the stylesheet on an in-app
          navigation here. `useEffect` runs correctly either way.
          `<noscript>` covers the no-JS case. */}
      <link rel="preload" href="/css/home-page.css" as="style" />
      <link id="home-page-css" rel="stylesheet" href="/css/home-page.css" media="print" />
      <DeferredHomeCssLoader />
      <noscript>
        <link rel="stylesheet" href="/css/home-page.css" />
      </noscript>
      <CmsVideoLightboxHydrator />
      {html ? (
        <React.Fragment>
          {renderContent(html)}
          {!html.includes(WRITERS_TOKEN) && <WritersCarousel writers={homeData.writers} />}
          {!html.includes(HOW_IT_WORKS_TOKEN) && <HowItWorksSection />}
          {!html.includes(BLOG_TOKEN) && (
            <HomeBlogTabs
              recentPosts={homeData.blogData?.recent}
              mostViewedPosts={homeData.blogData?.mostViewed}
            />
          )}
        </React.Fragment>
      ) : (
        <div className="text-center py-20 text-slate-500">
          Loading Home Page content from Joomla CMS...
        </div>
      )}
    </div>
  );
}
