"use client";

import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import {
  ArrowRight,
  Building2,
  Gauge,
  Landmark,
  Lightbulb,
  Sparkles,
  Target,
  TrendingUp,
  Wrench,
  Zap,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { cn } from "@/lib/utils";

type PillarId = "happening" | "matters" | "next";

const pillars: Array<{
  id: PillarId;
  step: number;
  title: string;
  tagline: string;
  detail: string;
  icon: typeof Gauge;
  accent: string;
  glow: string;
  preview: { label: string; value: string; sub: string };
}> = [
  {
    id: "happening",
    step: 1,
    title: "What is happening",
    tagline: "Live picture of brand health, pipeline, and threats.",
    detail:
      "Opportunities, competitor moves, social visibility, website trust, and federal bids — unified so you stop guessing from scattered dashboards.",
    icon: Gauge,
    accent: "text-sky-400",
    glow: "from-sky-500/20 to-sky-500/0 border-sky-500/40",
    preview: { label: "Signals detected", value: "12", sub: "Across 4 channels today" },
  },
  {
    id: "matters",
    step: 2,
    title: "Why it matters",
    tagline: "Strategic confidence — not random tactics.",
    detail:
      "BrandLxft ranks what actually moves revenue with confidence scores, urgency, and dollar potential — so you work on the right thing first.",
    icon: TrendingUp,
    accent: "text-emerald-400",
    glow: "from-emerald-500/20 to-emerald-500/0 border-emerald-500/40",
    preview: { label: "Revenue at stake", value: "$48K", sub: "If you act on top 3 priorities" },
  },
  {
    id: "next",
    step: 3,
    title: "What to do next",
    tagline: "Actions tied to revenue potential.",
    detail:
      "Draft the email, import the bid, fix the ad, beat the competitor. Role Agents execute with your approval — not another report in a folder.",
    icon: Target,
    accent: "text-amber-400",
    glow: "from-amber-500/20 to-amber-500/0 border-amber-500/40",
    preview: { label: "Next move", value: "Import bid", sub: "SAM.gov · due in 6 days" },
  },
];

const audiences = [
  {
    id: "trades",
    title: "Home services & trades",
    icon: Wrench,
    stat: "18K+",
    statLabel: "federal contracts / yr",
    text: "Landscaping, HVAC, plumbing — matched SAM.gov bids and plain-English registration.",
    gradient: "hover:border-emerald-500/40 hover:shadow-emerald-500/10",
  },
  {
    id: "local",
    title: "Growing local businesses",
    icon: Building2,
    stat: "4.2×",
    statLabel: "faster prioritization",
    text: "See who customers pick on social vs your site and where competitors are weak.",
    gradient: "hover:border-indigo-500/40 hover:shadow-indigo-500/10",
  },
  {
    id: "solo",
    title: "Owners without a marketing team",
    icon: Sparkles,
    stat: "3",
    statLabel: "questions answered daily",
    text: "Your AI co-founder frames every decision like an operator — without the jargon.",
    gradient: "hover:border-amber-500/40 hover:shadow-amber-500/10",
  },
];

function useScrollReveal(threshold = 0.15) {
  const ref = useRef<HTMLDivElement>(null);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setVisible(true);
          observer.disconnect();
        }
      },
      { threshold },
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, [threshold]);

  return { ref, visible };
}

