import Link from "next/link";
import Image from "next/image";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { Footer } from "@/components/layout/Footer";
import { Navbar } from "@/components/layout/Navbar";
import { WhatsAppWidget } from "@/components/layout/WhatsAppWidget";
import { CaseStudyCard, IndustryCard, PartnerLogoGrid, SolutionCard } from "@/components/ui/Cards";
import { DetailHeroMedia } from "@/components/ui/DetailHeroMedia";
import { ProjectVisual } from "@/components/ui/ProjectVisual";
import { ArticleBody } from "@/components/ui/ArticleBody";
import { ContactForm } from "@/components/sections/ContactForm";
import { SuccessStoryFilter } from "@/components/sections/SuccessStoryFilter";
import { HomeHeroSlider } from "@/components/sections/HomeHeroSlider";
import { HomeOverviewBackground } from "@/components/sections/HomeOverviewBackground";
import { HomeProductShowcase } from "@/components/sections/HomeProductShowcase";
import { HomeSolutionsShowcase } from "@/components/sections/HomeSolutionsShowcase";
import { InsightBrowser } from "@/components/sections/InsightBrowser";
import { ProductCatalog } from "@/components/sections/ProductCatalog";
import { absoluteUrl, breadcrumbJsonLd, createMetadata, organizationJsonLd, websiteJsonLd } from "@/lib/seo";
import { getSectionSeo } from "@/lib/section-seo";
import { getPathForKind, localizedPath, parseSegments, type RouteKind } from "@/lib/routing";
import { getBlogPosts, getCaseStudies, getIndustries, getPartnerBrands, getProductCategories, getProducts, getSiteSettings, getSolutions } from "@/lib/content";
import type { BlogPost, CaseStudy, FileAsset, ImageAsset, Industry, Locale, PartnerBrand, Product, ProductCategory, SiteSettings, Solution } from "@/types/content";
import { LangAttribute } from "@/components/seo/LangAttribute";
import { getImageAlt, getImageUrl } from "@/lib/images";

type PageProps = {
  params: Promise<{ segments?: string[] }>;
};

export const revalidate = 10;

export async function generateStaticParams() {
  const base = [
    [],
    ["id"],
    ["about"],
    ["id", "about"],
    ["solutions"],
    ["id", "solutions"],
    ["products"],
    ["id", "products"],
    ["industries"],
    ["id", "industries"],
    ["success-stories"],
    ["id", "success-stories"],
    ["room-designer"],
    ["id", "room-designer"],
    ["talk-to-akarya"],
    ["id", "talk-to-akarya"],
    ["insights"],
    ["id", "insights"],
    ["privacy-policy"],
    ["id", "privacy-policy"]
  ];

  const [solutions, products, industries, caseStudies, blogPosts] = await Promise.all([
    getSolutions(),
    getProducts(),
    getIndustries(),
    getCaseStudies(),
    getBlogPosts()
  ]);

  const detail = [
    ...solutions.flatMap((item) => [
      ["solutions", item.slug],
      ["id", "solutions", item.slug]
    ]),
    ...products.flatMap((item) => [
      ["products", item.slug],
      ["id", "products", item.slug]
    ]),
    ...industries.flatMap((item) => [
      ["industries", item.slug],
      ["id", "industries", item.slug]
    ]),
    ...caseStudies.flatMap((item) => [
      ["success-stories", item.slug],
      ["id", "success-stories", item.slug]
    ]),
    ...blogPosts.flatMap((item) => [
      ["insights", item.slug],
      ["id", "insights", item.slug]
    ])
  ];

  return [...base, ...detail].map((segments) => ({ segments }));
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { locale, kind, slug } = parseSegments((await params).segments);
  const path = getPathForKind(kind, slug);
  const pageContent = await getPageContent();
  const seo = getSeoContent(pageContent, kind, locale, slug);
  return createMetadata({
    locale,
    settings: pageContent.siteSettings,
    path,
    title: seo.title,
    description: seo.description,
    image: getImageUrl(seo.image)
  });
}

export default async function Page({ params }: PageProps) {
  const route = parseSegments((await params).segments);
  const { locale, path } = route;
  const content = await getPageContent();
  const jsonLd: unknown[] = [organizationJsonLd(locale, content.siteSettings), websiteJsonLd(locale, content.siteSettings)];
  if (route.kind !== "home") {
    jsonLd.push(pageBreadcrumbJsonLd(locale, path));
  }

  const body = (() => {
    switch (route.kind) {
      case "home":
        return <HomePage locale={locale} content={content} />;
      case "about":
        return <AboutPage locale={locale} settings={content.siteSettings} />;
      case "solutions":
        return <SolutionsPage locale={locale} content={content} />;
      case "solution":
        return <SolutionDetailPage locale={locale} slug={route.slug} content={content} />;
      case "products":
        return <ProductsPage locale={locale} content={content} />;
      case "product":
        return <ProductDetailPage locale={locale} slug={route.slug} content={content} />;
      case "industries":
        return <IndustriesPage locale={locale} content={content} />;
      case "industry":
        return <IndustryDetailPage locale={locale} slug={route.slug} content={content} />;
      case "case-studies":
        return <CaseStudiesPage locale={locale} content={content} />;
      case "case-study":
        return <CaseStudyDetailPage locale={locale} slug={route.slug} content={content} />;
      case "room-designer":
        return <RoomDesignerPage locale={locale} settings={content.siteSettings} />;
      case "partners":
        return <PartnersPage locale={locale} content={content} />;
      case "resources":
        return <ResourcesPage locale={locale} />;
      case "contact":
        return <ContactPage locale={locale} content={content} />;
      case "insights":
        return <InsightsPage locale={locale} content={content} />;
      case "insight":
        return <InsightDetailPage locale={locale} slug={route.slug} content={content} />;
      case "privacy-policy":
        return <PrivacyPage locale={locale} />;
      default:
        notFound();
    }
  })();

  return (
    <>
      <LangAttribute locale={locale} />
      <Navbar locale={locale} path={path} solutions={content.solutions} products={content.products} />
      {body}
      <Footer locale={locale} settings={content.siteSettings} />
      <WhatsAppWidget locale={locale} whatsappNumber={content.siteSettings.whatsappNumber} />
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />
    </>
  );
}

