import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import { notFound } from "next/navigation";
import { ArrowRight } from "lucide-react";
import { Container } from "@/components/container";
import { Breadcrumbs } from "@/components/breadcrumbs";
import { CTASection } from "@/components/cta-section";
import { JsonLd } from "@/components/json-ld";
import { FAQAccordion } from "@/components/faq-accordion";
import { getIndustry, industrySlugs } from "@/content/industries";
import { site, ogBase, twitterBase } from "@/content/site";
import { IndustryHeroSimulator } from "@/components/industries/industry-hero-simulator";
import { IndustryWhatsAppMockup } from "@/components/industries/industry-whatsapp-mockup";
import { IndustryVoiceShowcase } from "@/components/industries/industry-voice-showcase";
import { ThreeUIDefenseLines, ThreeUIGatewayFlow } from "@/components/threeui/dynamic-effects";
import { LazyEffect } from "@/components/threeui/lazy-effect";

export function generateStaticParams() {
  return industrySlugs.map((slug) => ({ slug }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const industry = getIndustry(slug);
  if (!industry) {
    return { title: "Industry not found", robots: { index: false, follow: false } };
  }

  const title = industry.seo?.title || `${industry.name} AI Agents — Voice & WhatsApp Automation`;
  const description = industry.seo?.description || industry.description;

  return {
    title,
    description,
    keywords: industry.keywords,
    alternates: { canonical: `/industries/${industry.slug}` },
    openGraph: {
      ...ogBase,
      title,
      description,
      url: `/industries/${industry.slug}`,
    },
    twitter: {
      ...twitterBase,
      title,
      description,
    },
  };
}

export default async function IndustryDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const industry = getIndustry(slug);
  if (!industry) notFound();

  const serviceSchema = {
    "@context": "https://schema.org",
    "@type": "Service",
    name: `AI Conversational Agents for ${industry.name}`,
    serviceType: "Conversational AI Automation",
    description: industry.description,
    provider: {
      "@type": "Organization",
      name: site.name,
      url: site.url,
    },
    areaServed: industry.name,
    audience: {
      "@type": "Audience",
      audienceType: `${industry.name} Enterprises`,
    },
  };

  const breadcrumbSchema = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      { "@type": "ListItem", position: 1, name: "Home", item: site.url },
      { "@type": "ListItem", position: 2, name: "Industries", item: `${site.url}/industries` },
      { "@type": "ListItem", position: 3, name: industry.name, item: `${site.url}/industries/${industry.slug}` },
    ],
  };

  const faqSchema = industry.faqs?.length
    ? {
        "@context": "https://schema.org",
        "@type": "FAQPage",
        mainEntity: industry.faqs.map((f) => ({
          "@type": "Question",
          name: f.q,
          acceptedAnswer: {
            "@type": "Answer",
            text: f.a,
          },
        })),
      }
    : null;

  const schemas: Record<string, unknown>[] = [serviceSchema, breadcrumbSchema];
  if (faqSchema) {
    schemas.push(faqSchema);
  }

  return (
    <>
      <JsonLd data={schemas} />

      <article className="relative overflow-hidden page-top-space pb-16 md:pb-20">
        {/* Ambient background glow for hero — starts at top: 0 behind fixed header */}
        <div
          aria-hidden="true"
          className="pointer-events-none absolute inset-x-0 top-0 -z-10 mx-auto h-96 w-full max-w-6xl bg-gradient-to-r from-[#4FDAF1]/20 via-[#F79C09]/15 to-[#E26B0B]/20 blur-3xl"
        />

        <Container className="max-w-6xl">
          {/* Top Nav Rail: Breadcrumbs */}
          <div className="flex flex-wrap items-center justify-between gap-4 border-b border-border/50 pb-5">
            <Breadcrumbs
              items={[
                { label: "Industries", href: "/industries" },
                { label: industry.name },
              ]}
            />
          </div>

          {/* Hero Section: 2-Column Desktop Layout. No decorative background sits
              behind the hero image — it stands on the clean page. */}
          <div className="relative mt-8 mb-14 sm:mb-16">
            <div className="grid grid-cols-1 items-center gap-8 lg:grid-cols-12 lg:gap-12">
            {/* Left Column: Eyebrow, H1, Supporting Text & CTAs (§16-18, §43) */}
            <div className="flex flex-col lg:col-span-7 text-left">
              <div className="mb-3 inline-flex w-fit items-center gap-2 rounded-full border border-[var(--accent-cyan-text)]/30 bg-[var(--accent-cyan-text)]/10 px-3 py-1 text-xs font-semibold text-[var(--accent-cyan-text)]">
                <span className="size-1.5 rounded-full bg-[var(--accent-cyan-text)] shadow-[0_0_6px_rgba(8,145,178,0.8)]" />
                <span>{industry.name} Conversational AI</span>
              </div>

              <h1 className="font-display text-4xl font-medium tracking-tight text-foreground sm:text-5xl md:text-6xl leading-[1.08]">
                AI agents for{" "}
                <span className="font-extrabold text-gradient-brand">
                  {industry.name.toLowerCase()}
                </span>
              </h1>

              <p className="mt-4 text-base text-muted-foreground sm:text-lg leading-relaxed max-w-xl">
                {industry.hero.sub}
              </p>

              {/* Action CTAs on the LEFT directly under supporting text (§43) */}
              <div className="mt-7 flex flex-wrap items-center gap-3.5">
                <Link
                  href="/contact"
                  className="inline-flex items-center justify-center rounded-full bg-gradient-brand px-6 py-3 text-sm font-bold text-white shadow-sm glow-brand transition-all hover:scale-[1.02] active:scale-[0.98]"
                >
                  Deploy {industry.name} Agent
                  <ArrowRight className="ml-2 size-4 text-white" />
                </Link>
                <Link
                  href="#simulator"
                  className="inline-flex items-center justify-center rounded-full border border-border bg-background px-6 py-3 text-sm font-semibold text-foreground transition-all hover:bg-muted"
                >
                  Live Interactive Demo
                </Link>
              </div>
            </div>

            {/* Right Column: Industry Hero Image */}
            <div className="flex items-center justify-center lg:col-span-5">
              <div className="w-full max-w-[380px] sm:max-w-[440px]">
                <Image
                  src={industry.image}
                  alt={industry.imageAlt}
                  width={486}
                  height={438}
                  priority
                  sizes="(max-width: 640px) 90vw, (max-width: 1024px) 45vw, 440px"
                  className="h-auto w-full object-contain transition-transform duration-500 hover:scale-[1.02]"
                />
              </div>
            </div>
            </div>
          </div>

          {/* Interactive Agent Simulator Card — DARK, Gateway Flow (§29: system/flow) */}
          <div id="simulator" className="dark relative isolate mt-12 overflow-hidden rounded-3xl border border-neutral-800 bg-[#020202] p-6 text-foreground shadow-2xl sm:mt-16 sm:p-8 md:p-10 scroll-mt-24">
            <div
              aria-hidden="true"
              className="pointer-events-none absolute inset-0 -z-10 opacity-30 select-none overflow-hidden"
            >
              <LazyEffect className="absolute inset-0 size-full">
                <ThreeUIGatewayFlow />
              </LazyEffect>
            </div>
            <div className="relative z-10">
              <div className="mb-6 max-w-2xl">
                <span className="text-xs font-bold uppercase tracking-wider text-neutral-400">
                  Interactive Simulator
                </span>
                <h2 className="mt-1.5 font-display text-2xl sm:text-3xl font-bold text-white">
                  Experience {industry.name} Agent Live
                </h2>
                <p className="mt-2 text-sm sm:text-base text-neutral-300 leading-relaxed">
                  Test-drive how Quto autonomously triages {industry.name.toLowerCase()} workflows, resolves multi-turn customer intents, and responds with sub-350ms cadence. Switch between Chat and Voice Call modes below to preview the agent experience.
                </p>
              </div>
              <IndustryHeroSimulator
                agentName={industry.hero.agentName}
                agentDescription={industry.hero.agentDescription}
                chatScript={industry.hero.chatScript}
                callScript={industry.hero.callScript}
                audioSample={industry.hero.audioSample}
              />
            </div>
          </div>

          {/* Showcase 1: Contextual Automation on Messaging (e.g. WhatsApp Refill / NDR) */}
          <section className="mt-20 sm:mt-28 grid grid-cols-1 gap-8 lg:grid-cols-12 lg:items-center lg:gap-12">
            <div className="space-y-6 lg:col-span-6">
              <span className="rounded-full border border-[var(--accent-cyan-text)]/30 bg-[var(--accent-cyan-text)]/10 px-3 py-1 text-xs font-semibold uppercase tracking-wider text-[var(--accent-cyan-text)]">
                Omnichannel Messaging
              </span>

              <h2 className="font-display text-3xl font-bold tracking-tight text-foreground sm:text-4xl leading-tight">
                {industry.showcaseMessaging.title}
              </h2>

              <p className="text-base leading-relaxed text-muted-foreground">
                {industry.showcaseMessaging.description}
              </p>

              <Link
                href="/whatsapp-ai"
                className="inline-flex w-fit items-center gap-1.5 text-sm font-semibold text-[var(--accent-cyan-text)] hover:underline"
              >
                Explore WhatsApp AI automation
                <ArrowRight className="size-4" />
              </Link>

              {/* Metrics Grid */}
              {industry.showcaseMessaging.metrics && industry.showcaseMessaging.metrics.length > 0 && (
                <div className="grid grid-cols-2 gap-4 border-t border-border/60 pt-6">
                  {industry.showcaseMessaging.metrics.map((m, idx) => (
                    <div key={idx} className="flex flex-col">
                      <span className="font-display text-xl sm:text-3xl font-black text-gradient-brand">
                        {m.value}
                      </span>
                      <span className="text-xs text-muted-foreground mt-1">{m.label}</span>
                    </div>
                  ))}
                </div>
              )}

            </div>

            <div className="lg:col-span-6">
              <IndustryWhatsAppMockup
                chatTitle={industry.showcaseMessaging.chatTitle}
                chatSubtitle={industry.showcaseMessaging.chatSubtitle}
                messages={industry.showcaseMessaging.messages}
              />
            </div>
          </section>

          {/* Showcase 2: Low-Latency Natural Voice AI - DARK TECHNICAL SECTION with Defense Lines */}
          <section className="dark relative isolate mt-20 overflow-hidden rounded-3xl border border-neutral-800 bg-[#020202] p-6 sm:p-10 lg:p-14 text-foreground shadow-2xl sm:mt-28">
            <div
              aria-hidden="true"
              className="pointer-events-none absolute inset-0 -z-10 opacity-30 select-none overflow-hidden"
            >
              <LazyEffect className="absolute inset-0 size-full">
                <ThreeUIDefenseLines />
              </LazyEffect>
            </div>
            <div className="relative z-10 grid grid-cols-1 gap-8 lg:grid-cols-12 lg:items-center lg:gap-12">
              <div className="lg:col-span-6 order-2 lg:order-1">
                <IndustryVoiceShowcase
                  callTitle={industry.showcaseVoice.callTitle}
                  callSubtitle={industry.showcaseVoice.callSubtitle}
                  durationSeconds={industry.showcaseVoice.durationSeconds}
                  audioUrl={industry.hero.audioSample}
                />
              </div>

              <div className="space-y-6 lg:col-span-6 order-1 lg:order-2">
                <span className="rounded-full bg-neutral-900 border border-[#67B7E7]/30 px-3 py-1 text-xs font-semibold uppercase tracking-wider text-[#67B7E7]">
                  Voice Telephony Intelligence
                </span>

                <h2 className="font-display text-3xl font-bold tracking-tight text-white sm:text-4xl leading-tight">
                  {industry.showcaseVoice.title}
                </h2>

                <p className="text-base leading-relaxed text-neutral-300">
                  {industry.showcaseVoice.description}
                </p>

                <Link
                  href="/voice-ai"
                  className="inline-flex w-fit items-center gap-1.5 text-sm font-semibold text-[#67B7E7] hover:underline"
                >
                  Explore Voice AI agents
                  <ArrowRight className="size-4" />
                </Link>

                {/* Metrics Grid */}
                {industry.showcaseVoice.metrics && industry.showcaseVoice.metrics.length > 0 && (
                  <div className="grid grid-cols-2 gap-4 border-t border-neutral-800 pt-6">
                    {industry.showcaseVoice.metrics.map((m, idx) => (
                      <div key={idx} className="flex flex-col">
                        <span className="font-display text-xl sm:text-3xl font-black text-gradient-cool">
                          {m.value}
                        </span>
                        <span className="text-xs text-neutral-400 mt-1">{m.label}</span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </section>

          {/* Key Industry Workflows Grid */}
          <section className="mt-24 sm:mt-32">
            <div className="text-center max-w-2xl mx-auto">
              <span className="rounded-full border border-[#F79C09]/30 bg-[#F79C09]/10 px-3 py-1 text-xs font-semibold uppercase tracking-wider text-[#F79C09]">
                Workflows & Capabilities
              </span>
              <h2 className="mt-3 font-display text-3xl font-bold tracking-tight text-foreground sm:text-4xl">
                Engineered for <span className="text-gradient-brand">{industry.name}</span> operations
              </h2>
              <p className="mt-2 text-sm text-muted-foreground">
                Pre-trained intent models and standard connectors designed for high-concurrency workflows.
              </p>
            </div>

            <div className="mt-10 grid grid-cols-1 gap-6 sm:grid-cols-2">
              {industry.useCases.map((uc, idx) => (
                <div
                  key={idx}
                  className="group relative flex flex-col justify-between rounded-2xl border border-border/80 bg-card p-6 shadow-xs transition-all duration-300 hover:border-[#4FDAF1]/50 hover:shadow-md"
                >
                  <div>
                    <div className="flex items-center justify-between gap-2">
                      <span className="rounded-full border border-[var(--accent-cyan-text)]/30 bg-[var(--accent-cyan-text)]/10 px-2.5 py-0.5 text-[11px] font-semibold text-[var(--accent-cyan-text)]">
                        {uc.tag}
                      </span>
                      {uc.metric && (
                        <span className="text-xs font-mono font-black text-gradient-warm">
                          {uc.metric}
                        </span>
                      )}
                    </div>

                    <h3 className="mt-4 font-display text-lg font-bold text-foreground group-hover:text-[var(--accent-cyan-text)] transition-colors">
                      {uc.title}
                    </h3>
                    <p className="mt-2 text-sm text-muted-foreground leading-relaxed">
                      {uc.description}
                    </p>
                  </div>

                  <div className="mt-6 flex items-center gap-1.5 text-xs font-semibold text-[var(--accent-cyan-text)]">
                    <span>Deploy this agent</span>
                    <ArrowRight className="size-3.5 transition-transform group-hover:translate-x-1" />
                  </div>
                </div>
              ))}
            </div>
          </section>

          {/* Industry FAQs */}
          {industry.faqs && industry.faqs.length > 0 && (
            <section className="mt-20 sm:mt-28">
              <div className="text-center max-w-xl mx-auto mb-10">
                <span className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                  Frequently Asked Questions
                </span>
                <h2 className="mt-2 font-display text-3xl font-bold tracking-tight text-foreground">
                  Common questions on {industry.name} deployment
                </h2>
              </div>
              <FAQAccordion faqs={industry.faqs} />
            </section>
          )}
        </Container>
      </article>

      <CTASection />
    </>
  );
}
