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 { ContactForm } from "@/components/sections/ContactForm";
import { SuccessStoryFilter } from "@/components/sections/SuccessStoryFilter";
import { HomeHeroSlider } from "@/components/sections/HomeHeroSlider";
import { HomeProductShowcase } from "@/components/sections/HomeProductShowcase";
import { HomeSolutionsShowcase } from "@/components/sections/HomeSolutionsShowcase";
import { InsightBrowser } from "@/components/sections/InsightBrowser";
import { ProductCatalogBrowser } from "@/components/sections/ProductCatalogBrowser";
import { breadcrumbJsonLd, createMetadata, organizationJsonLd, siteUrl, websiteJsonLd } from "@/lib/seo";
import { getPathForKind, localizedPath, parseSegments } from "@/lib/routing";
import { getBlogPosts, getCaseStudies, getIndustries, getPartnerBrands, getProducts, getSiteSettings, getSolutions } from "@/lib/content";
import type { BlogPost, CaseStudy, FileAsset, ImageAsset, Industry, Locale, PartnerBrand, Product, SiteSettings, Solution } from "@/types/content";
import { LangAttribute } from "@/components/seo/LangAttribute";
import { 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[];
  industries: Industry[];
  caseStudies: CaseStudy[];
  partnerBrands: PartnerBrand[];
  blogPosts: BlogPost[];
  siteSettings: SiteSettings;
};

const homePartnerLogos = [
  { name: "MAXHUB", src: "/logos/maxhub.svg" },
  { name: "Epson", src: "/logos/epson.svg" },
  { name: "Philips", src: "/logos/philips.svg" },
  { name: "Qiangli", src: "/logos/qiangli.svg" },
  { name: "Novastar", src: "/logos/novastar.svg" },
  { name: "Biamp", src: "/logos/biamp.svg" },
  { name: "JBL", src: "/logos/jbl.svg" },
  { name: "Shure", src: "/logos/shure.svg" },
  { name: "Yamaha", src: "/logos/yamaha.svg" }
];

const storyIndustryFilters = [
  { slug: "education", label: "Education" },
  { slug: "enterprise", label: "Enterprise" },
  { slug: "government-public-sector", label: "Government & Public Sector" },
  { slug: "hospitality-commercial", label: "Hospitality & Commercial" }
] as const;

function getStoryIndustrySlug(item: CaseStudy) {
  const industry = item.industry.toLowerCase();
  const category = item.projectCategory.toLowerCase();
  if (industry.includes("education") || industry.includes("museum") || category.includes("classroom")) return "education";
  if (industry.includes("government") || industry.includes("public sector") || category.includes("ifp")) return "government-public-sector";
  if (industry.includes("hospitality") || industry.includes("public experience") || category.includes("immersive")) return "hospitality-commercial";
  return "enterprise";
}

function getStoryIndustryLabel(item: CaseStudy) {
  const slug = getStoryIndustrySlug(item);
  return storyIndustryFilters.find((filter) => filter.slug === slug)?.label ?? "Enterprise";
}