type PageContent = {
  solutions: Solution[];
  products: Product[];
  productCategories: ProductCategory[];
  industries: Industry[];
  caseStudies: CaseStudy[];
  partnerBrands: PartnerBrand[];
  blogPosts: BlogPost[];
  siteSettings: SiteSettings;
};

async function getPageContent(): Promise<PageContent> {
  const [solutions, products, productCategories, industries, caseStudies, partnerBrands, blogPosts, siteSettings] = await Promise.all([
    getSolutions(),
    getProducts(),
    // New endpoint — tolerate a CMS that has not deployed it yet; ProductCatalog
    // falls back to the category reference embedded in each product.
    getProductCategories().catch(() => [] as ProductCategory[]),
    getIndustries(),
    getCaseStudies(),
    getPartnerBrands(),
    getBlogPosts(),
    getSiteSettings()
  ]);

  return { solutions, products, productCategories, industries, caseStudies, partnerBrands, blogPosts, siteSettings };
}

function getSeoContent(content: PageContent, kind: RouteKind, locale: Locale, slug?: string) {
  if (kind === "solution") {
    const item = content.solutions.find((solution) => solution.slug === slug);
    if (item) return { title: item.seoTitle[locale], description: item.seoDescription[locale], image: item.ogImage ?? item.heroImage };
  }
  if (kind === "product") {
    const item = content.products.find((product) => product.slug === slug);
    if (item) return { title: item.seoTitle[locale], description: item.seoDescription[locale], image: item.ogImage ?? item.heroImage };
  }
  if (kind === "industry") {
    const item = content.industries.find((industry) => industry.slug === slug);
    if (item) return { title: item.seoTitle[locale], description: item.seoDescription[locale], image: item.ogImage };
  }
  if (kind === "case-study") {
    const item = content.caseStudies.find((study) => study.slug === slug);
    if (item) return { title: item.seoTitle[locale], description: item.seoDescription[locale], image: item.ogImage ?? item.heroImage };
  }
  if (kind === "insight") {
    const item = content.blogPosts.find((post) => post.slug === slug);
    if (item) return { title: item.seoTitle[locale], description: item.seoDescription[locale], image: item.ogImage ?? item.coverImage };
  }

  // Listing + standalone section pages have no per-page CMS SEO record. Give
  // each one a distinct title/description instead of letting them all inherit
  // the single site-wide default. `home` intentionally keeps the CMS default.
  const section = getSectionSeo(kind, locale);
  return {
    title: section?.title,
    description: section?.description,
    image: undefined as ImageAsset | undefined
  };
}

