import Link from "next/link";
import { Zap, TrendingUp, FileText, Download, Clock, Shield, Star, ChevronRight, Video, Brain, Sparkles, Check } from "lucide-react";
import { LogoIcon } from "@/components/shared/logo";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { HeroSection, AnimatedSection, StaggerCard, HowItWorksAnimation } from "@/components/marketing/hero-section";

const features = [
  { icon: Brain, title: "AI Transcript Analysis", description: "Whisper-powered transcription with zero human intervention. Handles accents, background noise, and 50+ languages.", color: "from-violet-500/20 to-violet-600/10", iconColor: "text-violet-400", border: "border-violet-500/20" },
  { icon: TrendingUp, title: "Virality Score Engine", description: "Our model scores every segment on hooks, story arc, emotional peaks, quotability, and audience retention signals.", color: "from-cyan-500/20 to-cyan-600/10", iconColor: "text-cyan-400", border: "border-cyan-500/20" },
  { icon: FileText, title: "Full Transcript Export", description: "Download complete transcripts with timestamps. Perfect for show notes, blogs, and cross-platform repurposing.", color: "from-emerald-500/20 to-emerald-600/10", iconColor: "text-emerald-400", border: "border-emerald-500/20" },
  { icon: Clock, title: "Precise Timestamps", description: "Get exact start/end times for every clip suggestion. Jump straight to editing without rewatching the full video.", color: "from-orange-500/20 to-orange-600/10", iconColor: "text-orange-400", border: "border-orange-500/20" },
  { icon: Download, title: "Instant Export", description: "Download clip data, transcript snippets, and virality reports. Integrate directly with your editing workflow.", color: "from-pink-500/20 to-pink-600/10", iconColor: "text-pink-400", border: "border-pink-500/20" },
  { icon: Shield, title: "Privacy First", description: "Your videos are processed ephemerally. No storage, no training on your content, GDPR compliant by design.", color: "from-blue-500/20 to-blue-600/10", iconColor: "text-blue-400", border: "border-blue-500/20" },
];

const steps = [
  { step: "01", icon: Video, title: "Paste YouTube URL", description: "Drop any public YouTube link — podcasts, interviews, tutorials, vlogs. Our system fetches the audio automatically.", color: "text-red-400", bg: "bg-red-500/10", border: "border-red-500/20" },
  { step: "02", icon: Brain, title: "AI Analyzes Content", description: "Our pipeline transcribes audio, detects emotional peaks, quotable moments, story arcs, and viral-worthy segments.", color: "text-violet-400", bg: "bg-violet-500/10", border: "border-violet-500/20" },
  { step: "03", icon: Sparkles, title: "Get Viral Clips", description: "Receive ranked clip suggestions with timestamps, transcript snippets, virality scores, and reasons — ready to cut.", color: "text-cyan-400", bg: "bg-cyan-500/10", border: "border-cyan-500/20" },
];

interface MarketingTestimonial {
  id: number;
  name: string;
  role: string;
  content: string;
  rating: number;
  avatar: string;
}

const fallbackTestimonials: MarketingTestimonial[] = [
  { id: 1, name: "Rohit Mehta", role: "YouTube Creator · 280K subscribers", content: "ReelsCutter cut my editing prep time from 3 hours to 20 minutes per video. The virality scores are scary accurate.", rating: 5, avatar: "RM" },
  { id: 2, name: "Kavya Reddy", role: "Content Strategist @ GrowthMedia", content: "We process 30+ client videos a week. The Pro Max plan with API access was a game-changer for our workflow automation.", rating: 5, avatar: "KR" },
  { id: 3, name: "Aditya Nair", role: "Podcast Host · The Startup Files", content: "Every episode is 90 minutes. ReelsCutter finds the 5-6 clips that blow up on Instagram. Saved our social strategy.", rating: 5, avatar: "AN" },
];

async function getTestimonials(): Promise<MarketingTestimonial[]> {
  const base = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000";
  try {
    const response = await fetch(`${base}/testimonials`, { cache: "no-store" });
    if (!response.ok) return fallbackTestimonials;
    const data = (await response.json()) as MarketingTestimonial[];
    return data.length > 0 ? data : [];
  } catch {
    return fallbackTestimonials;
  }
}

