"use client";

import FAQs from "@/features/marketing/faqs";
import { cn } from "@/lib/utils";
import type { BlogCategory, BlogPost } from "@/lib/public-blog";
import { resolvePublicMediaUrl } from "@/lib/public-blog";
import { ArrowRight, Award, Calendar, Clock, FileEdit, MapPin, MessageCircle } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useMemo, useState } from "react";
import underlineImage from "@/assets/icons/underline.svg";

type CarouselSlide = {
  id: string;
  src: string;
  alt: string;
  caption: string;
  href: string;
};

const DEFAULT_FEATURE_IMAGE = "/services/feature-storefront.jpg";

function postsToSlides(posts: BlogPost[]): CarouselSlide[] {
  return posts.map((post) => ({
    id: post._id,
    src: resolvePublicMediaUrl(post.coverImage) || DEFAULT_FEATURE_IMAGE,
    alt: post.title,
    caption: post.title,
    href: `/blogs/${post.slug}`,
  }));
}

const GUARANTEE_ITEMS = [
  {
    icon: Award,
    title: "Satisfaction Guarantee",
    body: "We stand behind our platform with responsive support and a commitment to your success.",
  },
  {
    icon: FileEdit,
    title: "Free Quotes",
    body: "Understand pricing and scope up front so you can plan your rollout with confidence.",
  },
  {
    icon: MapPin,
    title: "Local Professionals",
    body: "Work with a team that understands regional logistics, compliance, and market nuances.",
  },
  {
    icon: Clock,
    title: "Fast 24-Hour Service",
    body: "Get answers quickly when issues arise—your operations should never wait on us.",
  },
  {
    icon: Calendar,
    title: "Flexible Appointments",
    body: "Schedule demos and onboarding sessions that fit your calendar, not the other way around.",
  },
  {
    icon: MessageCircle,
    title: "100% Commitment-Free",
    body: "Explore features and workflows before you commit—no pressure, no long-term lock-in.",
  },
] as const;

type Props = {
  categories: BlogCategory[];
  blogs: BlogPost[];
};