function HomePage({ locale, content }: { locale: Locale; content: PageContent }) {
  const overview = content.siteSettings.homepageOverview;
  const overviewEyebrow = overview?.eyebrow?.[locale];
  const overviewTitle = overview?.title?.[locale];
  const overviewBody = overview?.body?.[locale];
  const overviewMetrics = overview?.metrics ?? [];
  const overviewMedia = (overview?.media ?? []).filter((item) =>
    item.mediaType === "video" ? Boolean(item.video?.url) : Boolean(getImageUrl(item.image))
  );
  const hasOverviewMedia = overviewMedia.length > 0;
  const hasOverviewContent = Boolean(overviewEyebrow || overviewTitle || overviewBody || overviewMetrics.length);
  const featured = content.caseStudies.filter((item) => item.featuredProject).slice(0, 3);
  const partnerLogos = content.partnerBrands
    .map((brand) => ({ name: brand.name, src: getImageUrl(brand.logo) }))
    .filter((brand): brand is { name: string; src: string } => Boolean(brand.src));
  const partnerLabel = locale === "id" ? "Brand teknologi dan platform yang kami gunakan" : "Technology brands and platforms we work with";

  return (
    <main>
      <HomeHeroSlider locale={locale} slides={content.siteSettings.homepageHeroSlides ?? []} />

      {hasOverviewContent ? (
        <section className={`section home-overview-section${hasOverviewMedia ? " has-media" : ""}`}>
          <div className="container intro-grid">
            <div>
              {overviewEyebrow ? <p className="eyebrow">{overviewEyebrow}</p> : null}
              {overviewTitle ? <h2>{overviewTitle}</h2> : null}
            </div>
            {overviewBody ? <p>{overviewBody}</p> : null}
            {overviewMetrics.length ? (
              <div className="stats what-we-do-stats" aria-label={locale === "id" ? "Statistik project" : "Project statistics"}>
                {overviewMetrics.map((stat) => (
                  <div key={stat.title[locale]}>
                    <strong>{stat.title[locale]}</strong>
                    <span>{stat.description[locale]}</span>
                  </div>
                ))}
              </div>
            ) : null}
          </div>
          {hasOverviewMedia ? <HomeOverviewBackground locale={locale} media={overviewMedia} /> : null}
        </section>
      ) : null}

      <section className="home-solutions-section">
        <HomeSolutionsShowcase locale={locale} solutions={content.solutions} showcase={content.siteSettings.homepageShowcase} />
      </section>

      <HomeProductShowcase locale={locale} products={content.siteSettings.homepageProducts} productItems={content.products} />

      {featured.length ? (
        <section className="section case-band">
          <div className="container">
            <p className="eyebrow">{locale === "id" ? "Success Stories Terpilih" : "Selected Success Stories"}</p>
            <h2>{locale === "id" ? "Project integrasi sistem AV & IT terpilih." : "Selected AV & IT system integration projects."}</h2>
            <p className="section-lead">
              {locale === "id"
                ? "Lihat bagaimana Akarya membantu klien mengubah kebutuhan teknis menjadi ruang andal yang siap dipakai setiap hari."
                : "Explore how Akarya helps clients turn technical requirements into reliable spaces that are ready for daily use."}
            </p>
            <div className="case-grid">
              {featured.map((study) => (
                <CaseStudyCard key={study.slug} item={study} locale={locale} />
              ))}
            </div>
          </div>
        </section>
      ) : null}

      <section className="section">
        <div className="container">
          <div className="cta-row">
            <div>
              <h2>{locale === "id" ? "Merencanakan project AV & IT?" : "Planning an AV & IT project?"}</h2>
              <p>
                {locale === "id"
                  ? "Ceritakan kebutuhan classroom, meeting room, LED display, signage, command center, atau immersive space Anda."
                  : "Talk to Akarya about your classroom, meeting room, LED display, signage, command center, or immersive space requirement."}
              </p>
            </div>
            <Link className="btn btn-primary" prefetch={false} href={localizedPath("/room-designer", locale)}>
              Room Designer
            </Link>
          </div>
          {partnerLogos.length ? (
            <div className="partner-strip">
              <p className="eyebrow hero-eyebrow">{partnerLabel}</p>
              <div className="partner-marquee" role="group" aria-label={partnerLabel}>
                <div className="partner-marquee-track">
                  {[...partnerLogos, ...partnerLogos].map((brand, index) => (
                    <div
                      className="brand-logo-card"
                      key={`${brand.name}-${index}`}
                      aria-hidden={index >= partnerLogos.length ? "true" : undefined}
                    >
                      <Image src={brand.src} alt={index >= partnerLogos.length ? "" : `${brand.name} logo`} width={160} height={64} />
                    </div>
                  ))}
                </div>
              </div>
            </div>
          ) : null}
        </div>
      </section>
    </main>
  );
}

function AboutPage({ locale, settings }: { locale: Locale; settings: SiteSettings }) {
  const companyProfileUrl = settings.companyProfileFile?.url;
  return (
    <main>
      <PageHero locale={locale} eyebrow="Akarya" title={locale === "id" ? "Partner integrasi teknologi untuk ruang yang harus bekerja andal." : "A technology integration partner for spaces that need to work reliably."} body={locale === "id" ? "Akarya membantu organisasi merancang, menerapkan, dan mensupport sistem AV dan IT dengan standar implementasi yang rapi dan mudah dikembangkan." : "Akarya helps organizations design, deploy, and support AV and IT systems with clean implementation standards and room to scale."} />
      <section className="section">
        <div className="container intro-grid">
          <div>
            <p className="eyebrow">{locale === "id" ? "Pendekatan" : "Approach"}</p>
            <h2>{locale === "id" ? "Design. Deploy. Manage." : "Design. Deploy. Manage."}</h2>
          </div>
          <p>{locale === "id" ? "Kami menggabungkan AV engineering, kesiapan IT, dokumentasi, dan support workflow agar ruang teknologi tidak hanya terlihat modern, tetapi juga konsisten dipakai setiap hari." : "We connect AV engineering, IT readiness, documentation, and support workflow so technology spaces do not just look modern, but remain dependable in daily operation."}</p>
        </div>
      </section>
      <section className="section-tight">
        <div className="container resource-cta">
          <div>
            <p className="eyebrow">About Akarya</p>
            <h2>Company Profile</h2>
            <p>Learn more about Akarya&apos;s background, capabilities, and selected AV &amp; IT project experience.</p>
          </div>
          {companyProfileUrl ? (
            <a className="btn btn-primary" href={companyProfileUrl} target="_blank" rel="noreferrer" download>
              {locale === "id" ? "Unduh Company Profile" : "Download Company Profile"}
            </a>
          ) : (
            <Link className="btn btn-primary" prefetch={false} href={localizedPath("/talk-to-akarya", locale)}>
              {locale === "id" ? "Minta Company Profile" : "Request Company Profile"}
            </Link>
          )}
        </div>
      </section>
    </main>
  );
}

function SolutionsPage({ locale, content }: { locale: Locale; content: PageContent }) {
  return (
    <ListingPage locale={locale} eyebrow={locale === "id" ? "Solusi" : "Solutions"} title={locale === "id" ? "Solusi AV & IT untuk ruang belajar, kerja, dan experience modern." : "AV & IT solutions for modern learning, working, and experience spaces."} body={locale === "id" ? "Dari desain ruang dan pemilihan produk hingga instalasi, commissioning, training, dan support jangka panjang." : "From room design and product selection to installation, commissioning, training, and long-term support."}>
      <div className="listing-grid">{content.solutions.map((item) => <SolutionCard key={item.slug} item={item} locale={locale} />)}</div>
    </ListingPage>
  );
}

