"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import dynamic from "next/dynamic";
import { useRooSports } from "@/components/app-provider";
import { RooSportsLogo } from "@/components/roosports-logo";
import { DEFAULT_CMS_CONFIG, type CMSConfig } from "@/lib/cms";

const LottieCardMedia = dynamic(
  () => import("../components/LottieBasketballScene").then((m) => m.LottieCardMedia),
  { ssr: false }
);

export default function RooSportsApp() {
  const { isAuthenticated, authLoading } = useRooSports();
  const [cmsConfig, setCmsConfig] = useState<CMSConfig>(DEFAULT_CMS_CONFIG);
  // Mobile Menu State
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);

  // FAQ Accordion State
  const [activeFaq, setActiveFaq] = useState<number | null>(null);

  // Nav Background Scroll Effect & Active Section State
  const [isScrolled, setIsScrolled] = useState(false);
  const [activeSection, setActiveSection] = useState<"hero" | "about" | "faqs">("hero");

  useEffect(() => {
    let active = true;

    fetch("/api/cms", { cache: "no-store" })
      .then(async (response) => {
        if (!response.ok) return null;
        return response.json() as Promise<{ config?: CMSConfig }>;
      })
      .then((payload) => {
        if (active && payload?.config) setCmsConfig(payload.config);
      })
      .catch(() => {
        // Defaults remain visible if the content service is temporarily unavailable.
      });

    return () => {
      active = false;
    };
  }, []);

  useEffect(() => {
    const handleScroll = () => {
      if (window.scrollY > 50) {
        setIsScrolled(true);
      } else {
        setIsScrolled(false);
      }
    };
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  // IntersectionObserver for active nav link highlighting
  useEffect(() => {
    if (typeof window === "undefined") return;

    const sections = ["hero", "about", "faqs"];
    const observerOptions = {
      root: null,
      rootMargin: "-20% 0px -40% 0px",
      threshold: 0.2,
    };

    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          setActiveSection(entry.target.id as "hero" | "about" | "faqs");
        }
      });
    }, observerOptions);

    sections.forEach((id) => {
      const el = document.getElementById(id);
      if (el) observer.observe(el);
    });

    return () => observer.disconnect();
  }, []);

  const toggleAccordion = (index: number) => {
    setActiveFaq(activeFaq === index ? null : index);
  };

  return (
    <div
      suppressHydrationWarning
      className="bg-transparent text-[#0B0F12] min-h-screen antialiased selection:bg-[#0D131A] selection:text-white font-sans relative"
    >
      {/* TopNavBar */}
      <nav
        id="topNav"
        suppressHydrationWarning
        className={`fixed top-0 left-0 w-full z-50 flex justify-between items-center px-6 md:px-12 lg:px-16 transition-all duration-300 ${
          isScrolled
            ? "bg-white/80 backdrop-blur-md py-3 shadow-xs"
            : "bg-transparent py-6"
        }`}
      >
        <Link
          href="/"
          aria-label="RooSports home"
          className="text-4xl md:text-5xl font-extrabold tracking-tighter text-[#0B0F12] z-50 relative group"
        >
          <RooSportsLogo />
          <span className="absolute -bottom-2 left-0 w-0 h-0.5 bg-[#0B0F12] transition-all duration-300 group-hover:w-full"></span>
        </Link>

        {/* Desktop Nav Links */}
        <div className="hidden md:flex items-center space-x-10 lg:space-x-12 z-50">
          <Link
            className={`font-label-caps transition-all duration-300 py-1 border-b-2 ${
              activeSection === "hero"
                ? "text-[#0B0F12] font-bold border-[#0B0F12]"
                : "text-[#546067] border-transparent hover:text-[#0B0F12]"
            }`}
            href="/"
          >
            Home
          </Link>
          <Link
            className={`font-label-caps transition-all duration-300 py-1 border-b-2 ${
              activeSection === "about"
                ? "text-[#0B0F12] font-bold border-[#0B0F12]"
                : "text-[#546067] border-transparent hover:text-[#0B0F12]"
            }`}
            href="/#about"
          >
            About us
          </Link>
          <Link
            className={`font-label-caps transition-all duration-300 py-1 border-b-2 ${
              activeSection === "faqs"
                ? "text-[#0B0F12] font-bold border-[#0B0F12]"
                : "text-[#546067] border-transparent hover:text-[#0B0F12]"
            }`}
            href="/#faqs"
          >
            FAQs
          </Link>
          <Link
            className="font-label-caps transition-all duration-300 text-[#546067] hover:text-[#0B0F12] px-5 py-2.5 rounded-full border border-[#0B0F12]/15 hover:border-[#0B0F12] hover:bg-[#0B0F12] hover:text-white shadow-xs"
            href={isAuthenticated ? "/dashboard" : "/login"}
          >
            {authLoading ? "Account" : isAuthenticated ? "Dashboard" : "Login"}
          </Link>
          <button
            onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
            className="w-10 h-10 rounded-full border border-[#0B0F12]/10 flex items-center justify-center hover:bg-[#0B0F12] hover:text-white transition-all duration-300 cursor-pointer"
          >
            <span className="material-symbols-outlined text-xl">menu</span>
          </button>
        </div>

        {/* Mobile Nav Toggle */}
        <button
          onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
          className="md:hidden w-10 h-10 rounded-full border border-[#0B0F12]/10 flex items-center justify-center hover:bg-[#0B0F12] hover:text-white transition-all duration-300 z-50 cursor-pointer"
          id="mobileMenuBtn"
        >
          <span className="material-symbols-outlined text-xl">
            {isMobileMenuOpen ? "close" : "menu"}
          </span>
        </button>
      </nav>

      {/* Mobile Menu Overlay */}
      {isMobileMenuOpen && (
        <div
          id="mobileMenu"
          className="fixed inset-0 bg-white/95 backdrop-blur-md z-40 flex flex-col items-center justify-center space-y-8 pt-20"
        >
          <Link
            onClick={() => setIsMobileMenuOpen(false)}
            className={`text-3xl font-bold transition-opacity ${
              activeSection === "hero" ? "text-[#0B0F12] underline" : "text-[#0B0F12]/70 hover:opacity-100"
            }`}
            href="/"
          >
            Home
          </Link>
          <Link
            onClick={() => setIsMobileMenuOpen(false)}
            className={`text-3xl font-bold transition-opacity ${
              activeSection === "about" ? "text-[#0B0F12] underline" : "text-[#0B0F12]/70 hover:opacity-100"
            }`}
            href="/#about"
          >
            About us
          </Link>
          <Link
            onClick={() => setIsMobileMenuOpen(false)}
            className={`text-3xl font-bold transition-opacity ${
              activeSection === "faqs" ? "text-[#0B0F12] underline" : "text-[#0B0F12]/70 hover:opacity-100"
            }`}
            href="/#faqs"
          >
            FAQs
          </Link>
          <Link
            onClick={() => setIsMobileMenuOpen(false)}
            className="text-3xl font-bold text-[#0B0F12] hover:underline"
            href={isAuthenticated ? "/dashboard" : "/login"}
          >
            {authLoading ? "Account" : isAuthenticated ? "Dashboard" : "Login"}
          </Link>
        </div>
      )}

      {/* Main Alternating Zig-Zag Split-Screen Layout */}
      <main className="relative z-10 w-full max-w-7xl mx-auto px-6 md:px-12 lg:px-16 pt-28 md:pt-36 pb-28 md:pb-36 space-y-24 md:space-y-36 bg-transparent">
        
        {/* SECTION 1 (Hero): Text Left | Unboxed Seamless Animation Right */}
        <section className="min-h-[75vh] w-full grid grid-cols-1 lg:grid-cols-2 gap-12 lg:gap-16 items-center bg-transparent" id="hero">
          {/* Left Content */}
          <div className="flex flex-col justify-center items-start space-y-6 z-10">
            <div className="inline-flex items-center space-x-2 px-3 py-1 bg-white/60 backdrop-blur-md rounded-sm border border-[#0B0F12]/5 shadow-xs">
              <span className="w-2 h-2 rounded-full bg-[#0B0F12] animate-pulse"></span>
              <span className="font-label-caps text-[#546067]">
                {cmsConfig.landing.heroBadge}
              </span>
            </div>
            <h1 className="font-display-xl-mobile md:font-display-xl text-[#0B0F12]">
              {cmsConfig.landing.heroHeadline}
            </h1>
            <p className="text-lg md:text-xl text-[#546067] max-w-xl leading-relaxed">
              {cmsConfig.landing.heroSubheading}
            </p>
            <div className="flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-6 pt-4 w-full sm:w-auto">
              <Link
                className="inline-flex justify-center items-center px-8 py-4 text-white font-label-caps rounded-sm transition-colors duration-300 w-full sm:w-auto shadow-md"
                style={{ backgroundColor: cmsConfig.branding.primaryColor }}
                href={cmsConfig.landing.heroPrimaryCtaLink}
              >
                {cmsConfig.landing.heroPrimaryCtaText}
              </Link>
              <Link
                className="inline-flex justify-center items-center px-8 py-4 border border-[#0D131A] text-[#0D131A] font-label-caps rounded-sm hover:bg-white/30 transition-colors duration-300 w-full sm:w-auto"
                href={isAuthenticated ? "/dashboard" : cmsConfig.landing.heroSecondaryCtaLink}
              >
                {authLoading ? "ACCOUNT" : isAuthenticated ? "OPEN DASHBOARD" : cmsConfig.landing.heroSecondaryCtaText}
              </Link>
            </div>
            <p className="font-label-caps text-[#546067]">
              {cmsConfig.branding.announcementText}
            </p>
          </div>

          {/* Right Seamless Animation (Unboxed, Blended directly into screen) */}
          <div className="static lg:sticky lg:top-28 w-full min-h-[350px] md:min-h-[420px] flex items-center justify-center bg-transparent pointer-events-none overflow-visible">
            <LottieCardMedia speed={0.9} startFrame={0} endFrame={90} />
          </div>
        </section>

        {/* SECTION 2 (About Us / Privacy & Safety): Unboxed Seamless Animation Left | Text Right */}
        <section className="min-h-[70vh] w-full grid grid-cols-1 lg:grid-cols-2 gap-12 lg:gap-16 items-center bg-transparent scroll-mt-28" id="about">
          {/* Left Seamless Animation (Unboxed, Blended directly into screen) */}
          <div className="order-2 lg:order-1 static lg:sticky lg:top-28 w-full min-h-[320px] md:min-h-[400px] flex items-center justify-center bg-transparent pointer-events-none overflow-visible">
            <LottieCardMedia speed={0.85} startFrame={95} endFrame={185} />
          </div>

          {/* Right Content */}
          <div className="order-1 lg:order-2 flex flex-col justify-center space-y-6 z-10">
            <div className="inline-flex items-center space-x-2 px-3 py-1 bg-white/60 backdrop-blur-md rounded-sm border border-[#0B0F12]/5 shadow-xs w-fit">
              <span className="w-2 h-2 rounded-full bg-emerald-600 animate-pulse"></span>
              <span className="font-label-caps text-[#546067]">
                {cmsConfig.landing.aboutBadge}
              </span>
            </div>
            <h2 className="font-headline-lg-mobile md:font-headline-lg text-[#0B0F12]">
              {cmsConfig.landing.aboutHeadline}
            </h2>
            <p className="text-base text-[#546067] leading-relaxed">
              {cmsConfig.landing.aboutDescription}
            </p>
            {/* Glassmorphism Telemetry Card */}
            <div className="glass-panel bg-white/75 backdrop-blur-xl border border-white/60 shadow-xl rounded-2xl p-6 md:p-8">
              <div className="grid grid-cols-2 gap-6">
                <div>
                  <div className="text-3xl md:text-4xl font-extrabold text-[#0B0F12]">{cmsConfig.landing.stat1Value}</div>
                  <div className="font-label-caps text-[#546067] mt-1">{cmsConfig.landing.stat1Label}</div>
                </div>
                <div>
                  <div className="text-3xl md:text-4xl font-extrabold text-[#0B0F12]">{cmsConfig.landing.stat2Value}</div>
                  <div className="font-label-caps text-[#546067] mt-1">{cmsConfig.landing.stat2Label}</div>
                </div>
                <div className="col-span-2 h-px bg-[#0B0F12]/10 my-1"></div>
                <div>
                  <div className="text-3xl md:text-4xl font-extrabold text-[#0B0F12]">{cmsConfig.landing.stat3Value}</div>
                  <div className="font-label-caps text-[#546067] mt-1">{cmsConfig.landing.stat3Label}</div>
                </div>
                <div>
                  <div className="text-3xl md:text-4xl font-extrabold text-[#0B0F12]">{cmsConfig.landing.stat4Value}</div>
                  <div className="font-label-caps text-[#546067] mt-1">{cmsConfig.landing.stat4Label}</div>
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* SECTION 3 (FAQs): Clean, Streamlined Accordion Layout */}
        <section className="w-full bg-transparent scroll-mt-28 py-10 md:py-14" id="faqs">
          <div className="flex flex-col items-center text-center space-y-4 max-w-2xl mx-auto mb-10 md:mb-12">
            <div className="inline-flex items-center space-x-2 px-3 py-1 bg-white/60 backdrop-blur-md rounded-sm border border-[#0B0F12]/5 shadow-xs">
              <span className="w-2 h-2 rounded-full bg-[#0B0F12] animate-pulse"></span>
              <span className="font-label-caps text-[#546067]">
                GOT MORE QUESTIONS?
              </span>
            </div>
            <h2 className="font-headline-lg-mobile md:font-headline-lg text-[#0B0F12]">
              Frequently Asked Questions
            </h2>
            <p className="text-base md:text-lg text-[#546067] leading-relaxed">
              Clear answers on registration, safety, coaching, and how events get confirmed.
            </p>
          </div>

          <div className="w-full max-w-4xl mx-auto border-t border-[#0B0F12]/10">
            {cmsConfig.faqs.map((faq, index) => (
              <div
                key={faq.id}
                className={`accordion-item border-b border-[#0B0F12]/10 ${activeFaq === index ? "active" : ""}`}
              >
                <button
                  className="w-full grid grid-cols-[auto_1fr_auto] items-start gap-4 md:gap-6 py-5 md:py-6 text-left cursor-pointer group hover:bg-white/40 transition-colors duration-200 -mx-2 px-2 rounded-sm"
                  onClick={() => toggleAccordion(index)}
                  aria-expanded={activeFaq === index}
                >
                  <span className="font-label-caps text-[#546067]/70 pt-1.5 tabular-nums">
                    {String(index + 1).padStart(2, "0")}
                  </span>
                  <span
                    className={`text-base md:text-lg leading-snug transition-colors duration-200 ${
                      activeFaq === index ? "text-[#0B0F12] font-semibold" : "text-[#0B0F12] font-medium group-hover:text-[#0B0F12]"
                    }`}
                  >
                    {faq.question}
                  </span>
                  <span className="accordion-icon shrink-0 w-9 h-9 rounded-full border border-[#0B0F12]/10 flex items-center justify-center bg-white/50 text-[#546067]">
                    <span className="material-symbols-outlined text-[22px]">expand_more</span>
                  </span>
                </button>
                <div className="accordion-content">
                  <div>
                    <p className="text-sm md:text-base text-[#546067] leading-relaxed pb-5 md:pb-6 pl-10 md:pl-14 max-w-3xl">
                      {faq.answer}
                    </p>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </section>
      </main>

      {/* Footer Component */}
      <footer className="bg-transparent border-t border-[#dfe3e5] w-full px-6 md:px-12 lg:px-16 py-16 flex flex-col md:flex-row justify-between items-end relative z-20">
        <div className="mb-8 md:mb-0 w-full md:w-auto flex flex-col items-start">
          <span className="font-label-caps font-bold tracking-widest text-[#0B0F12] mb-4 block">
            {cmsConfig.branding.brandName}
          </span>
          <p className="text-[#546067] font-label-caps">
            © 2026 {cmsConfig.branding.brandTagline}. ALL RIGHTS RESERVED.
          </p>
        </div>
        <div className="flex flex-wrap gap-x-8 gap-y-4 w-full md:w-auto justify-start md:justify-end">
          <Link
            className="text-[#546067] font-label-caps hover:text-[#0B0F12] underline transition-all"
            href={isAuthenticated ? "/dashboard" : "/login"}
          >
            {authLoading ? "Account" : isAuthenticated ? "Dashboard" : "Login"}
          </Link>
        </div>
      </footer>
    </div>
  );
}
