import type { CalculatorConfig } from "@/types/home";
import type {
  BestDeal,
  JoomlaArticle,
  OrderServiceConfig,
  PricingConfig,
  WriterProfile,
} from "@/services/joomlaService";
import { joomlaService } from "@/services/joomlaService";
import type { NavigationResponse } from "@/types/navigation";
import { Breadcrumb } from "@/components/common/Breadcrumb";
import { ServiceSidebar } from "@/components/common/ServiceSidebar";
import { ServiceBanner } from "@/components/services/ServiceBanner";
import { ServiceBlogSection } from "@/components/services/ServiceBlogSection";
import { ServiceTestimonials } from "@/components/services/ServiceTestimonials";
import { renderArticleBody, splitArticleFaq } from "@/components/services/ArticleContentRenderer";
import { ALIAS_BANNER_TEXT, BANNER_SUPPRESSED_ALIASES, OUR_SERVICES_TITLE } from "@/components/services/serviceConstants";
import { findServiceBreadcrumbParent } from "@/lib/pageHelpers";

interface ServicePageViewProps {
  article: JoomlaArticle;
  navigationData: NavigationResponse;
  orderConfig: OrderServiceConfig[];
  bestDeals: BestDeal[];
  pricing: PricingConfig | null;
  calculatorConfig: CalculatorConfig;
  hasOurServicesBanner: boolean;
  cleanHtml: string;
  expertWriters: WriterProfile[];
  expertWriterImages: string[];
}

/**
 * The Services-page branch (banner + breadcrumb + body grid + blog
 * section), composed from its own child sections. This replicates
 * `service.php`'s real layout logic (see each derived flag's comment
 * below) — every piece here moved verbatim out of the former monolithic
 * `app/[...slug]/page.tsx` dispatcher.
 */