function ProductsPage({ locale, content }: { locale: Locale; content: PageContent }) {
  const products = content.products;
  const featured = products[0];
  const featuredImage = getImageUrl(featured?.heroImage);

  return (
    <main className="products-page">
      <section className="products-catalog-hero">
        {featuredImage ? (
          <Image src={featuredImage} alt={featured.title[locale]} fill priority sizes="100vw" className="products-catalog-hero-image" />
        ) : null}
        <div className="products-catalog-hero-shade" />
        <div className="container products-catalog-hero-content">
          <p className="eyebrow hero-eyebrow">{locale === "id" ? "Produk" : "Product"}</p>
          <h1>{locale === "id" ? "Produk teknologi untuk ruang AV & IT yang siap dipakai." : "Technology products for AV & IT spaces that are ready to use."}</h1>
          <p>{locale === "id" ? "Pilih kategori produk untuk mendukung classroom, meeting room, signage, audio, network, server, compute, dan software." : "Choose product categories for classrooms, meeting rooms, signage, audio, networks, servers, compute, and software."}</p>
        </div>
      </section>

      <ProductCatalog locale={locale} products={products} categories={content.productCategories} />
    </main>
  );
}

function RoomDesignerPage({ locale, settings }: { locale: Locale; settings: SiteSettings }) {
  const page = settings.roomDesignerPage;
  const imageUrl = getImageUrl(page?.backgroundImage);
  const videoUrl = page?.backgroundVideo?.url;
  const useVideo = page?.backgroundType === "video" && Boolean(videoUrl);
  const ctaHref = page?.ctaHref || "/talk-to-akarya";
  const externalCta = /^https?:\/\//.test(ctaHref);

  return (
    <main className="room-designer-page" aria-label="Room Designer">
      <section className="room-designer-hero">
        <div className="room-designer-media" aria-hidden={useVideo ? "true" : undefined}>
          {useVideo ? (
            <video autoPlay muted loop playsInline preload="metadata" poster={imageUrl || undefined}>
              <source src={videoUrl} />
            </video>
          ) : imageUrl ? (
            <Image
              src={imageUrl}
              alt={typeof page?.backgroundImage === "object" ? page.backgroundImage.alt || page.title?.[locale] || "Akarya Room Designer" : page?.title?.[locale] || "Akarya Room Designer"}
              fill
              priority
              sizes="100vw"
            />
          ) : null}
        </div>
        <div className="room-designer-shade" />
        <div className="container room-designer-content">
          <p className="eyebrow room-designer-eyebrow">{page?.eyebrow?.[locale] || "Room Designer"}</p>
          <h1>{page?.title?.[locale] || "Designed by You.\nEngineered by Us."}</h1>
          {page?.description?.[locale] ? <p className="room-designer-description">{page.description[locale]}</p> : null}
          <Link
            className="room-designer-cta"
            prefetch={false}
            href={externalCta ? ctaHref : localizedPath(ctaHref, locale)}
            target={externalCta ? "_blank" : undefined}
            rel={externalCta ? "noreferrer" : undefined}
          >
            {page?.ctaLabel?.[locale] || "Design Now"}
            <span aria-hidden="true">→</span>
          </Link>
        </div>
      </section>
    </main>
  );
}

function IndustriesPage({ locale, content }: { locale: Locale; content: PageContent }) {
  return (
    <ListingPage locale={locale} eyebrow={locale === "id" ? "Industri" : "Industries"} title={locale === "id" ? "Dibangun untuk organisasi yang membutuhkan ruang teknologi andal." : "Built for organizations that need reliable technology spaces."} body={locale === "id" ? "Setiap industri memiliki kebutuhan ruang, workflow, dan risiko operasional yang berbeda." : "Every industry has different room needs, workflows, and operational risks."}>
      <div className="industries-grid">{content.industries.map((item) => <IndustryCard key={item.slug} item={item} locale={locale} />)}</div>
    </ListingPage>
  );
}

function CaseStudiesPage({ locale, content }: { locale: Locale; content: PageContent }) {
  return (
    <ListingPage locale={locale} eyebrow="Success Stories" title={locale === "id" ? "Project integrasi sistem AV & IT terpilih." : "Selected AV & IT system integration projects."} body={locale === "id" ? "Lihat bagaimana Akarya membantu klien mengubah kebutuhan teknis menjadi ruang andal yang siap dipakai setiap hari." : "Explore how Akarya helps clients turn technical requirements into reliable spaces that are ready for daily use."}>
      <SuccessStoryFilter items={content.caseStudies} locale={locale} />
    </ListingPage>
  );
}

function PartnersPage({ locale, content }: { locale: Locale; content: PageContent }) {
  return (
    <ListingPage locale={locale} eyebrow={locale === "id" ? "Partner" : "Partners"} title={locale === "id" ? "Ekosistem teknologi untuk sistem yang reliable." : "A technology ecosystem for reliable systems."} body={locale === "id" ? "Brand teknologi dipilih sesuai kebutuhan project, kompatibilitas sistem, dan support jangka panjang." : "Technology brands are selected around project needs, system compatibility, and long-term support."}>
      <PartnerLogoGrid items={content.partnerBrands} locale={locale} />
    </ListingPage>
  );
}