async function getPageContent(): Promise<PageContent> {
  const [solutions, products, industries, caseStudies, partnerBrands, blogPosts, siteSettings] = await Promise.all([
    getSolutions(),
    getProducts(),
    getIndustries(),
    getCaseStudies(),
    getPartnerBrands(),
    getBlogPosts(),
    getSiteSettings()
  ]);

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

function getSeoContent(content: PageContent, kind: string, 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 };
  }

  const labels = {
    home: {
      en: [
        "Akarya | AV & IT System Integrator for Smart Classroom, LED Display & Immersive Space",
        "Akarya designs, installs, and supports reliable AV & IT systems for education, enterprise, government, and commercial spaces - from smart classrooms and meeting rooms to LED displays, digital signage, command centers, and immersive spaces."
      ],
      id: [
        "Akarya | System Integrator AV & IT Indonesia",
        "Akarya merancang, memasang, dan mendukung sistem AV & IT yang andal untuk pendidikan, enterprise, pemerintah, dan ruang komersial - mulai dari smart classroom, meeting room, LED display, digital signage, command center, hingga immersive space."
      ]
    },
    about: {
      en: ["About Akarya | AV & IT System Integrator", "Learn how Akarya designs, deploys, and supports enterprise-grade AV and IT systems."],
      id: ["Tentang Akarya | System Integrator AV & IT", "Pelajari bagaimana Akarya merancang, menerapkan, dan mensupport sistem AV dan IT enterprise-grade."]
    },
    solutions: {
      en: ["AV & IT Solutions | Akarya", "Explore Akarya solutions for classrooms, meeting rooms, LED display, signage, command center, and immersive spaces."],
      id: ["Solusi AV & IT | Akarya", "Jelajahi solusi Akarya untuk classroom, meeting room, LED display, signage, command center, dan immersive space."]
    },
    products: {
      en: ["Product | Akarya", "Explore Akarya technology product categories for classrooms, meeting rooms, displays, networks, audio, servers, and workspaces."],
      id: ["Produk | Akarya", "Jelajahi kategori produk teknologi Akarya untuk classroom, meeting room, display, network, audio, server, dan workspace."]
    },
    industries: {
      en: ["Industries | Akarya", "AV and IT integration for education, workplace, government, hospitality, museum, and control room environments."],
      id: ["Industri | Akarya", "Integrasi AV dan IT untuk edukasi, workplace, pemerintahan, hospitality, museum, dan control room."]
    },
    "case-studies": {
      en: ["Success Stories | Akarya", "Selected AV and IT project success stories from real client environments."],
      id: ["Success Stories | Akarya", "Success stories project integrasi sistem AV dan IT dari lingkungan customer nyata."]
    },
    "room-designer": {
      en: ["Room Designer | Akarya", "Akarya room designer tool for planning AV and IT spaces."],
      id: ["Room Designer | Akarya", "Room designer Akarya untuk perencanaan ruang AV dan IT."]
    },
    partners: {
      en: ["Technology Brands & Partners | Akarya", "Technology ecosystem supporting Akarya AV and IT system integration projects."],
      id: ["Brand Teknologi & Partner | Akarya", "Ekosistem teknologi yang mendukung project integrasi sistem AV dan IT Akarya."]
    },
    resources: {
      en: ["Resources | Akarya Sales & Project Planning Hub", "Download Akarya company profile, portfolio deck, solution sheets, project checklist, and video portfolio placeholders."],
      id: ["Resources | Akarya Sales & Project Planning Hub", "Akses company profile Akarya, portfolio deck, solution sheet, checklist kebutuhan project, dan placeholder video portfolio."]
    },
    contact: {
      en: ["Talk to Akarya | AV & IT Consultation", "Talk to Akarya for AV and IT system integration consultation in Indonesia."],
      id: ["Talk to Akarya | Konsultasi AV & IT", "Talk to Akarya untuk konsultasi integrasi sistem AV dan IT di Indonesia."]
    },
    insights: {
      en: ["Insights | Akarya", "Practical insights for planning AV, IT, meeting room, classroom, and display systems."],
      id: ["Insights | Akarya", "Insight praktis untuk merencanakan sistem AV, IT, meeting room, classroom, dan display."]
    },
    "privacy-policy": {
      en: ["Privacy Policy | Akarya", "Basic privacy policy for Akarya website visitors and inquiries."],
      id: ["Kebijakan Privasi | Akarya", "Kebijakan privasi dasar untuk pengunjung website dan inquiry Akarya."]
    }
  } as const;

  const fallback = labels[kind as keyof typeof labels]?.[locale] ?? labels.home[locale];
  return { title: fallback[0], description: fallback[1], image: undefined as ImageAsset | undefined };
}

