"use client";

import Image from "next/image";
import { useMemo, useState } from "react";
import { ArrowRight, ChevronRight, Lock, Star } from "lucide-react";

import { GlassCard } from "@/components/shared/glass-card";
import { HeroSection } from "@/components/home/hero-section";
import { InstagramNetworkSection } from "@/components/social/instagram-network-section";
import { Button } from "@/components/ui/button";
import { ButtonLink } from "@/components/ui/button-link";
import { Input } from "@/components/ui/input";
import type { CmsFaqItem } from "@/lib/cms/types";
import type { Product } from "@/types";
import { cn } from "@/lib/utils";
import {
  isSideBySideTransformation,
  type Testimonial,
  type Transformation,
} from "@/lib/site-content/types";
import { toast } from "sonner";

function SectionHeading({
  eyebrow,
  title,
  subtitle,
  align = "center",
}: {
  eyebrow: string;
  title: string;
  subtitle?: string;
  align?: "center" | "left";
}) {
  return (
    <div
      className={cn(
        "max-w-2xl",
        align === "center" && "mx-auto text-center",
        align === "left" && "text-left",
      )}
    >
      <p className="text-primary text-xs font-semibold uppercase tracking-widest">{eyebrow}</p>
      <h2 className="font-display mt-3 text-3xl font-semibold tracking-tight text-foreground sm:text-4xl">
        {title}
      </h2>
      {subtitle ? (
        <p className="text-muted-foreground mt-3 text-base leading-relaxed sm:text-lg">
          {subtitle}
        </p>
      ) : null}
    </div>
  );
}

