import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import { ArrowRight, Lock, Volume2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { Container } from "@/components/container";
import { Section } from "@/components/section";
import { SectionHeader } from "@/components/section-header";
import { Reveal, RevealGroup, RevealItem } from "@/components/motion";
import { HeroReveal } from "@/components/hero-reveal";
import { ProcessTimeline } from "@/components/process-timeline";
import { LogoMarquee } from "@/components/logo-marquee";
import { HeroChannelFan } from "@/components/hero-channel-fan";
import { HeroConsole } from "@/components/hero-console";
import { QAAuditSection } from "@/components/qa-audit-section";
import { UseCasesSection } from "@/components/use-cases-section";
import { IndustryTechSection } from "@/components/industry-tech-section";
import { QutoChatbotSection } from "@/components/quto-chatbot-section";
import { FAQAccordion } from "@/components/faq-accordion";
import { CTASection } from "@/components/cta-section";
import { JsonLd } from "@/components/json-ld";
import { HomeBlogCarousel } from "@/components/home-blog-carousel";
import { blogService } from "@/lib/blog-service";
import { integrations } from "@/content/integrations";
import { site } from "@/content/site";
import {
  homeFaqs,
  howItWorks,
  securityBadges,
  securityPoints,
} from "@/content/home";

export const metadata: Metadata = {
  title: {
    absolute: "Quto AI — AI Agents Agency for Voice, WhatsApp, Chat & Web",
  },
  description:
    "Quto AI builds and runs conversational AI agents across voice, WhatsApp, chat and web — done-for-you agents that book, qualify and support your customers.",
  alternates: { canonical: "/" },
};

const orgSchema = {
  "@context": "https://schema.org",
  "@type": "Organization",
  name: site.name,
  url: site.url,
  logo: `${site.url}/images/bot-logo.png`,
  description: site.description,
  ...(site.sameAs.length ? { sameAs: site.sameAs } : {}),
  ...(site.email
    ? {
        contactPoint: {
          "@type": "ContactPoint",
          email: site.email,
          contactType: "sales",
          areaServed: "Global",
        },
      }
    : {}),
};

const websiteSchema = {
  "@context": "https://schema.org",
  "@type": "WebSite",
  name: site.name,
  url: site.url,
};

type SolutionCardData = {
  iconSrc: string;
  iconAlt: string;
  title: string;
  desc: string;
  tag: string;
  href?: string;
  cta?: string;
  featured?: boolean;
};

const SOLUTIONS: SolutionCardData[] = [
  {
    iconSrc: "/images/ai-voice-agent.webp",
    iconAlt: "AI Voice Agent",
    title: "AI Voice Agents",
    desc: "Human-sounding inbound & outbound calling that handles interruptions, qualifies leads and books appointments 24/7.",
    tag: "Sub-350ms latency",
  },
  {
    iconSrc: "/images/whatsapp-ai-agent.webp",
    iconAlt: "WhatsApp AI Agent",
    title: "WhatsApp AI Agents",
    desc: "Automated re-engagement, cart recovery and interactive flows on the official WhatsApp Cloud API, where your customers already are.",
    tag: "Official Cloud API",
  },
  {
    iconSrc: "/images/web-agent.webp",
    iconAlt: "Web Agent",
    title: "Web Agents",
    desc: "An embeddable on-site assistant that engages high-intent visitors, answers product questions and routes booked calls.",
    tag: "Embeddable",
  },
  {
    iconSrc: "/images/cuto-chatbot-agent.webp",
    iconAlt: "Quto Talk Agent",
    title: "Quto Talk",
    desc: "Give us your website URL — we turn it into an intelligent chatbot that understands your business and helps your visitors.",
    tag: "Understands your website",
    href: "#quto-chatbot",
    cta: "See how it works",
    featured: true,
  },
];

function SolutionBentoCard({ s }: { s: SolutionCardData }) {
  const cardBorderAndGlow = s.featured
    ? "card-gradient-highlight shadow-[0_0_40px_-10px_rgba(79,218,241,0.35)] bg-gradient-to-br from-card via-[#4FDAF1]/5 to-[#E26B0B]/5"
    : s.title.includes("Voice")
      ? "border border-[#4FDAF1]/35 hover:border-[#4FDAF1]/80 hover:shadow-[0_0_30px_-10px_rgba(79,218,241,0.3)] bg-gradient-to-b from-card to-[#4FDAF1]/[0.03]"
      : s.title.includes("WhatsApp")
        ? "border border-[#67B7E7]/35 hover:border-[#67B7E7]/80 hover:shadow-[0_0_30px_-10px_rgba(103,183,231,0.3)] bg-gradient-to-b from-card to-[#67B7E7]/[0.03]"
        : "border border-[#F79C09]/35 hover:border-[#F79C09]/80 hover:shadow-[0_0_30px_-10px_rgba(247,156,9,0.3)] bg-gradient-to-b from-card to-[#F79C09]/[0.03]";

  const cls = `group flex h-full flex-col justify-between rounded-3xl p-6 shadow-sm transition-all duration-300 hover:-translate-y-1 hover:shadow-xl motion-reduce:transition-none motion-reduce:hover:translate-y-0 md:p-8 ${cardBorderAndGlow}`;

  const tagClass = s.featured
    ? "badge-gradient-brand font-bold text-foreground"
    : s.title.includes("Voice")
      ? "border border-[#4FDAF1]/50 bg-[#4FDAF1]/10 text-foreground font-semibold"
      : s.title.includes("WhatsApp")
        ? "border border-[#67B7E7]/50 bg-[#67B7E7]/10 text-foreground font-semibold"
        : "border border-[#F79C09]/50 bg-[#F79C09]/10 text-foreground font-semibold";

  const inner = (
    <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
      <div className="flex flex-1 flex-col justify-between">
        <div>
          <span className={cn("inline-flex rounded-full border px-3 py-1 text-xs", tagClass)}>
            {s.tag}
          </span>
          <h3 className="mt-4 font-display text-xl font-bold tracking-tight text-foreground sm:text-2xl">
            {s.featured ? (
              <span className="text-gradient-brand">{s.title}</span>
            ) : (
              s.title
            )}
          </h3>
          <p className="mt-2.5 text-sm leading-relaxed text-muted-foreground">
            {s.desc}
          </p>
        </div>
        {s.cta ? (
          <span className="mt-5 inline-flex items-center gap-1.5 text-xs font-bold uppercase tracking-wider text-[#E26B0B] group-hover:underline">
            {s.cta}
            <ArrowRight className="size-3.5 transition-transform group-hover:translate-x-1 motion-reduce:transition-none" />
          </span>
        ) : null}
      </div>

      {/* Right: the supplied WebP icon, large and clean — no box/background (§19–§22) */}
      <div className="relative shrink-0 self-center md:self-auto flex items-center justify-center size-28 sm:size-32 md:size-40 transition-transform duration-300 group-hover:scale-[1.04] motion-reduce:transition-none motion-reduce:group-hover:scale-100">
        <Image
          src={s.iconSrc}
          alt={s.iconAlt}
          width={405}
          height={405}
          sizes="(max-width: 768px) 128px, 160px"
          className="size-full object-contain select-none pointer-events-none"
        />
      </div>
    </div>
  );

  return s.href ? (
    <Link href={s.href} className={cls}>
      {inner}
    </Link>
  ) : (
    <div className={cls}>{inner}</div>
  );
}

// ISR: the homepage (including its latest-blog carousel) is cached and
// revalidated periodically — it does NOT become dynamic/uncached just because it
// shows the latest posts. Publishing also revalidates "/" for immediate freshness.
export const revalidate = 300;

export default async function HomePage() {
  // Public, server-side data access — 6 latest PUBLISHED posts, minimal fields,
  // DB-side limit. No admin API, no auth, no fetch-all-then-slice.
  const latestPosts = await blogService.getLatestPublishedPostCards(6);
  return (
    <>
      <JsonLd data={[orgSchema, websiteSchema]} />

      {/* 1. HERO */}
      <section className="relative overflow-hidden pt-20 pb-8 md:pt-24 md:pb-12">
        {/* Radiant ambient atmospheric color glows */}
        <div aria-hidden="true" className="pointer-events-none absolute -left-32 -top-12 size-[520px] rounded-full bg-[radial-gradient(circle,rgba(79,218,241,0.18)_0%,transparent_70%)] blur-3xl" />
        <div aria-hidden="true" className="pointer-events-none absolute -right-32 top-8 size-[520px] rounded-full bg-[radial-gradient(circle,rgba(226,107,11,0.15)_0%,transparent_70%)] blur-3xl" />
        <div aria-hidden="true" className="pointer-events-none absolute left-1/2 top-48 -translate-x-1/2 size-[650px] rounded-full bg-[radial-gradient(circle,rgba(247,156,9,0.08)_0%,transparent_70%)] blur-3xl" />

        <Container className="relative z-10 flex flex-col items-center text-center">
          <HeroReveal className="mb-6">
            <HeroChannelFan />
          </HeroReveal>

          <HeroReveal order={1}>
            <div className="badge-gradient-brand inline-flex max-w-full flex-wrap items-center justify-center gap-x-2 gap-y-1 rounded-full px-4 py-1.5 text-xs font-bold uppercase tracking-wider text-foreground shadow-sm">
              <span className="relative flex size-2">
                <span className="absolute inline-flex size-full animate-ping rounded-full bg-[#4FDAF1] opacity-80 motion-reduce:animate-none" />
                <span className="relative inline-flex size-2 rounded-full bg-[#4FDAF1]" />
              </span>
              <span>AI Agents Agency</span>
              <span className="text-muted-foreground/60">|</span>
              <span className="font-semibold text-foreground">Voice · WhatsApp · Web</span>
            </div>
          </HeroReveal>

          <HeroReveal order={2} lcp>
            <h1 className="mt-6 max-w-4xl text-balance font-display text-[clamp(2.75rem,6.5vw,5rem)] font-normal leading-[1.04] tracking-[-0.03em] text-foreground">
              <span className="font-extrabold text-gradient-brand">AI agents</span> that do the{" "}
              <span className="font-extrabold text-gradient-warm">work</span>.
            </h1>
          </HeroReveal>

          <HeroReveal order={3}>
            <p className="mt-5 max-w-2xl text-pretty text-base text-muted-foreground sm:text-lg md:text-xl md:leading-relaxed">
              We design, build and deploy conversational AI agents across{" "}
              <strong className="font-semibold text-foreground">
                Voice, WhatsApp, Chat and Web
              </strong>{" "}
              — so every lead is answered in seconds, qualified, and followed up
              24/7.
            </p>
          </HeroReveal>

          <HeroReveal order={4}>
            <div className="mt-8 flex flex-wrap items-center justify-center gap-3.5">
              <Button asChild variant="accent" size="pill-lg">
                <Link href="/contact" className="group">
                  Book a call
                  <ArrowRight className="ml-1.5 size-4 transition-transform group-hover:translate-x-1 motion-reduce:transition-none" />
                </Link>
              </Button>
              <Button asChild variant="outline" size="pill-lg" className="border-[#4FDAF1]/40 hover:border-[#4FDAF1] hover:bg-[#4FDAF1]/5">
                <Link href="#use-cases" className="flex items-center gap-2">
                  <Volume2 className="size-4 text-[#4FDAF1]" />
                  <span>Hear a live sample</span>
                </Link>
              </Button>
            </div>
          </HeroReveal>

          <HeroReveal order={5} className="mt-10 w-full">
            <HeroConsole />
          </HeroReveal>
        </Container>
      </section>

      {/* 2. WORKS WITH YOUR STACK */}
      <Section className="border-y border-border/60 py-6 md:py-8">
        <Container>
          <p className="text-center text-xs font-semibold uppercase tracking-widest text-muted-foreground">
            Orchestrated with your existing telephony &amp; business stack
          </p>
          <div className="mt-5">
            <LogoMarquee items={integrations} />
          </div>
        </Container>
      </Section>

      {/* 3. SOLUTIONS */}
      <Section id="solutions" className="scroll-mt-24 py-10 md:py-16">
        <Container>
          <Reveal>
            <SectionHeader
              eyebrow="Solutions"
              title={
                <>
                  What we <span className="text-gradient-brand font-extrabold">build for you</span>
                </>
              }
              lead="Start on a single channel or run them together as one continuous customer experience."
            />
          </Reveal>
          <RevealGroup className="mt-10 grid gap-5 sm:grid-cols-2">
            {SOLUTIONS.map((s) => (
              <RevealItem key={s.title} className="h-full">
                <SolutionBentoCard s={s} />
              </RevealItem>
            ))}
          </RevealGroup>
        </Container>
      </Section>

      {/* 4. QUTO CHATBOT AGENT */}
      <Section
        id="quto-chatbot"
        theme="dark"
        backgroundVariant="matrix"
        intensity="subtle"
        className="scroll-mt-24 border-y border-border/60 py-10 md:py-16"
      >
        <Container>
          <QutoChatbotSection />
        </Container>
      </Section>

      {/* 5. QA, ANALYTICS & ALERTS */}
      <Section className="py-10 md:py-16">
        <Container>
          <Reveal>
            <QAAuditSection />
          </Reveal>
        </Container>
      </Section>

      {/* 6. PERFECT FOR EVERY USE CASE (Industries) */}
      <Section id="use-cases" className="scroll-mt-24 border-t border-border/60 bg-secondary/40 py-10 md:py-12 lg:py-14">
        <Container>
          <Reveal>
            <UseCasesSection />
          </Reveal>
        </Container>
      </Section>

      {/* 7. INDUSTRY-LEADING TECH — full-section fine dot field (§57) */}
      <Section
        theme="dark"
        dots
        className="border-y border-border/60 py-10 md:py-16"
      >
        <Container>
          <Reveal>
            <SectionHeader
              eyebrow="Core Architecture"
              title={
                <>
                  Industry-leading tech, built for <span className="text-gradient-brand font-extrabold">real scale</span>
                </>
              }
              lead="Low-latency voice models, enterprise RAG guardrails and fault-tolerant telephony orchestration."
            />
          </Reveal>
          <div className="mt-8">
            <Reveal>
              <IndustryTechSection />
            </Reveal>
          </div>
        </Container>
      </Section>

      {/* 8. HOW IT WORKS — light section, a calm break between the two dark
             technical sections (§11, §54); spacing/hierarchy over decoration (§14) */}
      <Section
        className="border-b border-border/60 bg-secondary/30 py-10 md:py-16"
      >
        <Container>
          <Reveal>
            <SectionHeader
              eyebrow="How it works"
              title={
                <>
                  From your first message to a <span className="text-gradient-brand font-extrabold">live agent</span>
                </>
              }
              lead="A hands-on, done-for-you process — you tell us the goal, we build and deploy the agent with you."
            />
          </Reveal>
          <div className="mt-12">
            <ProcessTimeline steps={howItWorks} />
          </div>
        </Container>
      </Section>

      {/* 9. SECURITY / YOUR DATA STAYS YOURS — Topo Field (§7, §56): infrastructure,
             architecture, security. Dark section, effect visible but subordinate.
             Grid background disabled (§Part 2) so only Three.js TopoField graphic renders. */}
      <Section
        theme="dark"
        backgroundVariant="topo"
        intensity="medium"
        dots={false}
        showGrid={false}
        className="border-b border-border/60 py-12 md:py-16"
      >
        <Container>
          <Reveal>
            <SectionHeader
              eyebrow="Private by Default"
              title={
                <>
                  Your data stays <span className="text-gradient-brand font-extrabold">yours. Always.</span>
                </>
              }
              lead="Enterprise-grade architecture built to earn trust — honest, verifiable guarantees, not fabricated seals."
            />
          </Reveal>
          <RevealGroup className="mt-8 grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
            {securityPoints.map((p, idx) => {
              const iconColor =
                idx === 0
                  ? "bg-[#4FDAF1]/15 text-[#4FDAF1] border-[#4FDAF1]/30"
                  : idx === 1
                    ? "bg-[#67B7E7]/15 text-[#67B7E7] border-[#67B7E7]/30"
                    : idx === 2
                      ? "bg-[#F79C09]/15 text-[#F79C09] border-[#F79C09]/30"
                      : "bg-[#E26B0B]/15 text-[#E26B0B] border-[#E26B0B]/30";
              return (
                <RevealItem key={p.title} className="h-full">
                  <div className="flex h-full flex-col rounded-3xl border border-border bg-card p-6 transition-all hover:border-[#4FDAF1]/50 hover:shadow-[0_0_25px_-8px_rgba(79,218,241,0.2)]">
                    <span className={cn("inline-flex size-11 items-center justify-center rounded-2xl border", iconColor)}>
                      <Lock className="size-5" />
                    </span>
                    <h3 className="mt-4 font-display text-lg font-semibold text-foreground">
                      {p.title}
                    </h3>
                    <p className="mt-2 text-sm leading-relaxed text-pretty text-muted-foreground">
                      {p.body}
                    </p>
                  </div>
                </RevealItem>
              );
            })}
          </RevealGroup>
          <div className="mt-8 flex flex-wrap items-center justify-center gap-2.5">
            {securityBadges.map((b) => (
              <Badge
                key={b}
                variant="outline"
                className="rounded-full border-border bg-card/60 px-4 py-1 text-xs font-medium text-foreground"
              >
                {b}
              </Badge>
            ))}
          </div>
        </Container>
      </Section>

      {/* 10. FAQ */}
      <Section className="py-10 md:py-16">
        <Container>
          <Reveal>
            <SectionHeader
              align="center"
              eyebrow="Frequently Asked Questions"
              title={
                <>
                  Everything you need to know about <span className="text-gradient-brand font-extrabold">AI agents</span>
                </>
              }
              lead="Direct answers on timelines, integrations, pricing structure and data security."
            />
          </Reveal>
          <div className="mt-8">
            <FAQAccordion faqs={homeFaqs} />
          </div>
        </Container>
      </Section>

      {/* Latest from the blog — Embla carousel (max 6 published posts) */}
      {latestPosts.length > 0 && (
        <Section>
          <Container>
            <Reveal>
              <SectionHeader
                align="center"
                eyebrow="From the blog"
                title={
                  <>
                    Latest insights on <span className="text-gradient-brand font-extrabold">voice &amp; AI agents</span>
                  </>
                }
                lead="Engineering guides, benchmarks and product updates from the Quto AI team."
              />
            </Reveal>
            <div className="mt-8">
              <HomeBlogCarousel posts={latestPosts} />
            </div>
            <div className="mt-8 flex justify-center">
              <Button asChild variant="outline" size="pill">
                <Link href="/blog" className="group">
                  View all articles
                  <ArrowRight className="ml-1.5 size-4 transition-transform group-hover:translate-x-1 motion-reduce:transition-none" />
                </Link>
              </Button>
            </div>
          </Container>
        </Section>
      )}

      {/* 11. FINAL CTA */}
      <CTASection />
    </>
  );
}