function HomePage({ locale, content }: { locale: Locale; content: PageContent }) {
  const copy = locale === "id" ? homeCopy.id : homeCopy.en;
  const overview = content.siteSettings.homepageOverview;
  const overviewEyebrow = overview?.eyebrow?.[locale] || copy.whatWeDo;
  const overviewTitle = overview?.title?.[locale] || copy.introTitle;
  const overviewBody = overview?.body?.[locale] || copy.introBody;
  const overviewMetrics = overview?.metrics?.length ? overview.metrics : copy.stats.map((stat) => ({ title: { en: stat.title, id: stat.title }, description: { en: stat.description, id: stat.description } }));
  const featured = content.caseStudies.filter((item) => item.featuredProject).slice(0, 3);

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

      <section className="section home-overview-section">
        <div className="container intro-grid">
          <div>
            <p className="eyebrow">{overviewEyebrow}</p>
            <h2>{overviewTitle}</h2>
          </div>
          <p>{overviewBody}</p>
          <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>
        </div>
      </section>

      <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} />

      <section className="section case-band">
        <div className="container">
          <p className="eyebrow">{copy.caseEyebrow}</p>
          <h2>{copy.caseTitle}</h2>
          <p className="section-lead">{copy.caseBody}</p>
          <div className="case-grid">
            {featured.map((study) => (
              <CaseStudyCard key={study.slug} item={study} locale={locale} />
            ))}
          </div>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <div className="cta-row">
            <div>
              <h2>{copy.cta}</h2>
              <p>{copy.ctaBody}</p>
            </div>
            <Link className="btn btn-primary" prefetch={false} href={localizedPath("/talk-to-akarya", locale)}>
              {copy.ctaButton}
            </Link>
          </div>
          <div className="partner-strip">
            <p className="eyebrow hero-eyebrow">{copy.partnerLabel}</p>
            <div className="partner-marquee" role="group" aria-label={copy.partnerLabel}>
              <div className="partner-marquee-track">
                {[...homePartnerLogos, ...homePartnerLogos].map((brand, index) => (
                  <div
                    className="brand-logo-card"
                    key={`${brand.name}-${index}`}
                    aria-hidden={index >= homePartnerLogos.length ? "true" : undefined}
                  >
                    <Image src={brand.src} alt={index >= homePartnerLogos.length ? "" : `${brand.name} logo`} width={160} height={64} />
                  </div>
                ))}
              </div>
            </div>
          </div>
        </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>

      <ProductCatalogBrowser locale={locale} products={products} />
    </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?.length ? item.faqs.map((faq) => ({ question: faq.question[locale], answer: faq.answer[locale] })) : getProductFallbackFaqs(item, 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?.[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 detail = getSolutionEnablement(item.slug, locale);
  const relatedCases = content.caseStudies.filter((study) => item.relatedCaseStudies?.includes(study.slug)).slice(0, 3);

  return (
    <SalesDetailPage
      locale={locale}
      eyebrow={locale === "id" ? "Solusi" : "Solution"}
      title={item.title[locale]}
      summary={item.fullDescription[locale]}
      image={item.heroImage}
      video={item.detailHeroVideo}
      mediaImages={item.detailHeroImages}
      sections={[
        [locale === "id" ? "Masalah Umum Customer" : "Common Customer Problems", detail.problems],
        [locale === "id" ? "Solusi Akarya" : "Akarya Solution", [item.fullDescription[locale], detail.akaryaSolution]],
        [locale === "id" ? "Komponen Sistem" : "System Components", detail.components],
        [locale === "id" ? "Cocok untuk" : "Suitable For", detail.suitableFor],
        [locale === "id" ? "Manfaat" : "Benefits", detail.benefits]
      ]}
      relatedCases={relatedCases}
      faqs={detail.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 detail = getIndustryEnablement(item, locale);

  return (
    <SalesDetailPage
      locale={locale}
      eyebrow={locale === "id" ? "Industri" : "Industry"}
      title={detail.h1}
      summary={item.fullDescription[locale]}
      image={item.showcaseImage}
      video={item.detailHeroVideo}
      mediaImages={item.detailHeroImages}
      sections={[
        [locale === "id" ? "Pain Points" : "Pain Points", detail.painPoints],
        [locale === "id" ? "Solusi Relevan" : "Relevant Solutions", relatedSolutions.map((solution) => solution.title[locale])],
        [locale === "id" ? "Manfaat Utama" : "Key Benefits", detail.benefits]
      ]}
      relatedCases={relatedCases}
      relatedSolutions={relatedSolutions}
      faqs={detail.faqs}
    />
  );
}

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

function getProductFallbackFaqs(item: Product, locale: Locale): FaqItem[] {
  const title = item.title[locale];
  return [
    {
      question:
        locale === "id"
          ? `Apakah ${title} bisa disesuaikan dengan kebutuhan ruang?`
          : `Can ${title} be matched to a room requirement?`,
      answer:
        locale === "id"
          ? "Bisa. Akarya akan menyesuaikan rekomendasi produk dengan ukuran ruang, kebutuhan user, workflow, budget, dan rencana support."
          : "Yes. Akarya matches the product recommendation to room size, user needs, workflow, budget, and support planning."
    },
    {
      question: locale === "id" ? "Apakah Akarya membantu instalasi dan training?" : "Can Akarya support installation and training?",
      answer:
        locale === "id"
          ? "Ya. Akarya dapat membantu dari desain sistem, procurement, instalasi, commissioning, training user, sampai after-sales support."
          : "Yes. Akarya can support system design, procurement, installation, commissioning, user training, and after-sales support."
    }
  ];
}

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>
      <section className="section detail-experience-section">
        <div className="container detail-experience-grid">
          <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>
          <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" />
            <div className="detail-side-list">
              <span>{locale === "id" ? "Ruang & sistem" : "Rooms & systems"}</span>
              {visualItems.map((item) => (
                <strong key={item}>{item}</strong>
              ))}
            </div>
          </aside>
        </div>
      </section>
      {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}
      <FaqSection faqs={faqs} />
      <CtaPanel locale={locale} />
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(faqJsonLd(faqs)) }} />
    </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 benefits = item.benefits?.[locale] ?? [
    locale === "id" ? "Ruang lebih mudah dipakai oleh user harian." : "The room is easier for daily users to operate.",
    locale === "id" ? "Tim teknis lebih mudah melakukan support." : "Technical teams can support the system more easily."
  ];
  const crumbs = breadcrumbJsonLd([
    { name: "Home", url: `${siteUrl}${localizedPath("/", locale)}` },
    { name: "Success Stories", url: `${siteUrl}${localizedPath("/success-stories", locale)}` },
    { name: item.title[locale], url: `${siteUrl}${localizedPath(`/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">
            <blockquote className="story-quote">
              <p>{item.result[locale]}</p>
              <cite>{locale === "id" ? "Hasil project" : "Project result"}</cite>
            </blockquote>
            <StorySection title={locale === "id" ? "Background" : "Background"} body={item.background?.[locale] ?? item.shortSummary[locale]} />
            <StorySection title={locale === "id" ? "Tantangan" : "Challenge"} body={item.challenge[locale]} />
            <StorySection title={locale === "id" ? "Solusi" : "Solution"} body={item.solution[locale]} />
            <section className="story-section-block">
              <h2>{locale === "id" ? "Manfaat" : "Benefits"}</h2>
              <ul className="story-benefits-list">
                {benefits.map((benefit) => (
                  <li key={benefit}>{benefit}</li>
                ))}
              </ul>
            </section>
          </article>
          <aside className="story-info-panel" aria-label={locale === "id" ? "Informasi project" : "Project information"}>
            <h2>More Info</h2>
            <Meta label="Sector" value={getStoryIndustryLabel(item)} />
            <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]} />
      <article className="section container">
        <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 }: { locale: Locale; eyebrow: string; title: string; body: string }) {
  return (
    <section className="page-hero">
      <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: `${siteUrl}${localizedPath("/", 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: `${siteUrl}${localizedPath(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
      }
    }))
  };
}

