import { createFileRoute } from "@tanstack/react-router";
import { queryOptions, useSuspenseQuery } from "@tanstack/react-query";
import { Star, Users, Award, Lock, CheckCircle2, ChevronDown, Zap, Shield, TrendingUp, BookOpen, PlayCircle } from "lucide-react";
import { useState } from "react";
import { Link } from "@tanstack/react-router";

import { getLandingData } from "@/lib/course.functions";
import { Header } from "@/components/Header";
import { VideoEmbed } from "@/components/VideoEmbed";
import { LockedBadge, PreviewBadge } from "@/components/LockedBadge";
import { StudentProofs } from "@/components/StudentProofs";
import { useEffect } from "react";
import { trackEvent } from "@/lib/pixels";

const landingQuery = queryOptions({
  queryKey: ["landing"],
  queryFn: () => getLandingData(),
});

export const Route = createFileRoute("/")({
  head: () => ({
    meta: [
      { title: "Binary Options Mastery Course 2026 — Trade with Confidence" },
      { name: "description", content: "6 modules. Live trading examples. Lifetime access. Learn Binary Options trading from beginner to advanced in Bangla & English." },
      { property: "og:title", content: "Binary Options Mastery Course 2026" },
      { property: "og:description", content: "Master Binary Options trading from zero to pro. Enroll today." },
    ],
  }),
  loader: ({ context }) => context.queryClient.ensureQueryData(landingQuery),
  component: LandingPage,
  errorComponent: ({ error }) => <div className="p-8 text-center">{error.message}</div>,
});

function formatBDT(n: number) { return `৳${Number(n).toLocaleString("en-BD")}`; }

