import type { FAQItem } from "@/lib/types";
import type { Metadata } from "next";
import Image from "next/image";

import Link from "next/link";
import {
  ArrowRight,
  CheckCircle2,
  Building2,
  Settings2,
  Smartphone,
  BarChart3,
  Link2,
} from "lucide-react";

import Breadcrumbs, { BreadcrumbItem } from "@/components/Breadcrumbs";
import SeoJsonLd from "@/components/SeoJsonLd";
import { FAQSection } from "@/components/aeo/FAQSection";
import {
  MarketingPageTracker,
  TrackedCtaLink,
} from "@/components/marketing/MarketingAnalytics";
import { AnswerFirstBlock } from "@/components/marketing/AnswerFirstBlock";
import { Button } from "@/components/ui/Button";
import { breadcrumbSchema, faqPageSchema } from "@/lib/schema";

type LinkCard = {
  href: string;
  title: string;
  description: string;
};

type IndustryPageTemplateProps = {
  title: string;
  description: string;
  eyebrow: string;
  intro: string;
  pageType: "commercial" | "use_case";
  cluster: string;
  useCase?: string;
  breadcrumbs: BreadcrumbItem[];
  answer: string;
  whenToUse: string[];
  comparisonItems: {
    label: string;
    value: boolean;
    text?: string;
  }[];
  howToSteps: string[];
  primaryCta: {
    href: string;
    label: string;
  };
  secondaryCta: {
    href: string;
    label: string;
  };
  workflowTitle: string;
  workflowIntro: string;
  workflowCards: {
    title: string;
    description: string;
  }[];
  checklistTitle: string;
  checklist: string[];
  supportLinks: LinkCard[];
  faq: FAQItem[];
  schemaData?: Record<string, unknown>[];
  heroImage?: string;
  heroImageAlt?: string;
  statistics?: { value: string; label: string }[];
  benefits?: { title: string; description: string }[];
};

export function buildIndustryMetadata({
  title,
  fallbackTitle,
  description,
  canonicalPath,
}: {
  title: string;
  fallbackTitle?: string;
  description: string;
  canonicalPath: string;
}): Metadata {
  const canonical = `https://www.qrmaster.net${canonicalPath}`;
  const brandSuffix = " | QR Master";
  const maxTitleLength = 60;
  const maxBaseTitleLength = maxTitleLength - brandSuffix.length;
  const normalizedTitle = title.replace(/\s+\|\s+QR Master$/i, "").trim();
  const fallback = fallbackTitle?.replace(/\s+\|\s+QR Master$/i, "").trim();
  const candidates = [
    normalizedTitle,
    normalizedTitle.split(":")[0]?.trim(),
    fallback,
  ].filter((candidate): candidate is string => Boolean(candidate));
  const seoTitle =
    candidates.find((candidate) => candidate.length <= maxBaseTitleLength) ??
    normalizedTitle.slice(0, maxBaseTitleLength).replace(/\s+\S*$/, "").trim();
  const fullTitle = `${seoTitle} | QR Master`;

  return {
    title: {
      absolute: fullTitle,
    },
    description,
    alternates: {
      canonical,
      languages: {
        "x-default": canonical,
        en: canonical,
      },
    },
    openGraph: {
      title: fullTitle,
      description,
      url: canonical,
      type: "website",
      images: ["/og-image.png"],
    },
    twitter: {
      title: fullTitle,
      description,
    },
  };
}

// Map a consistent icon for workflow cards depending on index
const WORKFLOW_ICONS = [Smartphone, Settings2, BarChart3, Building2];