function ResourcesPage({ locale }: { locale: Locale }) {
  const resources = [
    ["Company Profile PDF", locale === "id" ? "Placeholder file: company-profile-akarya.pdf" : "Placeholder file: akarya-company-profile.pdf"],
    ["Portfolio Deck", locale === "id" ? "Placeholder deck untuk kunjungan sales dan follow-up WhatsApp." : "Placeholder deck for sales visits and WhatsApp follow-up."],
    ["Solution Sheet per Segment", "Education, Government & Public Sector, Corporate & Commercial, Hospitality"],
    ["Video Portfolio", locale === "id" ? "Placeholder video portfolio untuk QR code dan meeting presentation." : "Video portfolio placeholder for QR code and meeting presentation."],
    ["Customer Needs Checklist", locale === "id" ? "Checklist kebutuhan ruang, budget, timeline, dan next action." : "Checklist for room needs, budget, timeline, and next action."]
  ];

  return (
    <main>
      <PageHero
        locale={locale}
        eyebrow="Resources"
        title={locale === "id" ? "Sales resources untuk mempercepat diskusi project." : "Sales resources to make project discussions easier."}
        body={locale === "id" ? "Gunakan halaman ini sebagai digital showroom: company profile, portfolio, solution sheet, video placeholder, checklist kebutuhan, dan CTA WhatsApp." : "Use this page as a digital showroom: company profile, portfolio, solution sheets, video placeholders, needs checklist, and WhatsApp CTA."}
      />
      <section className="section">
        <div className="container resource-grid">
          {resources.map(([title, body]) => (
            <article className="card resource-card" key={title}>
              <p className="eyebrow">Resource</p>
              <h2>{title}</h2>
              <p>{body}</p>
              <Link prefetch={false} href={localizedPath("/talk-to-akarya", locale)}>{locale === "id" ? "Minta akses file" : "Request access"} →</Link>
            </article>
          ))}
        </div>
      </section>
      <CtaPanel locale={locale} title={locale === "id" ? "Butuh file untuk presentasi internal?" : "Need materials for an internal presentation?"} body={locale === "id" ? "Hubungi Akarya untuk company profile, portfolio deck, dan rekomendasi solusi sesuai sektor Anda." : "Talk to Akarya for a company profile, portfolio deck, and solution recommendation for your sector."} />
    </main>
  );
}

function ContactPage({ locale, content }: { locale: Locale; content: PageContent }) {
  return (
    <main>
      <PageHero locale={locale} eyebrow="Talk to Akarya" title="Talk to Akarya" body={locale === "id" ? "Ceritakan kebutuhan ruang atau solusi teknologi yang sedang Anda rencanakan. Tim Akarya akan membantu merekomendasikan langkah berikutnya." : "Tell us what kind of room or technology solution you are planning. Akarya will help recommend the right next step."} />
      <section className="section">
        <div className="container contact-layout">
          <div>
            <p className="eyebrow">PT Akarya Solusi Kreatif</p>
            <h2>{locale === "id" ? "Mulai dari kebutuhan ruang, bukan daftar alat." : "Start with the room need, not a device list."}</h2>
            <p>{locale === "id" ? "Kami akan membantu memetakan scope, risiko teknis, dan opsi solusi yang masuk akal untuk project Anda." : "We help map scope, technical risk, and practical solution options for your project."}</p>
          </div>
          <ContactForm locale={locale} whatsappNumber={content.siteSettings.whatsappNumber} />
        </div>
      </section>
    </main>
  );
}

function InsightsPage({ locale, content }: { locale: Locale; content: PageContent }) {
  return (
    <ListingPage locale={locale} eyebrow="Insights" title={locale === "id" ? "Catatan praktis untuk merencanakan sistem AV & IT." : "Practical notes for planning AV & IT systems."} body={locale === "id" ? "Panduan untuk smart classroom, meeting room, LED display, digital signage, command center, immersive room, dan AV system integration." : "Guides for smart classrooms, meeting rooms, LED displays, digital signage, command centers, immersive rooms, and AV system integration."}>
      <InsightBrowser posts={content.blogPosts} locale={locale} />
    </ListingPage>
  );
}

function ProductDetailPage({ locale, slug, content }: { locale: Locale; slug?: string; content: PageContent }) {
  const item = content.products.find((product) => product.slug === slug);
  if (!item) notFound();

  const relatedSolutions = content.solutions.filter((solution) => item.relatedSolutions?.includes(solution.slug)).slice(0, 6);
  const relatedCases = content.caseStudies.filter((study) => item.relatedCaseStudies?.includes(study.slug)).slice(0, 3);
  const faqs = item.faqs?.map((faq) => ({ question: faq.question[locale], answer: faq.answer[locale] })) ?? [];
  const allSections: Array<[string, string[]]> = [
    [locale === "id" ? "Fitur Utama" : "Key Features", item.keyFeatures?.[locale] ?? []],
    [locale === "id" ? "Cocok untuk" : "Suitable For", item.suitableFor?.[locale] ?? []],
    [locale === "id" ? "Manfaat" : "Benefits", item.benefits?.[locale] ?? []]
  ];
  const sections = allSections.filter(([, items]) => items.length);

  return (
    <SalesDetailPage
      locale={locale}
      eyebrow={item.category?.title?.[locale] || (locale === "id" ? "Produk" : "Product")}
      title={item.title[locale]}
      summary={item.fullDescription[locale] || item.shortDescription[locale]}
      image={item.heroImage}
      video={item.detailHeroVideo}
      mediaImages={item.detailHeroImages}
      sections={sections}
      relatedCases={relatedCases}
      relatedSolutions={relatedSolutions}
      faqs={faqs}
    />
  );
}

function SolutionDetailPage({ locale, slug, content }: { locale: Locale; slug?: string; content: PageContent }) {
  const item = content.solutions.find((solution) => solution.slug === slug);
  if (!item) notFound();
  const relatedCases = content.caseStudies.filter((study) => item.relatedCaseStudies?.includes(study.slug)).slice(0, 3);
  const faqs = item.faqs?.map((faq) => ({ question: faq.question[locale], answer: faq.answer[locale] })) ?? [];

  return (
    <SalesDetailPage
      locale={locale}
      eyebrow={item.eyebrow?.[locale] || (locale === "id" ? "Solusi" : "Solution")}
      title={item.title[locale]}
      summary={item.fullDescription[locale]}
      image={item.heroImage}
      video={item.detailHeroVideo}
      mediaImages={item.detailHeroImages}
      sections={[]}
      relatedCases={relatedCases}
      faqs={faqs}
    />
  );
}