function getIndustryEnablement(item: Industry, locale: Locale) {
  const h1Map: Record<string, string> = {
    education: locale === "id" ? "AV & IT untuk Education dan Smart Classroom" : "AV & IT for Education and Smart Classrooms",
    enterprise: locale === "id" ? "AV & IT untuk Enterprise Spaces" : "AV & IT for Enterprise Spaces",
    "government-public-sector": locale === "id" ? "AV & IT untuk Government & Public Sector" : "AV & IT for Government & Public Sector",
    "hospitality-commercial": locale === "id" ? "AV & Experience Technology untuk Hospitality & Commercial" : "AV & Experience Technology for Hospitality & Commercial"
  };

  return {
    h1: h1Map[item.slug] ?? item.title[locale],
    painPoints: item.painPoints?.[locale] ?? [item.shortDescription[locale]],
    benefits: item.keyBenefits?.[locale] ?? [item.fullDescription[locale]],
    faqs:
      item.faqs?.map((faq) => ({ question: faq.question[locale], answer: faq.answer[locale] })) ??
      defaultFaqs(locale, item.title[locale])
  };
}

function getSolutionEnablement(slug: string, locale: Locale) {
  const defaults = {
    problems:
      locale === "id"
        ? ["Customer sulit menentukan perangkat yang tepat", "Sistem lama tidak konsisten dan sulit disupport", "Ruang perlu terlihat profesional sebelum kunjungan atau event penting"]
        : ["Customers struggle to choose the right devices", "Existing systems are inconsistent and hard to support", "Rooms need to look professional before visits or important events"],
    akaryaSolution:
      locale === "id"
        ? "Akarya memulai dari kebutuhan ruang dan workflow pengguna, lalu merancang sistem, perangkat, instalasi, testing, training, dan support yang sesuai."
        : "Akarya starts from room needs and user workflow, then designs the system, devices, installation, testing, training, and support around that reality.",
    components:
      locale === "id"
        ? ["Display atau projection", "Audio system", "Kamera atau input source", "Control dan signal management", "Instalasi, testing, training"]
        : ["Display or projection", "Audio system", "Camera or input source", "Control and signal management", "Installation, testing, training"],
    suitableFor:
      locale === "id" ? ["Sekolah dan kampus", "Enterprise", "Pemerintah", "Hospitality dan ruang komersial"] : ["Schools and campuses", "Enterprise teams", "Government", "Hospitality and commercial spaces"],
    benefits:
      locale === "id" ? ["Ruang lebih mudah digunakan", "Tampilan lebih profesional", "Sistem lebih mudah disupport", "Dokumentasi project lebih jelas"] : ["Easier room operation", "More professional presentation", "Supportable system design", "Clearer project documentation"]
  };

  const bySlug: Record<string, Partial<typeof defaults>> = {
    "smart-classroom": {
      components: locale === "id" ? ["IFP atau interactive projector", "Audio kelas", "Camera untuk hybrid learning", "Wireless presentation", "Training pengajar"] : ["IFP or interactive projector", "Classroom audio", "Camera for hybrid learning", "Wireless presentation", "Teacher training"],
      suitableFor: locale === "id" ? ["Sekolah", "Kampus", "Training center", "Auditorium pembelajaran"] : ["Schools", "Universities", "Training centers", "Learning auditoriums"]
    },
    "led-display-videotron": {
      components: locale === "id" ? ["LED module", "Processor", "Mounting structure", "Content source", "Power dan service access"] : ["LED modules", "Processor", "Mounting structure", "Content source", "Power and service access"],
      suitableFor: locale === "id" ? ["Lobi", "Aula", "Command center", "Retail", "Ruang publik"] : ["Lobbies", "Halls", "Command centers", "Retail", "Public spaces"]
    },
    "meeting-room-video-conference": {
      components: locale === "id" ? ["Display", "Camera", "Microphone", "Speaker", "Room control", "Wireless presentation"] : ["Display", "Camera", "Microphone", "Speaker", "Room control", "Wireless presentation"],
      suitableFor: locale === "id" ? ["Meeting room", "Boardroom", "Hybrid meeting", "Executive room"] : ["Meeting rooms", "Boardrooms", "Hybrid meetings", "Executive rooms"]
    },
    "immersive-room": {
      components: locale === "id" ? ["Projection atau LED", "Media playback", "Audio", "Control workflow", "Content planning"] : ["Projection or LED", "Media playback", "Audio", "Control workflow", "Content planning"],
      suitableFor: locale === "id" ? ["Museum", "Hospitality", "Perpustakaan", "Brand experience"] : ["Museums", "Hospitality", "Libraries", "Brand experiences"]
    }
  };

  const merged = { ...defaults, ...bySlug[slug] };
  return {
    ...merged,
    faqs: defaultFaqs(locale, slug)
  };
}