export async function ServicePageView({
  article,
  navigationData,
  orderConfig,
  bestDeals,
  pricing,
  calculatorConfig,
  hasOurServicesBanner,
  cleanHtml,
  expertWriters,
  expertWriterImages,
}: ServicePageViewProps) {
  const bannerHeading = hasOurServicesBanner ? OUR_SERVICES_TITLE : article.title;

  const isOldLayout = article.isServicePage && !hasOurServicesBanner && article.pageLayout === "Old";

  const showBlogSection =
    isOldLayout ||
    (article.pageLayout === "Country_page" && article.alias === "dissertation-writing-services") ||
    article.pageLayout === "pay_someone_page_design";

  const relatedServices = isOldLayout ? await joomlaService.getRelatedServices(article.id) : [];
  const serviceBlog = showBlogSection ? await joomlaService.getServiceBlogPosts(article.alias) : null;
  // `reviews_dynamic()` is called unconditionally in service.php, but
  // `$reviews_data` is only ever echoed in the branches already verified
  // here — `showBlogSection` (right after `.blog_section` closes) is the
  // one this app replicates; see `ServiceTestimonials`.
  const serviceReviews = showBlogSection ? await joomlaService.getServiceReviews(article.alias) : [];

  const aliasBannerText = ALIAS_BANNER_TEXT[article.alias];
  const bannerTitle = hasOurServicesBanner
    ? "Our Services"
    : article.bannerFormTitle || aliasBannerText?.title || "Professional Academic Help";
  const bannerSubtitle = hasOurServicesBanner
    ? ""
    : article.bannerFormSubtitle || aliasBannerText?.subtitle || "Buy Assignment Writing Help Online";

  const suppressBanner =
    article.isServicePage &&
    !hasOurServicesBanner &&
    (article.pageLayout === "Full_Page" || article.pageLayout === "Country_detail_page_new") &&
    BANNER_SUPPRESSED_ALIASES.has(article.alias);

  const { mainHtml, faqHtml } = hasOurServicesBanner
    ? { mainHtml: cleanHtml, faqHtml: null }
    : splitArticleFaq(cleanHtml);
  const mainArticleBody = renderArticleBody(mainHtml, { article, expertWriters, expertWriterImages });
  const faqArticleBody = faqHtml
    ? renderArticleBody(faqHtml, { article, expertWriters, expertWriterImages })
    : null;

  const breadcrumbParent = findServiceBreadcrumbParent(navigationData.header.mainNav, `/${article.alias}`);
  const breadcrumbItems = breadcrumbParent
    ? [{ label: breadcrumbParent.label, href: breadcrumbParent.href }, { label: article.title }]
    : [{ label: article.title }];

  return (
    <div className={`bg-slate-50 min-h-[60vh]${hasOurServicesBanner ? " our-services-page" : ""}`}>
      {/* Banner is a full-bleed section, with the order form sitting inside
          it beside the copy — matching the live `.banner_landing_pages`
          rule, whose gradient spans the whole section rather than boxing in
          just the left-hand column. Suppressed for the 3 aliases
          `suppressBanner` covers — see its comment. */}
      <ServiceBanner
        article={article}
        hasOurServicesBanner={hasOurServicesBanner}
        bannerHeading={bannerHeading}
        bannerTitle={bannerTitle}
        bannerSubtitle={bannerSubtitle}
        suppressBanner={suppressBanner}
        calculatorConfig={calculatorConfig}
        orderConfig={orderConfig}
        pricing={pricing}
      />

      {/* The live site puts the breadcrumb below the banner, not above it. Suppressed on our-services which has no breadcrumb. */}
      {!hasOurServicesBanner && <Breadcrumb items={breadcrumbItems} />}

      {/*
       * `service.php` only wraps the article in the two-column
       * `inner_services container` (`.left` body + `.right` `$rightbar`
       * sidebar) inside the `Old`-layout branch (the same
       * `if ($Page_layout_type == 'Old' && ...)` gate the blog_section
       * above uses). New/Full_Page/Country_page/etc. just echo
       * `$dynamic_form` (the banner already rendered above) + `$result`
       * (the raw body) — no `$rightbar`/sidebar at all. `/our-services`
       * isn't governed by service.php at all — it's rendered through the
       * generic `default.php` article template (confirmed: this article has
       * no `page-layout` custom field set), which computes
       * `$custom_rightbar_section` defensively but never actually echoes it
       * anywhere — only `echo $result;` (the plain article body). So this
       * page gets the `our_service_price_calculate_Form` banner (driven by
       * the token, not by being a real Service page) but never a sidebar.
       */}
      {isOldLayout ? (
        <div className="service-content-grid max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-8 pt-2 grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
          <div className="lg:col-span-8">{mainArticleBody}</div>

          {/* The live site's right sidebar (Best Deal promo, Paid FREE
              Features, Our Samples, free tools) never renders on mobile —
              it's a desktop-only module placement (`position: user6`),
              not just a collapsed/stacked version of itself. `hidden`
              below `lg` instead of just letting the grid stack it. */}
          <div className="hidden lg:block lg:col-span-4">
            <ServiceSidebar
              orderNowUrl={navigationData.header.cta.orderNowUrl}
              relatedServices={relatedServices}
              bestDeals={bestDeals}
              cartUrl={navigationData.header.cta.cartUrl}
              offersUrl="/offers"
              pricing={pricing}
              priceCountry={calculatorConfig.priceCountry}
            />
          </div>
        </div>
      ) : hasOurServicesBanner ? (
        <div className="our-services-page w-full">{mainArticleBody}</div>
      ) : (
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-8 pt-2">{mainArticleBody}</div>
      )}

      {/* FAQ section rendered outside the 2-column content+sidebar grid so it spans full-width across the page */}
      {!hasOurServicesBanner && faqArticleBody && (
        <div className="faq-section-container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-12">
          {faqArticleBody}
        </div>
      )}

      <ServiceBlogSection serviceBlog={serviceBlog} />

      {/* Real order from service.php: `<?= $reviews_data; ?>` sits right
          after `.blog_section` closes. */}
      <ServiceTestimonials reviews={serviceReviews} />
    </div>
  );
}