function IndustryDetailPage({ locale, slug, content }: { locale: Locale; slug?: string; content: PageContent }) {
  const item = content.industries.find((industry) => industry.slug === slug);
  if (!item) notFound();
  const relatedSolutions = content.solutions.filter((solution) => item.relatedSolutions?.includes(solution.slug)).slice(0, 6);
  const relatedCases = content.caseStudies.filter((study) => item.relatedCaseStudies?.includes(study.slug)).slice(0, 3);
  const faqs = item.faqs?.map((faq) => ({ question: faq.question[locale], answer: faq.answer[locale] })) ?? [];
  const allSections: Array<[string, string[]]> = [
    ["Pain Points", item.painPoints?.[locale] ?? []],
    [locale === "id" ? "Solusi Relevan" : "Relevant Solutions", relatedSolutions.map((solution) => solution.title[locale])],
    [locale === "id" ? "Manfaat Utama" : "Key Benefits", item.keyBenefits?.[locale] ?? []]
  ];

  return (
    <SalesDetailPage
      locale={locale}
      eyebrow={locale === "id" ? "Industri" : "Industry"}
      title={item.title[locale]}
      summary={item.fullDescription[locale]}
      image={item.showcaseImage}
      video={item.detailHeroVideo}
      mediaImages={item.detailHeroImages}
      sections={allSections.filter(([, items]) => items.length)}
      relatedCases={relatedCases}
      relatedSolutions={relatedSolutions}
      faqs={faqs}
    />
  );
}

type FaqItem = { question: string; answer: string };

function SalesDetailPage({
  locale,
  eyebrow,
  title,
  summary,
  image,
  video,
  mediaImages,
  sections,
  relatedCases = [],
  relatedSolutions = [],
  faqs
}: {
  locale: Locale;
  eyebrow: string;
  title: string;
  summary: string;
  image?: ImageAsset;
  video?: FileAsset;
  mediaImages?: ImageAsset[];
  sections: Array<[string, string[]]>;
  relatedCases?: CaseStudy[];
  relatedSolutions?: Solution[];
  faqs: FaqItem[];
}) {
  const featureSections = sections.slice(0, 3);
  const supportingSections = sections.slice(3);
  const heroImages = mediaImages?.length ? mediaImages : image ? [image] : [];
  const sideImage = image ?? heroImages[0];
  const visualItems = relatedSolutions.length
    ? relatedSolutions.slice(0, 4).map((solution) => solution.title[locale])
    : sections
        .flatMap(([, items]) => items)
        .slice(0, 4);

  return (
    <main>
      <section className="detail-hero">
        <DetailHeroMedia video={video} images={heroImages} label={`${title} project media`} />
        <div className="container detail-hero-grid">
          <div className="detail-hero-content">
            <p className="eyebrow hero-eyebrow">{eyebrow}</p>
            <h1>{title}</h1>
            <p>{summary}</p>
            <div className="hero-actions">
              <Link className="btn btn-primary" prefetch={false} href={localizedPath("/talk-to-akarya", locale)}>
                Talk to Akarya
              </Link>
              <Link className="btn btn-secondary" prefetch={false} href={localizedPath("/success-stories", locale)}>
                {locale === "id" ? "View Success Stories" : "View Success Stories"}
              </Link>
            </div>
          </div>
        </div>
      </section>
      {featureSections.length || visualItems.length ? (
        <section className="section detail-experience-section">
          <div className="container detail-experience-grid">
            {featureSections.length ? (
              <div>
                <p className="eyebrow">{locale === "id" ? "Yang perlu dipahami" : "What to know"}</p>
                <h2>{locale === "id" ? "Lihat kebutuhan ruangnya secara lebih cepat." : "Scan the room need faster."}</h2>
                <p className="section-lead">
                  {locale === "id"
                    ? "Ringkasan masalah, solusi, komponen, dan manfaat dibuat lebih visual agar tim Anda lebih mudah memahami scope sebelum meeting."
                    : "Problems, solution scope, components, and benefits are grouped visually so your team can understand the scope before a meeting."}
                </p>
                <div className="detail-feature-grid">
                  {featureSections.map(([heading, items], index) => (
                    <section className="detail-feature-card card" key={heading}>
                      <span>{String(index + 1).padStart(2, "0")}</span>
                      <h3>{heading}</h3>
                      <ul>
                        {items.slice(0, 4).map((item) => (
                          <li key={item}>{item}</li>
                        ))}
                      </ul>
                    </section>
                  ))}
                </div>
              </div>
            ) : null}
            <aside className="detail-side-visual" aria-label={locale === "id" ? "Area solusi terkait" : "Related solution area"}>
              <ProjectVisual image={sideImage} label={`${title} visual reference`} className="detail-side-image" />
              {visualItems.length ? (
                <div className="detail-side-list">
                  <span>{locale === "id" ? "Ruang & sistem" : "Rooms & systems"}</span>
                  {visualItems.map((item) => (
                    <strong key={item}>{item}</strong>
                  ))}
                </div>
              ) : null}
            </aside>
          </div>
        </section>
      ) : null}
      {supportingSections.length ? (
        <section className="section detail-support-section">
          <div className="container detail-sections">
            {supportingSections.map(([heading, items]) => (
              <section className="detail-card card" key={heading}>
                <h2>{heading}</h2>
                <ul>
                  {items.map((item) => (
                    <li key={item}>{item}</li>
                  ))}
                </ul>
              </section>
            ))}
          </div>
        </section>
      ) : null}
      {relatedSolutions.length ? (
        <section className="section case-band">
          <div className="container">
            <p className="eyebrow">{locale === "id" ? "Solusi Terkait" : "Related Solutions"}</p>
            <div className="solutions-grid">
              {relatedSolutions.map((solution) => (
                <SolutionCard key={solution.slug} item={solution} locale={locale} />
              ))}
            </div>
          </div>
        </section>
      ) : null}
      {relatedCases.length ? (
        <section className="section case-band">
          <div className="container">
            <p className="eyebrow">{locale === "id" ? "Success Stories Terkait" : "Related Success Stories"}</p>
            <div className="case-grid">
              {relatedCases.map((study) => (
                <CaseStudyCard key={study.slug} item={study} locale={locale} />
              ))}
            </div>
          </div>
        </section>
      ) : null}
      {faqs.length ? <FaqSection faqs={faqs} /> : null}
      <CtaPanel locale={locale} />
      {faqs.length ? (
        <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(faqJsonLd(faqs)) }} />
      ) : null}
    </main>
  );
}