interface MarketingFaq {
  id: number;
  question: string;
  answer: string;
  sort_order: number;
}

interface MarketingPlan {
  id: number;
  plan_key: string;
  name: string;
  description: string;
  price_monthly: number | null;
  price_yearly: number | null;
  cta_label: string;
  cta_href: string;
  features: { label: string; included: boolean }[];
  is_popular: boolean;
}

const fallbackPlans: MarketingPlan[] = [
  {
    id: 1,
    plan_key: "free",
    name: "Free",
    description: "Try ReelsCutter risk-free",
    price_monthly: 0,
    price_yearly: 0,
    cta_label: "Get Started Free",
    cta_href: "/signup",
    features: [
      { label: "1 YouTube video per day", included: true },
      { label: "Max video length: 15 minutes", included: true },
      { label: "Watermarked export", included: true },
    ],
    is_popular: false,
  },
  {
    id: 2,
    plan_key: "pro",
    name: "Pro",
    description: "For serious content creators",
    price_monthly: 799,
    price_yearly: 6990,
    cta_label: "Upgrade to Pro",
    cta_href: "/signup?plan=pro",
    features: [
      { label: "5 YouTube links per day", included: true },
      { label: "Max video length: 20 minutes", included: true },
      { label: "Download transcript", included: true },
    ],
    is_popular: true,
  },
  {
    id: 3,
    plan_key: "pro_max",
    name: "Pro Max",
    description: "For agencies & power users",
    price_monthly: null,
    price_yearly: null,
    cta_label: "Contact Us",
    cta_href: "/contact",
    features: [
      { label: "Unlimited YouTube links", included: true },
      { label: "API access", included: true },
      { label: "Dedicated account manager", included: true },
    ],
    is_popular: false,
  },
];

async function getFaqs(): Promise<MarketingFaq[]> {
  const base = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000";
  try {
    const response = await fetch(`${base}/faqs`, { cache: "no-store" });
    if (!response.ok) return [];
    return (await response.json()) as MarketingFaq[];
  } catch {
    return [];
  }
}

async function getPlans(): Promise<MarketingPlan[]> {
  const base = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000";
  try {
    const response = await fetch(`${base}/plans`, { cache: "no-store" });
    if (!response.ok) return fallbackPlans;
    const data = (await response.json()) as MarketingPlan[];
    return data.length > 0 ? data : [];
  } catch {
    return fallbackPlans;
  }
}

