import type { Metadata } from "next";
import Link from "next/link";
import { ArrowRight, Sparkles, Phone, MessageSquare, Bot } 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 { Button } from "@/components/ui/button";
import { site, ogBase, twitterBase } from "@/content/site";
import { BLOG_POSTS, BlogPost } from "@/content/blog";
import { blogService } from "@/lib/blog-service";
import { BlogHeroFeatured } from "@/components/blog/blog-hero-featured";
import { BlogView } from "@/components/blog/blog-view";

export const revalidate = 60; // ISR revalidation every 60 seconds (or immediately on publish)

const BLOG_META_DESCRIPTION =
  "Practical guides on AI voice agents, WhatsApp automation, conversational AI and AI-driven customer operations — from the Quto AI team.";

export const metadata: Metadata = {
  title: { absolute: "Quto AI Blog — Guides on Voice AI, WhatsApp & AI Agents" },
  description: BLOG_META_DESCRIPTION,
  keywords: [
    "voice ai blog",
    "conversational ai guides",
    "ai agents tutorials",
    "whatsapp ai automation guides",
    "sip trunking voice ai",
    "bland ai alternatives",
  ],
  alternates: {
    canonical: "/blog",
    types: {
      "application/rss+xml": "/rss.xml",
    },
  },
  openGraph: {
    ...ogBase,
    title: "Quto AI Blog — Guides on Voice AI, WhatsApp & AI Agents",
    description: BLOG_META_DESCRIPTION,
    url: `${site.url}/blog`,
  },
  twitter: {
    ...twitterBase,
    title: "Quto AI Blog — Guides on Voice AI, WhatsApp & AI Agents",
    description: BLOG_META_DESCRIPTION,
  },
};

export default async function BlogIndexPage() {
  // Authoritative data: Fetches published articles from live MongoDB Atlas
  let posts: BlogPost[] = [];
  try {
    const mongoPosts = await blogService.getPublishedPosts({ limit: 100, lean: true });
    if (mongoPosts && mongoPosts.length > 0) {
      posts = mongoPosts as unknown as BlogPost[];
    } else {
      posts = BLOG_POSTS;
    }
  } catch {
    posts = BLOG_POSTS;
  }

  const featuredPost = posts.find((p) => p.featured) || posts[0];

  const blogSchema = {
    "@context": "https://schema.org",
    "@type": "Blog",
    name: "Quto AI Blog & Insights Hub",
    description: BLOG_META_DESCRIPTION,
    url: `${site.url}/blog`,
    publisher: {
      "@type": "Organization",
      name: site.name,
      url: site.url,
    },
    blogPost: posts.map((post) => ({
      "@type": "BlogPosting",
      headline: post.title,
      description: post.excerpt,
      datePublished: post.publishedDate,
      author: {
        "@type": "Person",
        name: post.author.name,
      },
      url: `${site.url}/blog/${post.slug}`,
    })),
  };

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

  return (
    <>
      <JsonLd data={[blogSchema, breadcrumbSchema]} />

      <div className="relative pb-20 page-top-space overflow-hidden min-h-[70vh]">
        {/* Ambient background glow for hero */}
        <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>
          {/* Breadcrumbs */}
          <div className="mb-6">
            <Breadcrumbs items={[{ label: "Blog" }]} />
          </div>

          {posts.length > 0 ? (
            <>
              {/* Featured Hero Article Card */}
              {featuredPost && <BlogHeroFeatured post={featuredPost} />}

              {/* Interactive All Blogs Section */}
              <BlogView posts={posts} />
            </>
          ) : (
            /* Creative "Coming Soon" / "Insights are coming" Experience */
            <div className="py-12 md:py-20">
              <div className="mx-auto max-w-3xl text-center">
                <div className="inline-flex items-center gap-2 rounded-full border border-[#4FDAF1]/40 bg-[#4FDAF1]/10 px-3.5 py-1 text-xs font-semibold text-[#4FDAF1]">
                  <Sparkles className="h-3.5 w-3.5" />
                  <span>Quto AI Insights &amp; Engineering</span>
                </div>

                <h1 className="mt-6 font-display text-4xl font-extrabold tracking-tight text-foreground sm:text-5xl lg:text-6xl">
                  Something thoughtful is{" "}
                  <span className="text-gradient-brand">coming</span>.
                </h1>

                <p className="mt-5 text-base leading-relaxed text-muted-foreground sm:text-lg max-w-2xl mx-auto">
                  We’re preparing practical insights on AI agents, automation, voice AI,
                  WhatsApp, and conversational technology.
                </p>

                <div className="mt-8 flex items-center justify-center gap-2">
                  <span className="relative flex size-2.5">
                    <span className="absolute inline-flex size-full animate-ping rounded-full bg-[#4FDAF1] opacity-75" />
                    <span className="relative inline-flex size-2.5 rounded-full bg-[#4FDAF1]" />
                  </span>
                  <span className="text-xs font-semibold tracking-wider uppercase text-foreground/80">
                    Stay tuned
                  </span>
                </div>

                {/* Quick Topics Preview Cards */}
                <div className="mt-14 grid grid-cols-1 gap-4 sm:grid-cols-3 text-left">
                  <div className="rounded-2xl border border-border/80 bg-card/60 p-5 shadow-xs transition hover:border-[#4FDAF1]/40">
                    <div className="flex size-9 items-center justify-center rounded-xl bg-[#4FDAF1]/10 text-[#4FDAF1] mb-3">
                      <Phone className="size-4" />
                    </div>
                    <h2 className="text-sm font-bold text-foreground">Voice AI Systems</h2>
                    <p className="mt-1 text-xs text-muted-foreground leading-relaxed">
                      Sub-350ms telephony latency, SIP streaming, and interruption handling.
                    </p>
                  </div>

                  <div className="rounded-2xl border border-border/80 bg-card/60 p-5 shadow-xs transition hover:border-[#67B7E7]/40">
                    <div className="flex size-9 items-center justify-center rounded-xl bg-[#67B7E7]/10 text-[#67B7E7] mb-3">
                      <MessageSquare className="size-4" />
                    </div>
                    <h2 className="text-sm font-bold text-foreground">WhatsApp Automation</h2>
                    <p className="mt-1 text-xs text-muted-foreground leading-relaxed">
                      Official Cloud API flows, CRM sync, and automated conversational recovery.
                    </p>
                  </div>

                  <div className="rounded-2xl border border-border/80 bg-card/60 p-5 shadow-xs transition hover:border-[#F79C09]/40">
                    <div className="flex size-9 items-center justify-center rounded-xl bg-[#F79C09]/10 text-[#F79C09] mb-3">
                      <Bot className="size-4" />
                    </div>
                    <h2 className="text-sm font-bold text-foreground">Autonomous Agents</h2>
                    <p className="mt-1 text-xs text-muted-foreground leading-relaxed">
                      Enterprise security, zero data retention, and multi-channel orchestration.
                    </p>
                  </div>
                </div>

                <div className="mt-12 flex flex-wrap items-center justify-center gap-3">
                  <Button asChild variant="outline" size="pill">
                    <Link href="/about" className="group">
                      About the Team
                      <ArrowRight className="ml-1.5 size-3.5 transition-transform group-hover:translate-x-1" />
                    </Link>
                  </Button>
                  <Button asChild variant="accent" size="pill">
                    <Link href="/contact">
                      Contact Quto AI
                    </Link>
                  </Button>
                </div>
              </div>
            </div>
          )}
        </Container>
      </div>

      <CTASection />
    </>
  );
}