function LandingPage() {
  const { data } = useSuspenseQuery(landingQuery);
  const { course, modules, lessons, testimonials, faqs, settings, proofs } = data;
  useEffect(() => { trackEvent("ViewContent", { content_name: course?.title, content_category: "course", value: Number(course?.discount_price ?? course?.price ?? 0), currency: "BDT" }); }, [course?.id]);

  if (!course) {
    return (
      <div className="min-h-screen">
        <Header />
        <div className="grid place-items-center py-32 text-muted-foreground">No course published yet.</div>
      </div>
    );
  }

  const price = course.discount_price ?? course.price;
  const hasDiscount = course.discount_price != null && Number(course.discount_price) < Number(course.price);
  const benefits = Array.isArray(course.benefits) ? course.benefits as string[] : [];

  return (
    <div className="min-h-screen">
      <Header />

      {/* HERO */}
      <section className="relative overflow-hidden bg-hero-radial">
        <div className="mx-auto grid max-w-7xl gap-10 px-4 py-12 md:py-20 lg:grid-cols-2 lg:items-center">
          <div className="space-y-6">
            <div className="inline-flex items-center gap-2 rounded-full border border-primary/30 bg-primary/10 px-3 py-1 text-xs font-medium text-primary">
              <Zap className="h-3 w-3" /> 2026 Edition — Updated Strategies
            </div>
            <h1 className="font-display text-4xl font-bold leading-[1.05] tracking-tight md:text-5xl lg:text-6xl">
              {course.title.split(" ").slice(0, -2).join(" ")}{" "}
              <span className="text-gradient-primary">{course.title.split(" ").slice(-2).join(" ")}</span>
            </h1>
            <p className="text-lg text-muted-foreground md:text-xl">{course.subtitle}</p>

            <div className="flex flex-wrap items-center gap-5 text-sm">
              <div className="flex items-center gap-1.5">
                {Array.from({ length: 5 }).map((_, i) => (
                  <Star key={i} className={`h-4 w-4 ${i < Math.round(Number(course.rating)) ? "fill-gold text-gold" : "text-muted"}`} />
                ))}
                <span className="ml-1 font-semibold">{course.rating}</span>
                <span className="text-muted-foreground">/ 5.0</span>
              </div>
              <div className="flex items-center gap-1.5 text-muted-foreground">
                <Users className="h-4 w-4 text-primary" /> {course.student_count.toLocaleString()} students
              </div>
              <div className="flex items-center gap-1.5 text-muted-foreground">
                <Award className="h-4 w-4 text-gold" /> Instructor: {course.instructor_name}
              </div>
            </div>

            <div className="flex flex-wrap items-end gap-4 pt-2">
              <div className="flex items-baseline gap-2">
                {hasDiscount && <span className="text-base text-muted-foreground line-through">{formatBDT(Number(course.price))}</span>}
                <span className="text-4xl font-bold text-gradient-gold">{formatBDT(Number(price))}</span>
              </div>
              {hasDiscount && (
                <span className="rounded-full bg-destructive/20 px-3 py-1 text-xs font-semibold text-destructive">
                  {Math.round((1 - Number(course.discount_price) / Number(course.price)) * 100)}% OFF
                </span>
              )}
            </div>

            <div className="flex flex-col gap-3 pt-2 sm:flex-row">
              <a href="#buy" className="rounded-xl bg-gradient-primary px-6 py-4 text-center font-semibold text-primary-foreground shadow-glow transition hover:scale-[1.02]">
                Enroll Now — {formatBDT(Number(price))}
              </a>
              <a href="#intro" className="inline-flex items-center justify-center gap-2 rounded-xl border border-border bg-card px-6 py-4 font-semibold hover:bg-muted">
                <PlayCircle className="h-5 w-5" /> Watch Intro
              </a>
            </div>
          </div>

          <div className="relative">
            <div className="absolute -inset-4 rounded-3xl bg-gradient-primary opacity-20 blur-3xl" />
            <div className="relative overflow-hidden rounded-2xl border border-border shadow-card">
              {course.thumbnail_url ? (
                <img src={course.thumbnail_url} alt={course.title} className="aspect-video w-full object-cover" loading="eager" />
              ) : (
                <div className="grid aspect-video place-items-center bg-muted text-muted-foreground">No thumbnail</div>
              )}
              <div className="absolute left-4 top-4 rounded-full bg-black/60 px-3 py-1 text-xs font-semibold backdrop-blur">Course Preview</div>
            </div>
          </div>
        </div>
      </section>

      {/* INTRO VIDEO */}
      <section id="intro" className="border-t border-border/40 bg-card/30 py-16">
        <div className="mx-auto max-w-4xl px-4">
          <div className="mb-6 text-center">
            <h2 className="font-display text-3xl font-bold md:text-4xl">Free Introduction Video</h2>
            <p className="mt-2 text-muted-foreground">Watch this preview to see what you'll learn inside.</p>
          </div>
          <VideoEmbed url={course.intro_video_url} poster={course.thumbnail_url ?? undefined} />
        </div>
      </section>

      {/* MODULES */}
      <section id="modules" className="py-20">
        <div className="mx-auto max-w-5xl px-4">
          <div className="mb-10 text-center">
            <h2 className="font-display text-3xl font-bold md:text-4xl">Course Curriculum</h2>
            <p className="mt-2 text-muted-foreground">
              {modules.length} modules · {lessons.length} lessons · Lifetime access
            </p>
          </div>
          <div className="space-y-4">
            {modules.map((m) => {
              const ml = lessons.filter((l) => l.module_id === m.id);
              return (
                <details key={m.id} open className="group rounded-2xl border border-border bg-card overflow-hidden">
                  <summary className="flex cursor-pointer list-none items-center justify-between gap-4 p-5 hover:bg-muted/40">
                    <div className="flex items-center gap-3">
                      <div className="grid h-10 w-10 place-items-center rounded-lg bg-gradient-primary text-sm font-bold text-primary-foreground">{m.position}</div>
                      <div>
                        <h3 className="font-semibold">{m.title}</h3>
                        <p className="text-xs text-muted-foreground">{ml.length} lessons</p>
                      </div>
                    </div>
                    <ChevronDown className="h-5 w-5 text-muted-foreground transition group-open:rotate-180" />
                  </summary>
                  <ul className="divide-y divide-border border-t border-border">
                    {ml.map((l) => {
                      const locked = !l.is_free_preview;
                      return (
                        <li key={l.id} className={`flex items-center justify-between gap-3 px-5 py-3 ${locked ? "bg-muted/20" : ""}`}>
                          <div className="flex min-w-0 items-center gap-3">
                            {locked ? (
                              <Lock className="h-4 w-4 shrink-0 text-warning" />
                            ) : (
                              <PlayCircle className="h-4 w-4 shrink-0 text-primary" />
                            )}
                            <span className={`truncate text-sm ${locked ? "text-muted-foreground" : "text-foreground"}`}>{l.title}</span>
                          </div>
                          <div className="flex shrink-0 items-center gap-2">
                            {locked ? <LockedBadge /> : <PreviewBadge />}
                            <span className="text-xs text-muted-foreground">{Math.round(l.duration_seconds / 60)}m</span>
                          </div>
                        </li>
                      );
                    })}
                  </ul>
                </details>
              );
            })}
          </div>
        </div>
      </section>

      {/* BENEFITS */}
      <section id="benefits" className="border-t border-border/40 bg-card/30 py-20">
        <div className="mx-auto max-w-5xl px-4">
          <div className="mb-10 text-center">
            <h2 className="font-display text-3xl font-bold md:text-4xl">What You'll Master</h2>
            <p className="mt-2 text-muted-foreground">Real outcomes you can apply on day 1.</p>
          </div>
          <div className="grid gap-4 md:grid-cols-2">
            {benefits.map((b, i) => (
              <div key={i} className="flex items-start gap-3 rounded-xl border border-border bg-card p-5">
                <CheckCircle2 className="mt-0.5 h-5 w-5 shrink-0 text-primary" />
                <span className="text-sm md:text-base">{b}</span>
              </div>
            ))}
          </div>

          <div className="mt-10 grid gap-4 sm:grid-cols-3">
            {[
              { i: TrendingUp, t: "Proven Strategies", d: "Battle-tested on real markets." },
              { i: Shield, t: "Risk-First Mindset", d: "Protect your capital first, profit second." },
              { i: BookOpen, t: "Lifetime Access", d: "Learn at your own pace, forever." },
            ].map(({ i: Icon, t, d }) => (
              <div key={t} className="rounded-xl border border-border bg-card p-5">
                <Icon className="h-6 w-6 text-gold" />
                <h3 className="mt-3 font-semibold">{t}</h3>
                <p className="mt-1 text-sm text-muted-foreground">{d}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* TESTIMONIALS */}
      <section id="testimonials" className="py-20">
        <div className="mx-auto max-w-6xl px-4">
          <div className="mb-10 text-center">
            <h2 className="font-display text-3xl font-bold md:text-4xl">Loved by 1,200+ Students</h2>
          </div>
          <div className="grid gap-5 md:grid-cols-2 lg:grid-cols-3">
            {testimonials.map((t) => (
              <div key={t.id} className="rounded-2xl border border-border bg-card p-6">
                <div className="flex items-center gap-1">
                  {Array.from({ length: t.rating }).map((_, i) => <Star key={i} className="h-4 w-4 fill-gold text-gold" />)}
                </div>
                <p className="mt-3 text-sm leading-relaxed">{t.content}</p>
                <p className="mt-4 text-sm font-semibold">— {t.student_name}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* STUDENT INBOX PROOFS */}
      <StudentProofs proofs={proofs as any} />



      {/* FAQ */}
      <section id="faq" className="border-t border-border/40 bg-card/30 py-20">
        <div className="mx-auto max-w-3xl px-4">
          <div className="mb-10 text-center">
            <h2 className="font-display text-3xl font-bold md:text-4xl">Frequently Asked Questions</h2>
          </div>
          <div className="space-y-3">
            {faqs.map((f) => <FaqItem key={f.id} q={f.question} a={f.answer} />)}
          </div>
        </div>
      </section>

      {/* FINAL CTA */}
      <section id="buy" className="py-20">
        <div className="mx-auto max-w-3xl px-4">
          <div className="rounded-3xl border border-primary/30 bg-gradient-to-br from-card to-card/40 p-8 text-center shadow-glow md:p-12">
            <h2 className="font-display text-3xl font-bold md:text-4xl">Ready to Start Trading?</h2>
            <p className="mx-auto mt-3 max-w-xl text-muted-foreground">
              Join {course.student_count.toLocaleString()}+ students. Pay with bKash. Get instant access after admin approval.
            </p>
            <div className="mt-6 flex items-baseline justify-center gap-3">
              {hasDiscount && <span className="text-muted-foreground line-through">{formatBDT(Number(course.price))}</span>}
              <span className="text-5xl font-bold text-gradient-gold">{formatBDT(Number(price))}</span>
            </div>
            <Link to="/buy" className="mt-8 inline-block rounded-xl bg-gradient-primary px-8 py-4 font-semibold text-primary-foreground shadow-glow transition hover:scale-[1.02]">
              Enroll with bKash
            </Link>
            <p className="mt-4 text-xs text-muted-foreground">
              bKash: <strong className="text-foreground">{settings?.bkash_number}</strong> ({settings?.bkash_account_type})
            </p>
          </div>
        </div>
      </section>

      <footer className="border-t border-border/40 py-8 text-center text-xs text-muted-foreground">
        © 2026 Binary Options Mastery · {settings?.support_email ?? "support@example.com"}
      </footer>
    </div>
  );
}

function FaqItem({ q, a }: { q: string; a: string }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="rounded-xl border border-border bg-card">
      <button onClick={() => setOpen((o) => !o)} className="flex w-full items-center justify-between gap-3 p-5 text-left">
        <span className="font-medium">{q}</span>
        <ChevronDown className={`h-5 w-5 shrink-0 text-muted-foreground transition ${open ? "rotate-180" : ""}`} />
      </button>
      {open && <div className="border-t border-border px-5 py-4 text-sm text-muted-foreground">{a}</div>}
    </div>
  );
}