export function IndustryPageTemplate({
  title,
  description,
  eyebrow,
  intro,
  pageType,
  cluster,
  useCase,
  breadcrumbs,
  answer,
  whenToUse,
  comparisonItems,
  howToSteps,
  primaryCta,
  secondaryCta,
  workflowTitle,
  workflowIntro,
  workflowCards,
  checklistTitle,
  checklist,
  supportLinks,
  faq,
  schemaData = [],
  heroImage = "/hero-qr-scan-mockup.png",
  heroImageAlt = "Industry example showing a QR code workflow in action",
  statistics = [],
  benefits = [],
}: IndustryPageTemplateProps) {
  return (
    <>
      <SeoJsonLd
        data={[...schemaData, breadcrumbSchema(breadcrumbs), faqPageSchema(faq)]}
      />
      <MarketingPageTracker
        pageType={pageType}
        cluster={cluster}
        useCase={useCase}
      />

      <div className="min-h-screen bg-white text-slate-900 font-sans">
        
        {/* --- HERO SECTION --- */}
        <section className="relative pt-24 pb-20 lg:pt-36 lg:pb-32 overflow-hidden border-b border-slate-100 bg-slate-50/50">
          {/* Decorative Backgrounds */}
          <div className="pointer-events-none absolute inset-0 bg-[linear-gradient(to_right,#cbd5e1_1px,transparent_1px),linear-gradient(to_bottom,#cbd5e1_1px,transparent_1px)] bg-[size:4rem_4rem] [mask-image:radial-gradient(ellipse_80%_80%_at_50%_0%,#000_80%,transparent_110%)] opacity-30" />
          <div className="absolute top-0 right-0 -mr-[20rem] w-[60rem] h-[60rem] bg-blue-200/40 rounded-full blur-[120px] pointer-events-none" />
          
          <div className="relative container mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
            <div className="grid gap-16 lg:grid-cols-2 lg:gap-8 items-center">
              
              {/* Left Column: Text & CTAs */}
              <div className="flex flex-col justify-center text-center lg:text-left pt-10 lg:pt-0">
                <Breadcrumbs
                  items={breadcrumbs}
                  className="mb-8 justify-center lg:justify-start [&_a]:text-slate-500 [&_a:hover]:text-blue-600 [&_span]:text-slate-400 [&_[aria-current=page]]:text-slate-900"
                />

                <div className="inline-flex items-center gap-2 rounded-full border border-blue-200 bg-white/60 backdrop-blur-sm px-4 py-2 text-sm font-semibold text-blue-700 shadow-sm mb-8 mx-auto lg:mx-0 w-max">
                  <span className="relative flex h-2 w-2">
                    <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"></span>
                    <span className="relative inline-flex rounded-full h-2 w-2 bg-blue-500"></span>
                  </span>
                  Industry Solutions
                </div>

                <h1 className="max-w-3xl text-5xl font-extrabold tracking-tight text-slate-900 sm:text-6xl lg:text-7xl mb-8 leading-[1.1]">
                  {title.replace("QR Codes for", "")}{" "}
                  <span className="text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-indigo-600 block sm:inline">
                    QR Codes
                  </span>
                </h1>
                
                <p className="max-w-2xl text-xl leading-relaxed text-slate-600 mb-12 font-medium mx-auto lg:mx-0">
                  {intro}
                </p>

                <div className="flex flex-col sm:flex-row items-center justify-center lg:justify-start gap-4 w-full">
                  <TrackedCtaLink
                    href={primaryCta.href}
                    ctaLabel={primaryCta.label}
                    ctaLocation="hero_primary"
                    pageType={pageType}
                    cluster={cluster}
                    useCase={useCase}
                  >
                    <Button
                      size="lg"
                      className="w-full sm:w-auto bg-blue-600 hover:bg-blue-700 text-white rounded-full px-8 py-7 text-lg font-bold shadow-xl shadow-blue-600/30 transition-all hover:-translate-y-1"
                    >
                      {primaryCta.label}
                    </Button>
                  </TrackedCtaLink>

                  <TrackedCtaLink
                    href={secondaryCta.href}
                    ctaLabel={secondaryCta.label}
                    ctaLocation="hero_secondary"
                    pageType={pageType}
                    cluster={cluster}
                    useCase={useCase}
                  >
                    <Button
                      variant="outline"
                      size="lg"
                      className="w-full sm:w-auto overflow-hidden bg-white border-slate-200 text-slate-700 hover:border-slate-300 hover:bg-slate-50 hover:text-slate-900 rounded-full px-8 py-7 text-lg font-bold shadow-sm transition-all hover:-translate-y-1"
                    >
                      {secondaryCta.label}
                    </Button>
                  </TrackedCtaLink>
                </div>
              </div>

              {/* Right Column: Abstract App Interface Mockup */}
              <div className="relative mx-auto w-full max-w-lg lg:max-w-none flex justify-center lg:justify-end mt-12 lg:mt-0 pb-16 lg:pb-0">
                
                <div className="relative w-full max-w-[440px] aspect-[4/5] sm:aspect-[4/5]">
                  {/* Decorative glowing blobs behind the image */}
                  <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[120%] h-[120%] bg-blue-500/20 blur-[90px] rounded-full pointer-events-none" />
                  <div className="absolute -top-10 -right-10 w-64 h-64 bg-indigo-500/20 blur-[70px] rounded-full pointer-events-none" />
                  
                  {/* Floating abstract element 1: Notification */}
                  <div className="absolute z-30 top-1/4 -left-6 sm:-left-12 bg-white/90 backdrop-blur-md p-4 rounded-2xl shadow-2xl shadow-slate-200/50 border border-slate-100/50 flex items-center gap-4 transition-transform hover:scale-105 duration-300 scale-90 sm:scale-100">
                    <div className="w-12 h-12 rounded-full bg-emerald-100 flex items-center justify-center shrink-0">
                      <CheckCircle2 className="w-6 h-6 text-emerald-600" />
                    </div>
                    <div>
                      <div className="text-sm font-black text-slate-900 tracking-tight">Active Scan!</div>
                      <div className="text-xs text-slate-500 font-medium">Just now</div>
                    </div>
                  </div>

                  {/* Floating abstract element 2: Stats */}
                  <div className="absolute z-30 bottom-1/4 -right-4 sm:-right-8 bg-white/90 backdrop-blur-md p-4 rounded-2xl shadow-2xl shadow-slate-200/50 border border-slate-100/50 flex items-center gap-4 transition-transform hover:scale-105 duration-300 scale-90 sm:scale-100 delay-100">
                    <div className="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center shrink-0">
                      <BarChart3 className="w-6 h-6 text-blue-600" />
                    </div>
                    <div>
                      <div className="text-sm font-black text-slate-900 tracking-tight">+148 Views</div>
                      <div className="text-xs text-slate-500 font-medium">This week</div>
                    </div>
                  </div>

                  {/* AI Generated Photorealistic Image */}
                  <div className="relative z-20 w-full h-full rounded-[2rem] sm:rounded-[2.5rem] shadow-2xl shadow-blue-900/30 border-8 border-white overflow-hidden rotate-0 sm:rotate-2 transition-transform duration-700 hover:rotate-0">
                    <Image
                      src={heroImage}
                      alt={heroImageAlt}
                      fill
                      priority
                      className="object-cover"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>


        {/* --- BENEFITS SECTION --- */}
        {benefits.length > 0 && (
          <section className="py-20 bg-slate-50 border-t border-slate-100 relative z-10">
            <div className="container mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
              <div className="text-center mb-16">
                <h2 className="text-3xl font-bold tracking-tight text-slate-900 sm:text-4xl max-w-2xl mx-auto">
                  Why Leading {title.replace("QR Codes for ", "").replace("QR Codes for", "")} Businesses Use QR Master
                </h2>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
                {benefits.map((benefit, index) => (
                  <div key={benefit.title} className="bg-white rounded-3xl p-8 shadow-sm border border-slate-200 hover:border-blue-200 hover:shadow-lg transition-all">
                    <div className="w-12 h-12 rounded-full bg-indigo-50 flex items-center justify-center text-indigo-600 font-bold text-xl mb-6">
                      {index + 1}
                    </div>
                    <h3 className="text-xl font-bold text-slate-900 mb-4">{benefit.title}</h3>
                    <p className="text-slate-600 leading-relaxed">{benefit.description}</p>
                  </div>
                ))}
              </div>
            </div>
          </section>
        )}

        {/* --- WORKFLOW CARDS SECTION (USE CASES) --- */}
        <section className="py-12 bg-white relative z-10">
          <div className="container mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
              {workflowCards.map((card, index) => {
                const Icon = WORKFLOW_ICONS[index % WORKFLOW_ICONS.length];
                return (
                  <div
                    key={card.title}
                    className="flex flex-col group rounded-[2rem] border border-slate-200 bg-white p-8 shadow-sm hover:shadow-xl transition-all duration-300 hover:-translate-y-1"
                  >
                    <div className="mb-6 flex h-14 w-14 items-center justify-center rounded-2xl bg-blue-50 text-blue-600 group-hover:scale-110 group-hover:bg-blue-600 group-hover:text-white transition-all duration-300">
                      <Icon className="h-7 w-7" />
                    </div>
                    <h3 className="mb-3 text-2xl font-bold text-slate-900 leading-tight">
                      {card.title}
                    </h3>
                    <p className="text-slate-600 leading-relaxed text-lg">
                      {card.description}
                    </p>
                  </div>
                );
              })}
            </div>
          </div>
        </section>

        {/* --- QUICK SUMMARY (ANSWER FIRST) --- */}
        <section className="py-16">
          <div className="container mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
            <div className="mb-8 text-center">
              <h2 className="text-3xl font-bold tracking-tight text-slate-900 sm:text-4xl">
                Quick Summary
              </h2>
              <p className="mt-4 text-lg text-slate-600 max-w-2xl mx-auto">
                {answer}
              </p>
            </div>
            
            <div className="rounded-[2rem] border border-slate-100 bg-white p-2">
              <AnswerFirstBlock
                whatIsIt={answer}
                whenToUse={whenToUse}
                comparison={{
                  leftTitle: "Static Pages",
                  rightTitle: "QR Master Pages",
                  items: comparisonItems,
                }}
                howTo={{
                  steps: howToSteps,
                }}
                className="mt-0 shadow-none border-0"
              />
            </div>
          </div>
        </section>

        {/* --- IMPLEMENTATION CHECKLIST --- */}
        <section className="py-20 bg-slate-50">
          <div className="container mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
            <div className="mx-auto max-w-2xl text-center mb-12">
              <h2 className="text-3xl font-bold tracking-tight text-slate-900 sm:text-4xl">
                {checklistTitle}
              </h2>
            </div>
            <div className="grid gap-x-8 gap-y-4 sm:grid-cols-2">
              {checklist.map((item) => (
                <div key={item} className="flex items-start gap-4 p-4 rounded-xl bg-white border border-slate-200 shadow-sm">
                  <CheckCircle2 className="h-6 w-6 shrink-0 text-blue-600 mt-0.5" />
                  <span className="text-lg font-medium text-slate-700">{item}</span>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* --- RECOMMENDED TOOLS --- */}
        <section className="py-24">
          <div className="container mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
            <div className="relative overflow-hidden rounded-[2.5rem] bg-slate-900 px-6 py-16 sm:px-12 sm:py-20 lg:px-16 text-center text-white shadow-2xl shadow-indigo-900/20 border border-slate-800">
              <div className="absolute -top-24 -right-24 w-96 h-96 bg-blue-600/20 blur-[100px] rounded-full pointer-events-none" />
              <div className="absolute -bottom-24 -left-24 w-96 h-96 bg-indigo-600/20 blur-[100px] rounded-full pointer-events-none" />
              <div className="relative z-10">
                <h2 className="text-3xl font-bold tracking-tight sm:text-4xl mb-12">
                  Recommended Tools
                </h2>
                <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3 max-w-5xl mx-auto">
                  {supportLinks.map((link) => (
                    <Link
                      key={link.href}
                      href={link.href}
                      className="group flex flex-col items-center rounded-3xl bg-slate-800/50 p-8 border border-slate-700 transition-all hover:bg-white hover:border-white hover:scale-105 backdrop-blur-md shadow-xl"
                    >
                      <div className="mb-4 text-indigo-400 group-hover:text-blue-600 transition-colors">
                        <Link2 className="h-10 w-10" />
                      </div>
                      <div className="text-xl font-bold text-white group-hover:text-slate-900 mb-2 transition-colors">
                        {link.title}
                      </div>
                      <p className="mb-4 text-sm leading-relaxed text-slate-400 group-hover:text-slate-600 transition-colors">
                        {link.description}
                      </p>
                      <div className="text-sm font-medium text-slate-300 group-hover:text-blue-600 transition-colors">
                        Use Tool &rarr;
                      </div>
                    </Link>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* --- FAQ SECTION --- */}
        <section className="py-16">
          <div className="container mx-auto max-w-4xl px-4 sm:px-6 lg:px-8">
            <div className="text-center mb-10">
              <h2 className="text-3xl font-bold tracking-tight text-slate-900 sm:text-4xl">
                FAQ
              </h2>
            </div>
            <div className="rounded-3xl bg-white p-6 sm:p-10 shadow-sm border border-slate-200">
              <FAQSection items={faq} title="" />
            </div>
          </div>
        </section>

        {/* --- FINAL CTA --- */}
        <section className="relative overflow-hidden bg-slate-900 border-t border-slate-800 pt-24 pb-44 text-center -mb-20">
          <div className="absolute top-0 right-1/4 w-[40rem] h-[40rem] bg-blue-600/20 blur-[120px] rounded-full pointer-events-none" />
          <div className="absolute bottom-0 left-1/4 w-[40rem] h-[40rem] bg-indigo-600/20 blur-[120px] rounded-full pointer-events-none" />
          
          <div className="relative z-10 container mx-auto max-w-4xl px-4 sm:px-6 lg:px-8">
            <h2 className="mb-6 text-4xl font-extrabold tracking-tight text-white sm:text-5xl">
              Ready to modernize your operations?
            </h2>
            <p className="mx-auto mb-10 text-xl text-slate-300 max-w-2xl font-medium">
              Elevate your {title.replace("QR Codes for", "").trim().toLowerCase()} experience: seamless operations and enhanced engagement.
            </p>
            <div className="flex flex-col justify-center gap-4 sm:flex-row">
              <TrackedCtaLink
                href={primaryCta.href}
                ctaLabel={primaryCta.label}
                ctaLocation="footer_primary"
                pageType={pageType}
                cluster={cluster}
                useCase={useCase}
              >
                <Button
                  size="lg"
                  className="w-full bg-blue-600 px-10 py-7 text-lg font-bold text-white hover:bg-blue-500 hover:shadow-blue-500/25 sm:w-auto rounded-full shadow-xl shadow-blue-600/20 transition-all hover:-translate-y-1 border border-blue-500"
                >
                  {primaryCta.label}
                </Button>
              </TrackedCtaLink>
            </div>
          </div>
        </section>

      </div>
    </>
  );
}