export default async function HomePage() {
  const [testimonials, faqs, plans] = await Promise.all([getTestimonials(), getFaqs(), getPlans()]);

  return (
    <div className="relative overflow-hidden">
      <div className="fixed inset-0 bg-radial-violet pointer-events-none" />
      <div className="fixed inset-0 bg-grid pointer-events-none opacity-50" />

      {/* HERO — client component for animations */}
      <HeroSection />

      {/* HOW IT WORKS */}
      <section id="how-it-works" className="py-24 px-4">
        <div className="container mx-auto max-w-6xl">
          <AnimatedSection className="text-center mb-16">
            <Badge className="bg-cyan-500/15 text-cyan-300 border-cyan-500/30 mb-4">Simple 3-Step Process</Badge>
            <h2 className="text-3xl md:text-4xl font-bold mb-4">
              From URL to Viral Clips in <span className="gradient-text">Under 2 Minutes</span>
            </h2>
            <p className="text-zinc-400 max-w-xl mx-auto">No software to install. No editing skills required.</p>
          </AnimatedSection>

          <HowItWorksAnimation />

          <div className="grid md:grid-cols-3 gap-8">
            {steps.map((step, i) => (
              <StaggerCard key={i} delay={i * 0.15} className={`glass-card-hover p-8 text-center border ${step.border}`}>
                <div className={`w-14 h-14 rounded-2xl ${step.bg} border ${step.border} flex items-center justify-center mx-auto mb-4`}>
                  <step.icon className={`w-7 h-7 ${step.color}`} />
                </div>
                <div className="text-xs font-mono text-zinc-600 mb-2">{step.step}</div>
                <h3 className="text-lg font-semibold text-white mb-3">{step.title}</h3>
                <p className="text-sm text-zinc-400 leading-relaxed">{step.description}</p>
              </StaggerCard>
            ))}
          </div>
        </div>
      </section>

      {/* FEATURES */}
      <section id="features" className="py-24 px-4 bg-white/[0.02]">
        <div className="container mx-auto max-w-6xl">
          <AnimatedSection className="text-center mb-16">
            <Badge className="bg-violet-500/15 text-violet-300 border-violet-500/30 mb-4">Everything You Need</Badge>
            <h2 className="text-3xl md:text-4xl font-bold mb-4">
              Built for <span className="gradient-text">Serious Creators</span>
            </h2>
          </AnimatedSection>
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
            {features.map((feature, i) => (
              <StaggerCard key={i} delay={i * 0.08} className={`glass-card-hover p-6 bg-gradient-to-br ${feature.color} border ${feature.border}`}>
                <feature.icon className={`w-8 h-8 ${feature.iconColor} mb-4`} />
                <h3 className="text-base font-semibold text-white mb-2">{feature.title}</h3>
                <p className="text-sm text-zinc-400 leading-relaxed">{feature.description}</p>
              </StaggerCard>
            ))}
          </div>
        </div>
      </section>

      {/* PLANS */}
      <section className="py-24 px-4">
        <div className="container mx-auto max-w-6xl text-center">
          <AnimatedSection className="mb-12">
            <Badge className="bg-emerald-500/15 text-emerald-300 border-emerald-500/30 mb-4">Plans</Badge>
            <h2 className="text-3xl md:text-4xl font-bold mb-4">
              Simple, <span className="gradient-text">Transparent Pricing</span>
            </h2>
            <p className="text-zinc-400 max-w-xl mx-auto">Start free. Scale as your content does.</p>
          </AnimatedSection>

          {plans.length > 0 && (
            <div className="grid md:grid-cols-3 gap-6 mb-10">
              {plans.map((plan, i) => (
                <StaggerCard
                  key={plan.id}
                  delay={i * 0.1}
                  className={`glass-card p-6 text-left border ${
                    plan.is_popular ? "border-violet-500/50 glow-violet" : "border-white/10"
                  }`}
                >
                  <div className="flex items-start justify-between gap-3 mb-5">
                    <div>
                      <h3 className="text-lg font-bold text-white">{plan.name}</h3>
                      <p className="text-xs text-zinc-500 mt-1">{plan.description}</p>
                    </div>
                    {plan.is_popular && (
                      <Badge className="bg-violet-500/15 text-violet-300 border-violet-500/30 text-xs">
                        Popular
                      </Badge>
                    )}
                  </div>

                  <div className="mb-5">
                    {plan.price_monthly === null ? (
                      <div className="text-2xl font-black text-white">Custom</div>
                    ) : (
                      <div className="flex items-baseline gap-1">
                        <span className="text-3xl font-black text-white">₹{plan.price_monthly}</span>
                        <span className="text-sm text-zinc-500">/mo</span>
                      </div>
                    )}
                    {plan.price_yearly !== null && plan.price_yearly > 0 && (
                      <p className="text-xs text-zinc-600 mt-1">₹{plan.price_yearly}/year</p>
                    )}
                  </div>

                  <ul className="space-y-2.5 mb-6">
                    {plan.features.slice(0, 5).map((feature) => (
                      <li key={feature.label} className="flex items-center gap-2 text-sm">
                        <Check className={`w-4 h-4 flex-shrink-0 ${feature.included ? "text-emerald-400" : "text-zinc-700"}`} />
                        <span className={feature.included ? "text-zinc-300" : "text-zinc-600"}>{feature.label}</span>
                      </li>
                    ))}
                  </ul>

                  <Link href={plan.cta_href}>
                    <Button
                      className={`w-full h-10 ${
                        plan.is_popular
                          ? "bg-gradient-to-r from-violet-600 to-violet-500 text-white border-0"
                          : "bg-white/8 hover:bg-white/12 text-white border border-white/12"
                      }`}
                    >
                      {plan.cta_label}
                    </Button>
                  </Link>
                </StaggerCard>
              ))}
            </div>
          )}

          <AnimatedSection>
            <Link href="/pricing">
              <Button size="lg" variant="outline" className="bg-white/5 border-white/10 text-zinc-200 hover:bg-white/10 hover:text-white px-8">
                View All Plans <ChevronRight className="w-4 h-4 ml-1" />
              </Button>
            </Link>
          </AnimatedSection>
        </div>
      </section>

      {/* TESTIMONIALS */}
      {testimonials.length > 0 && (
        <section className="py-24 px-4 bg-white/[0.02]">
          <div className="container mx-auto max-w-6xl">
            <AnimatedSection className="text-center mb-16">
              <h2 className="text-3xl md:text-4xl font-bold mb-4">
                Loved by <span className="gradient-text">Creators Like You</span>
              </h2>
            </AnimatedSection>
            <div className="grid md:grid-cols-3 gap-6">
              {testimonials.map((t, i) => (
                <StaggerCard key={t.id} delay={i * 0.1} className="glass-card p-6">
                  <div className="flex items-center gap-1 mb-4">
                    {[...Array(t.rating)].map((_, j) => <Star key={j} className="w-4 h-4 fill-yellow-400 text-yellow-400" />)}
                  </div>
                  <p className="text-zinc-300 text-sm leading-relaxed mb-6">&ldquo;{t.content}&rdquo;</p>
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-full bg-gradient-to-br from-violet-600 to-cyan-500 flex items-center justify-center text-sm font-bold text-white">{t.avatar}</div>
                    <div>
                      <div className="text-sm font-semibold text-white">{t.name}</div>
                      <div className="text-xs text-zinc-500">{t.role}</div>
                    </div>
                  </div>
                </StaggerCard>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* FAQ */}
      <section className="py-24 px-4">
        <div className="container mx-auto max-w-3xl">
          <AnimatedSection className="text-center mb-12">
            <h2 className="text-3xl md:text-4xl font-bold mb-4">
              Frequently Asked <span className="gradient-text">Questions</span>
            </h2>
          </AnimatedSection>
          <Accordion className="space-y-3">
            {faqs.map((faq) => (
              <AccordionItem key={faq.id} value={faq.id} className="glass-card border-white/8 px-6 rounded-xl">
                <AccordionTrigger className="text-left text-sm font-medium text-zinc-200 hover:text-white hover:no-underline py-5">
                  {faq.question}
                </AccordionTrigger>
                <AccordionContent className="text-sm text-zinc-400 leading-relaxed pb-5">
                  {faq.answer}
                </AccordionContent>
              </AccordionItem>
            ))}
          </Accordion>
        </div>
      </section>

      {/* BOTTOM CTA */}
      <section className="py-24 px-4">
        <div className="container mx-auto max-w-4xl">
          <AnimatedSection className="relative glass-card p-12 text-center overflow-hidden">
            <div className="absolute inset-0 bg-gradient-to-br from-violet-600/10 via-transparent to-cyan-600/10 pointer-events-none" />
            <LogoIcon size={40} className="mx-auto mb-4" />
            <h2 className="text-3xl md:text-4xl font-bold mb-4">
              Ready to Find Your Next <span className="gradient-text-hero">Viral Reel?</span>
            </h2>
            <p className="text-zinc-400 mb-8 max-w-lg mx-auto">
              Join 2,400+ creators who save hours every week. Free forever plan available.
            </p>
            <Link href="/signup">
              <Button size="lg" className="bg-gradient-to-r from-violet-600 to-cyan-500 hover:opacity-90 text-white border-0 shadow-xl shadow-violet-900/30 px-8 h-12">
                <Zap className="w-4 h-4 mr-2" />
                Start Free — No Card Needed
              </Button>
            </Link>
            <div className="flex flex-wrap justify-center gap-6 mt-8 text-xs text-zinc-500">
              {["Free plan forever", "No credit card", "Cancel anytime", "GDPR compliant"].map((t) => (
                <div key={t} className="flex items-center gap-1.5">
                  <Check className="w-3.5 h-3.5 text-emerald-500" />
                  {t}
                </div>
              ))}
            </div>
          </AnimatedSection>
        </div>
      </section>
    </div>
  );
}