function defaultFaqs(locale: Locale, topic: string): FaqItem[] {
  return [
    {
      question: locale === "id" ? "Apakah Akarya bisa melakukan survey lokasi?" : "Can Akarya do a site survey?",
      answer: locale === "id" ? "Ya. Survey membantu memetakan ukuran ruang, existing system, risiko instalasi, kebutuhan user, dan estimasi scope." : "Yes. A survey helps map room size, existing systems, installation risk, user needs, and estimated scope."
    },
    {
      question: locale === "id" ? "Apakah Akarya bisa memberi rekomendasi solusi sebelum proposal?" : "Can Akarya recommend a solution before proposal?",
      answer: locale === "id" ? `Bisa. Tim Akarya dapat membantu rekomendasi awal untuk ${topic} berdasarkan sektor, budget range, timeline, dan kebutuhan ruang.` : `Yes. Akarya can prepare an initial recommendation for ${topic} based on sector, budget range, timeline, and room needs.`
    },
    {
      question: locale === "id" ? "Apakah ada training setelah instalasi?" : "Is user training included after installation?",
      answer: locale === "id" ? "Training dan handover dapat disiapkan agar pengguna harian dan tim teknis lebih siap mengoperasikan sistem." : "Training and handover can be prepared so daily users and technical teams can operate the system with more confidence."
    }
  ];
}