export function ServicesMarketingPage({ categories, blogs }: Props) {
  const [selectedCategorySlug, setSelectedCategorySlug] = useState("");

  const categoryTabs = useMemo(() => {
    if (categories.length > 0) return categories;
    const seen = new Map<string, BlogCategory>();
    for (const b of blogs) {
      const c = b.category;
      if (c?.slug) seen.set(c.slug, c);
    }
    return Array.from(seen.values());
  }, [categories, blogs]);

  const tabs = useMemo(
    () => [{ slug: "", label: "All" }, ...categoryTabs.map((c) => ({ slug: c.slug, label: c.name }))],
    [categoryTabs]
  );

  const filteredPosts = useMemo(() => {
    if (!selectedCategorySlug) return blogs;
    return blogs.filter((b) => b.category?.slug === selectedCategorySlug);
  }, [blogs, selectedCategorySlug]);

  const slides = useMemo((): CarouselSlide[] => {
    if (filteredPosts.length > 0) return postsToSlides(filteredPosts);
    return [
      {
        id: "empty",
        src: DEFAULT_FEATURE_IMAGE,
        alt: "Blog",
        caption:
          selectedCategorySlug
            ? "No published posts in this category yet. Publish from Super Admin to show them here."
            : "No published blog posts yet. Publish from Super Admin to feature them on this page.",
        href: "/blogs",
      },
    ];
  }, [filteredPosts, selectedCategorySlug]);

  const onTabChange = (slug: string) => {
    setSelectedCategorySlug(slug);
  };

  return (
    <div className="bg-white">
      {/* Hero: Features */}
      <section className="container max-w-6xl pt-12 pb-8 text-center">
        <h1 className="text-4xl font-bold tracking-tight text-[#003D6B] md:text-5xl flex flex-col items-center ">

          Features


          <Image src={underlineImage} alt="underline" width={100} height={100} />
        </h1>
        <p className="mx-auto mt-5 max-w-3xl text-base leading-relaxed text-slate-600 md:text-lg">
          Explore a spectrum of cutting-edge solutions tailored to elevate your business. Our features
          are designed to meet the diverse needs of modern commerce.
        </p>

        <div className="mt-10 flex flex-wrap items-center justify-center gap-3 md:gap-4">
          {tabs.map(({ slug, label }) => {
            const active = selectedCategorySlug === slug;
            return (
              <button
                key={slug || "all"}
                type="button"
                onClick={() => onTabChange(slug)}
                className={cn(
                  "rounded-full px-5 py-2.5 text-sm font-semibold transition-colors md:px-7 md:py-3 md:text-base",
                  active
                    ? "bg-[#003D6B] text-white shadow-sm"
                    : "border-2 border-[#007BFF]/35 bg-white text-[#003D6B] hover:border-[#007BFF]/60"
                )}
              >
                {label}
              </button>
            );
          })}
        </div>
      </section>

      {/* Feature cards */}
      <section className="container max-w-6xl pb-6">
        <div className="grid gap-4 pb-2 md:grid-cols-2 md:gap-6 lg:grid-cols-3">
          {slides.map((s) => (
            <div
              key={`${selectedCategorySlug}-${s.id}-${s.href}`}
              className="relative min-h-[280px] overflow-hidden rounded-t-[28px] bg-slate-200 shadow-sm md:min-h-[340px]"
            >
              <Image
                src={s.src}
                alt={s.alt}
                fill
                className="object-cover"
                sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
              />
              <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/25 to-transparent" />
              <div className="absolute inset-x-0 bottom-0 flex flex-col gap-3 p-5 text-left md:p-7">
                <p className="max-w-xl text-sm font-medium leading-snug text-white md:text-base">
                  {s.caption}
                </p>
                <Link
                  href={s.href}
                  className="inline-flex w-fit items-center gap-2 rounded-full border border-white px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-white/10"
                >
                  Learn More
                  <ArrowRight className="size-4" aria-hidden />
                </Link>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Satisfaction guarantee — notched panel */}
      <section className="px-4 pb-16 pt-4 md:px-6">
        <div
          className="relative mx-auto max-w-6xl overflow-hidden bg-[#003D6B] px-6 py-12 text-white md:px-14 md:py-16"
          style={{
            clipPath:
              "polygon(0 32px, 32px 0, calc(100% - 32px) 0, 100% 32px, 100% 100%, 0 100%)",
          }}
        >
          <div className="mb-10 flex flex-col gap-6 md:flex-row md:items-start md:justify-between md:gap-12">
            <h2 className="max-w-md text-2xl text-white font-bold leading-tight md:text-3xl lg:text-4xl">
              Fast, Friendly, and Satisfaction Guarantee
            </h2>
            <p className="max-w-xl text-sm leading-relaxed text-white/90 md:text-base">
              From onboarding to day-to-day operations, we focus on clear communication, practical
              training, and support that respects your time—so your team can stay focused on growing
              sales and serving customers.
            </p>
          </div>

          <div className="grid gap-8 sm:grid-cols-2 lg:grid-cols-3 lg:gap-x-10 lg:gap-y-10">
            {GUARANTEE_ITEMS.map(({ icon: Icon, title, body }) => (
              <div key={title} className="flex gap-4">
                <div className="flex size-11 shrink-0 items-center justify-center rounded-full border border-white/30 bg-white/10">
                  <Icon className="size-5 text-white" strokeWidth={1.75} aria-hidden />
                </div>
                <div>
                  <h3 className="font-bold text-white">{title}</h3>
                  <p className="mt-1 text-sm leading-relaxed text-white/85">{body}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section className="border-t border-slate-100 bg-[#F8F9FA]/80 py-16 md:py-20">
        <div className="container max-w-6xl">
          <div className="flex flex-col gap-10 md:flex-row md:gap-16">
            <div className="shrink-0 md:w-[38%]">
              <h2 className="text-3xl font-bold leading-tight text-[#003D6B] md:text-4xl">
                Frequently Asked Questions
              </h2>
              <p className="mt-6 text-slate-700">
                Still need help?{" "}
                <Link href="/contact-us" className="font-semibold text-[#007BFF] underline">
                  Get Help Now
                </Link>
              </p>
            </div>
            <div className="min-w-0 flex-1 rounded-2xl bg-white p-2 shadow-sm md:p-4">
              <FAQs />
            </div>
          </div>
        </div>
      </section>

      {/* Blog + categories */}
      {/* <section className="container max-w-6xl py-16 md:py-20">
        <div className="mb-8 text-center md:text-left">
          <h2 className="text-3xl font-bold text-[#003D6B] md:text-4xl">From the blog</h2>
          <p className="mt-3 max-w-2xl text-slate-600">
            Tips, product updates, and guides from our team—browse by category or read the latest
            posts.
          </p>
        </div>

        <div className="mb-10 flex flex-wrap justify-center gap-2 md:justify-start">
          <Link
            href="/blogs"
            className="rounded-full border-2 border-[#007BFF]/35 bg-[#003D6B] px-4 py-2 text-sm font-semibold text-white"
          >
            All categories
          </Link>
          {categories.map((cat) => (
            <Link
              key={cat._id}
              href={`/blogs?category=${cat.slug}`}
              className="rounded-full border-2 border-[#007BFF]/35 bg-white px-4 py-2 text-sm font-semibold text-[#003D6B] transition-colors hover:border-[#007BFF]/60"
            >
              {cat.name}
            </Link>
          ))}
        </div>

        {blogs.length === 0 ? (
          <div className="rounded-2xl border border-dashed border-slate-200 bg-[#F8F9FA]/50 p-10 text-center text-slate-600">
            No published articles yet. Visit the{" "}
            <Link href="/blogs" className="font-medium text-[#007BFF] underline">
              blog
            </Link>{" "}
            when your team has published posts.
          </div>
        ) : (
          <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
            {blogs.map((post) => (
              <article
                key={post._id}
                className="flex flex-col overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm transition-shadow hover:shadow-md"
              >
                <div className="flex flex-1 flex-col p-5">
                  <p className="text-xs font-semibold uppercase tracking-wide text-[#007BFF]">
                    {post.category?.name || "General"}
                  </p>
                  <h3 className="mt-2 text-lg font-bold text-[#003D6B]">{post.title}</h3>
                  <p className="mt-2 line-clamp-3 flex-1 text-sm text-slate-600">
                    {post.excerpt || post.content}
                  </p>
                  <Link
                    href={`/blogs/${post.slug}`}
                    className="mt-4 inline-flex items-center gap-1 text-sm font-semibold text-[#007BFF]"
                  >
                    Read article
                    <ArrowRight className="size-4" />
                  </Link>
                </div>
              </article>
            ))}
          </div>
        )}

        <div className="mt-10 text-center md:text-left">
          <Link
            href="/blogs"
            className="inline-flex items-center gap-2 font-semibold text-[#007BFF] underline"
          >
            View all posts
            <ArrowRight className="size-4" />
          </Link>
        </div>
      </section> */}
    </div>
  );
}