function CaseStudyDetailPage({ locale, slug, content }: { locale: Locale; slug?: string; content: PageContent }) {
  const item = content.caseStudies.find((study) => study.slug === slug);
  if (!item) notFound();
  const storyVisuals = item.galleryImages?.length ? item.galleryImages.slice(0, 3) : [item.heroImage, undefined, undefined];
  const crumbs = breadcrumbJsonLd([
    { name: "Home", url: absoluteUrl("/", locale) },
    { name: "Success Stories", url: absoluteUrl("/success-stories", locale) },
    { name: item.title[locale], url: absoluteUrl(`/success-stories/${item.slug}`, locale) }
  ]);

  return (
    <main>
      <section className="detail-hero">
        <div className="container detail-hero-grid">
          <div>
            <Link className="eyebrow hero-eyebrow" prefetch={false} href={localizedPath("/success-stories", locale)}>
              ← Success Stories
            </Link>
            <p className="eyebrow hero-eyebrow">{`${item.industry} · ${item.location} · ${item.year}`}</p>
            <h1>{item.title[locale]}</h1>
            <p>{item.shortSummary[locale]}</p>
          </div>
          <ProjectVisual image={item.heroImage} label={item.title[locale]} />
        </div>
      </section>
      <section className="story-showcase">
        <div className="container">
          <div className="story-media-grid">
            {storyVisuals.map((image, index) => (
              <ProjectVisual key={index} image={image} label={`${item.title[locale]} project visual ${index + 1}`} />
            ))}
          </div>
        </div>
      </section>
      <section className="section story-section">
        <div className="container story-layout">
          <article className="story-article">
            {item.body?.length ? (
              <ArticleBody blocks={item.body} locale={locale} />
            ) : (
              <StorySection title={locale === "id" ? "Ringkasan" : "Overview"} body={item.shortSummary[locale]} />
            )}
          </article>
          <aside className="story-info-panel" aria-label={locale === "id" ? "Informasi project" : "Project information"}>
            <h2>More Info</h2>
            <Meta label="Sector" value={item.industry} />
            <Meta label="Client" value={item.clientName} />
            <Meta label="Location" value={item.location} />
            <Meta label="Year" value={item.year} />
            <Meta label="Project" value={item.projectCategory} />
            <Meta label="Products" value={item.productsOrTechnologiesUsed.join(", ")} />
            {item.partnerBrands.length ? <Meta label="Partner" value={item.partnerBrands.join(", ")} /> : null}
            {item.portfolioFile?.url ? (
              <a className="btn btn-primary story-download" href={item.portfolioFile.url} target="_blank" rel="noreferrer">
                {locale === "id" ? "Download Portfolio Project" : "Download Project Portfolio"}
              </a>
            ) : null}
          </aside>
        </div>
      </section>
      {item.galleryImages?.length && item.galleryImages.length > 3 ? (
        <section className="section story-extra-gallery">
          <div className="container">
            <div className="story-gallery-header">
              <p className="eyebrow">Gallery</p>
              <h2>{locale === "id" ? "Galeri Project" : "Project Gallery"}</h2>
            </div>
            <div className="gallery-grid">
              {item.galleryImages.slice(3).map((image, index) => (
                <ProjectVisual key={index} image={image} label={`${item.title[locale]} gallery ${index + 4}`} />
              ))}
            </div>
          </div>
        </section>
      ) : null}
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(crumbs) }} />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify({
            "@context": "https://schema.org",
            "@type": ["CreativeWork", "Project"],
            name: item.title[locale],
            description: item.shortSummary[locale],
            datePublished: item.publishedAt,
            locationCreated: item.location,
            about: item.projectCategory
          })
        }}
      />
      <CtaPanel locale={locale} compact />
    </main>
  );
}

function StorySection({ title, body }: { title: string; body: string }) {
  return (
    <section className="story-section-block">
      <h2>{title}</h2>
      <p>{body}</p>
    </section>
  );
}