function ValueStrip() {
  const items = [
    { title: "Structured programming", body: "Progressions you can follow week to week." },
    { title: "Nutrition architecture", body: "Systems that match your training phase." },
    { title: "Accountability", body: "Support channels for paying members." },
  ];
  return (
    <section className="border-border/50 border-y bg-muted/15">
      <div className="ds-container ds-section py-12 sm:py-16">
        <div className="grid gap-6 md:grid-cols-3 md:gap-8">
          {items.map((item, i) => (
            <div
              key={item.title}
              className={cn(
                "animate-fade-in-up relative rounded-2xl border border-border/50 bg-card/40 p-6 backdrop-blur-sm motion-reduce:animate-none",
                i === 1 && "stagger-1",
                i === 2 && "stagger-2",
              )}
            >
              <p className="font-display text-lg font-semibold tracking-tight">{item.title}</p>
              <p className="text-muted-foreground mt-2 text-sm leading-relaxed">{item.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function BeforeAfterScrollStrip({ transformations }: { transformations: Transformation[] }) {
  const pool = useMemo(() => {
    return transformations
      .filter((t) => t.collageSrc || isSideBySideTransformation(t) || t.beforeSrc || t.afterSrc)
      .slice(0, 10);
  }, [transformations]);

  if (!pool.length) return null;

  return (
    <section className="ds-section">
      <div className="ds-container">
        <SectionHeading
          eyebrow="Proof"
          title="Real transformations"
          subtitle="Scroll through client results — collages and side-by-sides. Open the gallery for the full set."
        />

        <div className="mt-12 -mx-4 scroll-pl-4 px-4 sm:mx-0 sm:scroll-pl-0 sm:px-0">
          <div className="flex gap-4 overflow-x-auto pb-2 pt-1 snap-x snap-mandatory [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
            {pool.map((t) => (
              <GlassCard
                key={t.id}
                className="w-[min(85vw,280px)] shrink-0 snap-start overflow-hidden p-0 sm:w-[260px]"
              >
                {t.collageSrc ? (
                  <div className="relative aspect-[4/5] bg-muted">
                    <Image
                      src={t.collageSrc}
                      alt={t.title}
                      fill
                      className="object-cover object-top"
                      sizes="260px"
                    />
                  </div>
                ) : isSideBySideTransformation(t) ? (
                  <div className="grid grid-cols-2 gap-px bg-muted">
                    <div className="relative aspect-[3/4]">
                      <Image
                        src={t.beforeSrc ?? ""}
                        alt={`${t.title} before`}
                        fill
                        className="object-cover object-top"
                        sizes="130px"
                      />
                      <span className="pointer-events-none absolute bottom-2 left-2 rounded-md bg-black/60 px-2 py-0.5 text-[10px] font-medium text-white">
                        Before
                      </span>
                    </div>
                    <div className="relative aspect-[3/4]">
                      <Image
                        src={t.afterSrc ?? ""}
                        alt={`${t.title} after`}
                        fill
                        className="object-cover object-top"
                        sizes="130px"
                      />
                      <span className="pointer-events-none absolute bottom-2 right-2 rounded-md bg-black/60 px-2 py-0.5 text-[10px] font-medium text-white">
                        After
                      </span>
                    </div>
                  </div>
                ) : (
                  <div className="relative aspect-[4/5] bg-muted">
                    <Image
                      src={t.afterSrc ?? t.beforeSrc ?? ""}
                      alt={t.title}
                      fill
                      className="object-cover object-top"
                      sizes="260px"
                    />
                  </div>
                )}
                <div className="space-y-1 p-4">
                  <p className="font-display text-sm font-semibold leading-snug">{t.title}</p>
                  {t.clientName ? (
                    <p className="text-primary text-xs font-medium">{t.clientName}</p>
                  ) : null}
                  <p className="text-muted-foreground text-xs">{t.timeframe}</p>
                  {t.description ? (
                    <p className="text-muted-foreground line-clamp-2 text-xs leading-relaxed">
                      {t.description}
                    </p>
                  ) : null}
                </div>
              </GlassCard>
            ))}
            <div className="flex w-[min(72vw,200px)] shrink-0 snap-start items-stretch">
              <ButtonLink
                href="/gallery"
                variant="outline"
                className="flex min-h-[180px] flex-1 flex-col items-center justify-center gap-2 rounded-2xl text-center"
              >
                <span className="font-display text-sm font-semibold">Full gallery</span>
                <ChevronRight className="text-muted-foreground size-4" />
              </ButtonLink>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function FeaturedPlans({ products }: { products: Product[] }) {
  const plans = products.filter((p) => p.type === "program").slice(0, 3);
  return (
    <section className="ds-section border-border/40 border-t bg-muted/10">
      <div className="ds-container">
        <SectionHeading
          eyebrow="Plans"
          title="Featured coaching paths"
          subtitle="Packages plus standalone diet or training options — pick what matches your season."
        />
        <div className="mt-12 grid gap-6 lg:grid-cols-3">
          {plans.map((p, i) => (
            <div
              key={p.id}
              className={cn(
                "animate-fade-in-up motion-reduce:animate-none",
                i === 1 && "stagger-1",
                i === 2 && "stagger-2",
              )}
            >
              <GlassCard className="flex h-full flex-col overflow-hidden p-0">
                <div className="relative aspect-[16/10] overflow-hidden bg-muted">
	                  <Image
	                    src={p.image}
	                    alt={p.title}
	                    fill
	                    priority={i === 0}
	                    className={cn(
	                      "object-cover transition duration-500 hover:scale-[1.02]",
                      i === 0 && "object-[50%_10%]",
                      i === 1 && "object-[50%_20%]",
                      i === 2 && "object-top",
                    )}
	                    sizes="(max-width: 1023px) calc(100vw - 2rem), 380px"
	                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-background/85 to-transparent" />
                  {p.compareAtInr ? (
                    <span className="bg-primary text-primary-foreground absolute left-3 top-3 rounded-md px-2.5 py-1 text-xs font-semibold">
                      Save ₹{p.compareAtInr - p.priceInr}
                    </span>
                  ) : null}
                </div>
                <div className="flex flex-1 flex-col p-6">
                  <h3 className="font-display text-lg font-semibold tracking-tight">{p.title}</h3>
                  <p className="text-muted-foreground mt-2 flex-1 text-sm leading-relaxed">
                    {p.description}
                  </p>
                  <div className="mt-6 flex items-end justify-between gap-4 border-t border-border/50 pt-5">
                    <div>
                      <p className="text-muted-foreground text-xs font-medium uppercase tracking-wider">
                        From
                      </p>
                      <p className="font-display text-2xl font-semibold text-primary">
                        ₹{p.priceInr}
                      </p>
                    </div>
                    <ButtonLink href={`/programs#${p.slug}`} className="rounded-xl">
                      Details
                    </ButtonLink>
                  </div>
                </div>
              </GlassCard>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function TestimonialsCarousel({ testimonials }: { testimonials: Testimonial[] }) {
  return (
    <section className="ds-section border-border/40 border-y">
      <div className="ds-container">
        <SectionHeading
          eyebrow="Voices"
          title="What athletes say"
          subtitle="Outcomes from people who run the program like a product — consistency over hype."
        />
        <div className="mt-12 flex snap-x snap-mandatory gap-4 overflow-x-auto pb-2 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
          {testimonials.map((t) => (
            <GlassCard
              key={t.id}
              variant="blue"
              className="min-w-[min(100%,300px)] shrink-0 snap-start sm:min-w-[360px]"
            >
              <div className="flex items-center gap-3">
                <div className="relative size-11 overflow-hidden rounded-full border border-border/60">
	                  <Image src={t.image} alt={t.name} fill className="object-cover" sizes="44px" />
                </div>
                <div>
                  <p className="text-sm font-semibold">{t.name}</p>
                  <p className="text-muted-foreground text-xs">{t.role}</p>
                </div>
                <Star className="text-amber-400 ml-auto size-4 shrink-0" />
              </div>
              <p className="text-muted-foreground mt-4 text-sm leading-relaxed">“{t.quote}”</p>
              <p className="text-primary mt-4 text-xs font-semibold uppercase tracking-wider">
                {t.result}
              </p>
            </GlassCard>
          ))}
        </div>
      </div>
    </section>
  );
}

function NewsletterSection() {
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await fetch("/api/newsletter", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      if (!res.ok) throw new Error();
      toast.success("You are on the list.");
      setEmail("");
    } catch {
      toast.error("Could not subscribe — try again.");
    } finally {
      setLoading(false);
    }
  }
  return (
    <section className="ds-section">
      <div className="ds-container">
        <GlassCard className="mx-auto max-w-3xl text-center">
        <p className="text-primary text-xs font-semibold uppercase tracking-widest">Newsletter</p>
        <h3 className="font-display mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
          Weekly protocol notes
        </h3>
        <p className="text-muted-foreground mt-2 text-sm sm:text-base">
          Micro-lessons and rotation ideas — no spam.
        </p>
        <form
          onSubmit={submit}
          className="mx-auto mt-8 flex max-w-md flex-col gap-3 sm:flex-row"
        >
          <Input
            type="email"
            required
            placeholder="you@email.com"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="h-11 flex-1"
          />
          <Button type="submit" disabled={loading} className="h-11 shrink-0 rounded-xl sm:px-6">
            Subscribe
          </Button>
        </form>
        </GlassCard>
      </div>
    </section>
  );
}

function FaqPreview({ faqItems }: { faqItems: CmsFaqItem[] }) {
  const preview = faqItems.slice(0, 4);
  return (
    <section className="ds-section border-border/40 border-t bg-muted/10">
      <div className="ds-container max-w-3xl">
        <SectionHeading eyebrow="FAQ" title="Answers, fast" align="left" />
        <div className="mt-10 flex flex-col gap-3">
          {preview.map((item) => (
            <GlassCard key={item.id} className="p-5">
              <p className="text-sm font-semibold text-foreground">{item.question}</p>
              <p className="text-muted-foreground mt-2 text-sm leading-relaxed line-clamp-3">{item.answer.replace(/<[^>]+>/g, "")}</p>
            </GlassCard>
          ))}
        </div>
        <div className="mt-8">
          <ButtonLink href="/faq" variant="ghost" className="text-primary gap-1 px-0">
            View all questions
            <ArrowRight className="size-4" />
          </ButtonLink>
        </div>
      </div>
    </section>
  );
}

function PremiumContentTeaser() {
  return (
    <section className="ds-section pb-20 sm:pb-28">
      <div className="ds-container">
        <GlassCard className="flex max-w-5xl flex-col items-center gap-8 px-6 py-10 sm:mx-auto sm:flex-row sm:items-center sm:justify-between sm:px-10">
        <div className="flex max-w-lg flex-col items-center gap-4 text-center sm:flex-row sm:items-start sm:text-left">
          <div className="bg-primary/10 text-primary flex size-12 shrink-0 items-center justify-center rounded-xl">
            <Lock className="size-6" />
          </div>
          <div>
            <p className="text-primary text-xs font-semibold uppercase tracking-widest">
              Member vault
            </p>
            <h3 className="font-display mt-1 text-xl font-semibold tracking-tight sm:text-2xl">
              Protocols unlock after purchase
            </h3>
            <p className="text-muted-foreground mt-2 text-sm leading-relaxed">
              Videos, logs, and PDFs appear in your dashboard as soon as payment clears.
            </p>
          </div>
        </div>
        <ButtonLink href="/signup" size="lg" className="shrink-0 rounded-xl px-6">
          Create account
        </ButtonLink>
      </GlassCard>
      </div>
    </section>
  );
}

export function MarketingHome({
  heroBackgroundImage,
  testimonials,
  transformations,
  faqItems,
  products,
}: {
  heroBackgroundImage: string;
  testimonials: Testimonial[];
  transformations: Transformation[];
  faqItems: CmsFaqItem[];
  products: Product[];
}) {
  return (
    <>
      <HeroSection backgroundImage={heroBackgroundImage} />
      <ValueStrip />
      <BeforeAfterScrollStrip transformations={transformations} />
      <FeaturedPlans products={products} />
      <TestimonialsCarousel testimonials={testimonials} />
      <InstagramNetworkSection id="instagram" />
      <NewsletterSection />
      <FaqPreview faqItems={faqItems} />
      <PremiumContentTeaser />
    </>
  );
}