const homeCopy = {
  en: {
    eyebrow: "AV & IT System Integrator",
    title: "Building Reliable AV, IT & Experience Technology Spaces",
    body: "Akarya is an AV & IT system integrator in Indonesia, helping education, enterprise, government, and commercial teams design, deploy, and maintain smart classrooms, meeting rooms, LED displays, digital signage, command centers, and immersive spaces.",
    primary: "Talk to Akarya",
    secondary: "",
    visual:
      "Photo-ready area: replace with real Akarya project photo - smart classroom, LED wall, meeting room, command center, or immersive room.",
    stats: [
      {
        title: "60+ Smart Classroom & AV Spaces",
        description: "Designed for education, enterprise, and public sector environments."
      },
      {
        title: "End-to-End Integration",
        description: "From consultation, system design, procurement, installation, testing, training, to after-sales support."
      },
      {
        title: "Reliable Project Execution",
        description: "Built with clear documentation, technical coordination, and long-term serviceability."
      }
    ],
    whatWeDo: "What We Do",
    introTitle: "Premium AV & IT integration for spaces people use every day.",
    introBody:
      "Akarya helps organizations turn classrooms, meeting rooms, command centers, museums, hospitality venues, and public spaces into reliable technology environments that are easy to understand and ready to operate.",
    sectorTitle: "Choose Your Sector",
    sectors: [
      {
        label: "Education",
        title: "Improve learning quality and classroom interaction.",
        body: "Smart classroom, interactive projector, IFP, auditorium, hybrid learning, and immersive learning environments.",
        href: "/industries/education"
      },
      {
        label: "Government & Public Sector",
        title: "Support digital transformation and public service.",
        body: "Meeting rooms, command centers, videotron, digital signage, auditoriums, and interactive museum systems.",
        href: "/industries/government-public-sector"
      },
      {
        label: "Enterprise",
        title: "Create professional, clean, easy-to-use workspaces.",
        body: "Meeting room, boardroom, video conference, lobby LED, signage, and collaboration systems.",
        href: "/industries/enterprise"
      },
      {
        label: "Hospitality & Commercial",
        title: "Create memorable guest and customer experiences.",
        body: "LED display, digital signage, immersive room, lobby display, and experience technology.",
        href: "/industries/hospitality-commercial"
      }
    ],
    solutionsTitle: "Choose the Right AV & IT Solution",
    solutionsBody: "From room design and product selection to installation, commissioning, training, and long-term support.",
    caseEyebrow: "Selected Success Stories",
    caseTitle: "Selected AV & IT system integration projects.",
    caseBody:
      "Explore how Akarya helps clients turn technical requirements into reliable spaces that are ready for daily use.",
    industriesEyebrow: "Industries",
    industriesTitle: "Built for organizations that need reliable technology spaces.",
    processEyebrow: "How Akarya Works",
    processTitle: "From room understanding to after-sales support.",
    process: ["Understand the Room", "Design the System", "Install & Commission", "Train the User", "Support After Deployment"],
    partnerLabel: "Technology brands and platforms we work with",
    cta: "Planning an AV & IT project?",
    ctaBody:
      "Talk to Akarya about your classroom, meeting room, LED display, signage, command center, or immersive space requirement.",
    ctaButton: "Talk to Akarya"
  },
  id: {
    eyebrow: "AV & IT System Integrator",
    title: "Building Reliable AV, IT & Experience Technology Spaces",
    body: "Akarya adalah system integrator AV & IT di Indonesia yang membantu institusi pendidikan, enterprise, pemerintah, dan ruang komersial merancang, memasang, dan mendukung smart classroom, meeting room, LED display, digital signage, command center, dan immersive space.",
    primary: "Talk to Akarya",
    secondary: "",
    visual:
      "Photo-ready area: replace with real Akarya project photo - smart classroom, LED wall, meeting room, command center, or immersive room.",
    stats: [
      {
        title: "60+ Smart Classroom & AV Spaces",
        description: "Dirancang untuk lingkungan pendidikan, enterprise, dan sektor publik."
      },
      {
        title: "End-to-End Integration",
        description: "Dari konsultasi, desain sistem, pengadaan, instalasi, testing, training, hingga after-sales support."
      },
      {
        title: "Reliable Project Execution",
        description: "Dibangun dengan dokumentasi jelas, koordinasi teknis, dan kemudahan service jangka panjang."
      }
    ],
    whatWeDo: "Yang Kami Kerjakan",
    introTitle: "Integrasi AV & IT premium untuk ruang yang dipakai setiap hari.",
    introBody:
      "Akarya membantu organisasi mengubah classroom, meeting room, command center, museum, venue hospitality, dan ruang publik menjadi lingkungan teknologi yang andal, mudah dipahami, dan siap dioperasikan.",
    sectorTitle: "Pilih Sektor Anda",
    sectors: [
      {
        label: "Education",
        title: "Tingkatkan kualitas belajar dan interaksi kelas.",
        body: "Smart classroom, interactive projector, IFP, auditorium, hybrid learning, dan immersive learning.",
        href: "/industries/education"
      },
      {
        label: "Government & Public Sector",
        title: "Dukung transformasi digital dan layanan publik.",
        body: "Meeting room, command center, videotron, digital signage, auditorium, dan interactive museum.",
        href: "/industries/government-public-sector"
      },
      {
        label: "Enterprise",
        title: "Bangun workspace profesional, rapi, dan mudah digunakan.",
        body: "Meeting room, boardroom, video conference, lobby LED, signage, dan collaboration system.",
        href: "/industries/enterprise"
      },
      {
        label: "Hospitality & Commercial",
        title: "Bangun pengalaman tamu dan customer yang berkesan.",
        body: "LED display, digital signage, immersive room, lobby display, dan experience technology.",
        href: "/industries/hospitality-commercial"
      }
    ],
    solutionsTitle: "Pilih Solusi AV & IT yang Tepat",
    solutionsBody: "Dari desain ruang dan pemilihan produk hingga instalasi, commissioning, training, dan support jangka panjang.",
    caseEyebrow: "Selected Success Stories",
    caseTitle: "Project integrasi sistem AV & IT terpilih.",
    caseBody:
      "Lihat bagaimana Akarya membantu klien mengubah kebutuhan teknis menjadi ruang andal yang siap dipakai setiap hari.",
    industriesEyebrow: "Industri",
    industriesTitle: "Dibangun untuk organisasi yang membutuhkan ruang teknologi andal.",
    processEyebrow: "Cara Kerja Akarya",
    processTitle: "Dari memahami ruang sampai support setelah deployment.",
    process: ["Understand the Room", "Design the System", "Install & Commission", "Train the User", "Support After Deployment"],
    partnerLabel: "Technology brands and platforms we work with",
    cta: "Planning an AV & IT project?",
    ctaBody:
      "Talk to Akarya about your classroom, meeting room, LED display, signage, command center, or immersive space requirement.",
    ctaButton: "Talk to Akarya"
  }
};