function InsightDetailPage({ locale, slug, content }: { locale: Locale; slug?: string; content: PageContent }) {
  const item = content.blogPosts.find((post) => post.slug === slug);
  if (!item) notFound();
  return (
    <main>
      <PageHero locale={locale} eyebrow="Insight" title={item.title[locale]} body={item.excerpt[locale]} image={item.coverImage} />
      <article className="section container">
        {item.body?.length ? (
          <ArticleBody blocks={item.body} locale={locale} />
        ) : (
          <p style={{ maxWidth: 760, color: "var(--copy)", fontSize: "1.2rem", lineHeight: 1.7 }}>{item.content?.[locale]}</p>
        )}
      </article>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify({
            "@context": "https://schema.org",
            "@type": "BlogPosting",
            headline: item.title[locale],
            description: item.excerpt[locale],
            author: { "@type": "Organization", name: item.author },
            datePublished: item.publishedAt
          })
        }}
      />
    </main>
  );
}

function PrivacyPage({ locale }: { locale: Locale }) {
  return (
    <main>
      <PageHero locale={locale} eyebrow="Privacy" title={locale === "id" ? "Kebijakan Privasi" : "Privacy Policy"} body={locale === "id" ? "Kebijakan dasar terkait data yang dikirim melalui website Akarya." : "Basic policy for data submitted through the Akarya website."} />
      <section className="section container">
        <div style={{ maxWidth: 820 }}>
          <h2>{locale === "id" ? "Data yang kami terima" : "Data we receive"}</h2>
          <p>{locale === "id" ? "Kami dapat menerima nama, perusahaan, email, nomor WhatsApp, kebutuhan solusi, dan pesan yang Anda kirim melalui form Talk to Akarya." : "We may receive name, company, email, WhatsApp number, solution need, and message submitted through the Talk to Akarya form."}</p>
          <h2>{locale === "id" ? "Penggunaan data" : "How we use data"}</h2>
          <p>{locale === "id" ? "Data digunakan untuk menindaklanjuti inquiry, konsultasi project, dan komunikasi terkait kebutuhan layanan." : "Data is used to follow up inquiries, project consultation, and communication related to service needs."}</p>
        </div>
      </section>
    </main>
  );
}

function ListingPage({ locale, eyebrow, title, body, children }: { locale: Locale; eyebrow: string; title: string; body: string; children: React.ReactNode }) {
  return (
    <main>
      <PageHero locale={locale} eyebrow={eyebrow} title={title} body={body} />
      <section className="section">
        <div className="container">{children}</div>
      </section>
    </main>
  );
}

function PageHero({
  eyebrow,
  title,
  body,
  image
}: {
  locale: Locale;
  eyebrow: string;
  title: string;
  body: string;
  image?: ImageAsset;
}) {
  const imageUrl = getImageUrl(image);
  return (
    <section className={`page-hero${imageUrl ? " page-hero-media" : ""}`}>
      {imageUrl ? (
        <>
          <Image className="page-hero-image" src={imageUrl} alt={getImageAlt(image, title)} fill priority sizes="100vw" />
          <div className="page-hero-shade" />
        </>
      ) : null}
      <div className="container">
        <p className="eyebrow hero-eyebrow">{eyebrow}</p>
        <h1>{title}</h1>
        <p>{body}</p>
      </div>
    </section>
  );
}

function Meta({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <span>{label}</span>
      <strong>{value}</strong>
    </div>
  );
}

function pageBreadcrumbJsonLd(locale: Locale, path: string) {
  const cleanPath = path.replace(/^\/id(?=\/|$)/, "") || "/";
  const parts = cleanPath.split("/").filter(Boolean);
  const items = [
    { name: "Home", url: absoluteUrl("/", locale) },
    ...parts.map((part, index) => {
      const href = `/${parts.slice(0, index + 1).join("/")}`;
      return {
        name: part
          .split("-")
          .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
          .join(" "),
        url: absoluteUrl(href, locale)
      };
    })
  ];

  return breadcrumbJsonLd(items);
}

function FaqSection({ faqs }: { faqs: FaqItem[] }) {
  return (
    <section className="section">
      <div className="container">
        <p className="eyebrow">FAQ</p>
        <div className="faq-grid">
          {faqs.map((faq) => (
            <article className="card faq-card" key={faq.question}>
              <h2>{faq.question}</h2>
              <p>{faq.answer}</p>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function CtaPanel({
  locale,
  title,
  body,
  compact = false
}: {
  locale: Locale;
  title?: string;
  body?: string;
  compact?: boolean;
}) {
  return (
    <section className={`section-tight cta-panel${compact ? " compact" : ""}`}>
      <div className="container cta-row">
        <div>
          <h2>{title ?? (locale === "id" ? "Siap membahas kebutuhan ruang Anda?" : "Ready to discuss your project needs?")}</h2>
          <p>{body ?? (locale === "id" ? "Ceritakan kebutuhan ruang atau solusi teknologi yang sedang Anda rencanakan. Tim Akarya akan membantu merekomendasikan langkah berikutnya." : "Tell us what kind of room or technology solution you are planning. Akarya will help recommend the right next step.")}</p>
        </div>
        <div className="hero-actions">
          <Link className="btn btn-primary" prefetch={false} href={localizedPath("/talk-to-akarya", locale)}>
            Talk to Akarya
          </Link>
          <Link className="btn btn-secondary" prefetch={false} href={localizedPath("/success-stories", locale)}>
            {locale === "id" ? "Lihat Success Stories" : "View Success Stories"}
          </Link>
        </div>
      </div>
    </section>
  );
}

function faqJsonLd(faqs: FaqItem[]) {
  return {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: faqs.map((faq) => ({
      "@type": "Question",
      name: faq.question,
      acceptedAnswer: {
        "@type": "Answer",
        text: faq.answer
      }
    }))
  };
}