export function WhyItMattersInteractive() {
  const [active, setActive] = useState<PillarId>("happening");
  const [hoveredAudience, setHoveredAudience] = useState<string | null>(null);
  const [mouse, setMouse] = useState({ x: 50, y: 30 });

  const heroReveal = useScrollReveal(0.1);
  const pillarsReveal = useScrollReveal(0.12);
  const audienceReveal = useScrollReveal(0.1);

  const activePillar = pillars.find((p) => p.id === active)!;
  const ActiveIcon = activePillar.icon;

  return (
    <>
      {/* Hero */}
      <section
        ref={heroReveal.ref}
        className={cn(
          "relative mx-auto max-w-6xl overflow-hidden px-4 py-20 transition-all duration-1000",
          heroReveal.visible ? "translate-y-0 opacity-100" : "translate-y-8 opacity-0",
        )}
        onMouseMove={(e) => {
          const rect = e.currentTarget.getBoundingClientRect();
          setMouse({
            x: ((e.clientX - rect.left) / rect.width) * 100,
            y: ((e.clientY - rect.top) / rect.height) * 100,
          });
        }}
      >
        <div
          className="pointer-events-none absolute inset-0 opacity-60 transition-opacity duration-300"
          style={{
            background: `radial-gradient(600px circle at ${mouse.x}% ${mouse.y}%, rgba(14,165,233,0.18), transparent 50%),
              radial-gradient(400px circle at 80% 20%, rgba(99,102,241,0.12), transparent 40%)`,
          }}
        />
        <div className="relative grid gap-10 lg:grid-cols-2 lg:items-center">
          <div>
            <p className="mb-4 inline-flex items-center gap-2 rounded-full border border-sky-500/30 bg-sky-500/10 px-3 py-1 text-xs text-sky-300">
              <Zap className="h-3.5 w-3.5" />
              BrandLxft framework
            </p>
            <h1 className="text-4xl font-bold leading-tight md:text-5xl lg:text-6xl">
              Why it{" "}
              <span className="text-gradient-brand">matters</span>
            </h1>
            <p className="mt-5 max-w-xl text-lg leading-relaxed text-slate-300">
              Growth tools dump data. BrandLxft answers three questions every owner needs — with revenue attached.
            </p>
            <div className="mt-8 flex flex-wrap gap-3">
              <Link href="/signup">
                <Button size="lg" className="gap-2 shadow-lg shadow-sky-500/20">
                  Build My Business Brain
                  <ArrowRight className="h-4 w-4" />
                </Button>
              </Link>
              <Link href="/demo">
                <Button variant="outline" size="lg">
                  Try a live demo
                </Button>
              </Link>
            </div>
          </div>

          {/* Mini interactive loop */}
          <div className="relative">
            <div className="absolute -inset-4 rounded-3xl bg-gradient-to-br from-sky-500/10 via-indigo-500/5 to-amber-500/10 blur-2xl" />
            <Card className="relative overflow-hidden border-slate-700/80 bg-slate-900/80 backdrop-blur">
              <CardContent className="p-6">
                <p className="mb-4 text-xs uppercase tracking-widest text-slate-500">Live framework preview</p>
                <div className="flex gap-2">
                  {pillars.map((p) => {
                    const Icon = p.icon;
                    const isActive = active === p.id;
                    return (
                      <button
                        key={p.id}
                        type="button"
                        onClick={() => setActive(p.id)}
                        className={cn(
                          "flex flex-1 flex-col items-center gap-2 rounded-xl border px-2 py-3 text-center transition-all duration-300",
                          isActive
                            ? `border-slate-600 bg-slate-800/80 scale-105 shadow-lg ${p.glow.split(" ")[2]}`
                            : "border-transparent bg-slate-950/50 hover:border-slate-700 hover:bg-slate-800/40",
                        )}
                      >
                        <span
                          className={cn(
                            "flex h-9 w-9 items-center justify-center rounded-full transition-colors",
                            isActive ? "bg-slate-700" : "bg-slate-800",
                          )}
                        >
                          <Icon className={cn("h-4 w-4", isActive ? p.accent : "text-slate-500")} />
                        </span>
                        <span className={cn("text-[10px] font-medium leading-tight", isActive ? "text-slate-200" : "text-slate-500")}>
                          Step {p.step}
                        </span>
                      </button>
                    );
                  })}
                </div>

                <div
                  key={active}
                  className="mt-5 animate-fade-in-up rounded-xl border border-slate-700/80 bg-gradient-to-br from-slate-950 to-slate-900 p-4"
                >
                  <div className="flex items-start gap-3">
                    <div className={cn("rounded-lg bg-slate-800 p-2", activePillar.accent)}>
                      <ActiveIcon className="h-5 w-5 text-white mix-blend-screen" />
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="font-semibold text-slate-100">{activePillar.title}</p>
                      <p className="mt-1 text-sm text-slate-400">{activePillar.tagline}</p>
                    </div>
                  </div>
                  <div className="mt-4 grid grid-cols-2 gap-3 border-t border-slate-800 pt-4">
                    <div>
                      <p className="text-[10px] uppercase tracking-wide text-slate-500">{activePillar.preview.label}</p>
                      <p className={cn("mt-0.5 text-2xl font-bold tabular-nums", activePillar.accent)}>
                        {activePillar.preview.value}
                      </p>
                    </div>
                    <div className="flex items-end">
                      <p className="text-xs text-slate-500">{activePillar.preview.sub}</p>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </section>

      {/* Interactive pillars */}
      <section
        ref={pillarsReveal.ref}
        className={cn(
          "mx-auto max-w-6xl px-4 pb-20 transition-all duration-1000 delay-100",
          pillarsReveal.visible ? "translate-y-0 opacity-100" : "translate-y-10 opacity-0",
        )}
      >
        <div className="mb-8 text-center">
          <h2 className="text-2xl font-semibold md:text-3xl">Explore each step</h2>
          <p className="mt-2 text-slate-400">Click a pillar — watch the preview update above and below.</p>
        </div>

        <div className="grid gap-4 lg:grid-cols-3">
          {pillars.map((p) => {
            const Icon = p.icon;
            const isActive = active === p.id;
            return (
              <button
                key={p.id}
                type="button"
                onClick={() => setActive(p.id)}
                className={cn(
                  "group relative overflow-hidden rounded-2xl border p-6 text-left transition-all duration-500",
                  isActive
                    ? `border-slate-600 bg-gradient-to-br ${p.glow} shadow-xl scale-[1.02]`
                    : "border-slate-800/80 bg-slate-900/40 hover:border-slate-700 hover:bg-slate-900/70",
                )}
              >
                <div
                  className={cn(
                    "absolute inset-0 opacity-0 transition-opacity duration-500 group-hover:opacity-100",
                    isActive && "opacity-100",
                  )}
                  style={{
                    background: `radial-gradient(circle at 50% 0%, rgba(255,255,255,0.06), transparent 60%)`,
                  }}
                />
                <div className="relative">
                  <div className="mb-4 flex items-center justify-between">
                    <span className={cn("flex h-11 w-11 items-center justify-center rounded-xl bg-slate-800 transition-transform duration-300", isActive && "scale-110")}>
                      <Icon className={cn("h-5 w-5", p.accent)} />
                    </span>
                    <span className="text-xs font-mono text-slate-600">0{p.step}</span>
                  </div>
                  <h3 className="text-lg font-semibold text-slate-100">{p.title}</h3>
                  <p className="mt-2 text-sm font-medium text-slate-300">{p.tagline}</p>
                  <p
                    className={cn(
                      "mt-3 text-sm leading-relaxed text-slate-400 transition-all duration-500",
                      isActive ? "max-h-40 opacity-100" : "max-h-0 opacity-0 lg:max-h-0 lg:opacity-0",
                      "lg:group-hover:max-h-40 lg:group-hover:opacity-100",
                    )}
                  >
                    {p.detail}
                  </p>
                  {isActive ? (
                    <span className="mt-4 inline-flex items-center gap-1 text-xs text-sky-400">
                      Active in preview <ArrowRight className="h-3 w-3" />
                    </span>
                  ) : null}
                </div>
              </button>
            );
          })}
        </div>
      </section>

      {/* Audiences */}
      <section
        ref={audienceReveal.ref}
        className={cn(
          "border-y border-slate-800/80 bg-slate-900/30 py-20 transition-all duration-1000",
          audienceReveal.visible ? "opacity-100" : "opacity-0",
        )}
      >
        <div className="mx-auto max-w-6xl px-4">
          <div className="mb-10 flex flex-wrap items-end justify-between gap-4">
            <div>
              <div className="mb-2 flex items-center gap-2">
                <Lightbulb className="h-5 w-5 text-indigo-400" />
                <h2 className="text-2xl font-semibold md:text-3xl">Who this is for</h2>
              </div>
              <p className="text-slate-400">Hover or tap to highlight your path.</p>
            </div>
            <Link href="/opportunities" className="text-sm text-sky-400 hover:text-sky-300">
              See federal work guide →
            </Link>
          </div>

          <div className="grid gap-4 md:grid-cols-3">
            {audiences.map((item) => {
              const Icon = item.icon;
              const isHovered = hoveredAudience === item.id;
              return (
                <div
                  key={item.id}
                  role="button"
                  tabIndex={0}
                  onMouseEnter={() => setHoveredAudience(item.id)}
                  onMouseLeave={() => setHoveredAudience(null)}
                  onFocus={() => setHoveredAudience(item.id)}
                  onBlur={() => setHoveredAudience(null)}
                  className={cn(
                    "group cursor-default rounded-2xl border border-slate-800 bg-slate-950/50 p-6 transition-all duration-500 hover:-translate-y-1 hover:shadow-2xl",
                    item.gradient,
                    isHovered && "-translate-y-1 shadow-2xl",
                  )}
                >
                  <div className="mb-4 flex items-center justify-between">
                    <span className="flex h-10 w-10 items-center justify-center rounded-lg bg-slate-800 transition-colors group-hover:bg-slate-700">
                      <Icon className="h-5 w-5 text-slate-300" />
                    </span>
                    {item.id === "trades" ? (
                      <Landmark className="h-4 w-4 text-emerald-400/60" />
                    ) : null}
                  </div>
                  <p className={cn("text-3xl font-bold tabular-nums transition-colors", isHovered ? "text-gradient-brand" : "text-slate-100")}>
                    {item.stat}
                  </p>
                  <p className="text-xs uppercase tracking-wide text-slate-500">{item.statLabel}</p>
                  <h3 className="mt-4 font-semibold text-slate-100">{item.title}</h3>
                  <p className="mt-2 text-sm leading-relaxed text-slate-400">{item.text}</p>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="relative mx-auto max-w-4xl overflow-hidden px-4 py-24 text-center">
        <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
          <div className="h-64 w-64 animate-pulse-soft rounded-full bg-sky-500/10 blur-3xl" />
        </div>
        <div className="relative">
          <h2 className="text-3xl font-semibold md:text-4xl">
            Stop guessing.{" "}
            <span className="text-gradient-brand">Start executing.</span>
          </h2>
          <p className="mx-auto mt-4 max-w-xl text-slate-400">
            Connect once. BrandLxft learns your market, finds opportunities, and tells you the highest-value move
            today.
          </p>
          <div className="mt-8 flex flex-wrap justify-center gap-3">
            <Link href="/signup">
              <Button size="lg" className="gap-2 px-8 shadow-lg shadow-sky-500/25">
                Get started free
                <ArrowRight className="h-4 w-4" />
              </Button>
            </Link>
            <Link href="/">
              <Button variant="ghost" size="lg">
                Back to home
              </Button>
            </Link>
          </div>
        </div>
      </section>
    </>
  );
}
