"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import { motion } from "framer-motion";
import { ChevronRight } from "lucide-react";

/* ════════════════════════════════════════════════════════════
   DATA
   ════════════════════════════════════════════════════════════ */

const SECTIONS = [
  { id: "hero", label: "Home", num: "01" },
  { id: "about", label: "About", num: "02" },
  { id: "destinations", label: "Destinations", num: "03" },
  { id: "sustainability", label: "Sustainability", num: "04" },
  { id: "experiences", label: "Experiences", num: "05" },
  { id: "contact", label: "Contact", num: "06" },
];

const CATEGORIES = [
  "Island Tours",
  "Cultural Heritage",
  "Eco Adventures",
  "Luxury Retreats",
];

const STATS = [
  { value: 14, label: "Years of Excellence" },
  { value: 50, label: "Thousand Guests" },
  { value: 99, label: "Islands Explored" },
  { value: null, display: "24/7", label: "Concierge Service" },
];

const CONTENT_SECTIONS: {
  id: string;
  prefix: string;
  heading: string;
  headingStrong: string;
  body: string;
  linkText: string;
  linkHref: string;
  imageUrl: string;
}[] = [
  {
    id: "about",
    prefix: "/ About Us",
    heading: "We are",
    headingStrong:
      "Langkawi Legacy — a destination experience company with Malaysian roots, redefining adventure and authenticity.",
    body: "Founded in the heart of Kedah, we bring together the raw beauty of Langkawi\u2019s archipelago with world-class hospitality. Our team of local experts and global storytellers crafts experiences that honour the land, celebrate the culture, and leave lasting impressions on every traveller who walks our shores.",
    linkText: "Learn More",
    linkHref: "#destinations",
    imageUrl:
      "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1920&q=80",
  },
  {
    id: "destinations",
    prefix: "/ Our Destinations",
    heading: "Langkawi Legacy operates a network of",
    headingStrong:
      "curated destinations strategically located across the Langkawi archipelago and beyond.",
    body: "From the mangrove forests of Kilim Karst to the summit of Gunung Mat Cincang, each destination is selected for its natural significance, cultural richness, and capacity to deliver transformative experiences that connect guests to the soul of Malaysia.",
    linkText: "Explore Destinations",
    linkHref: "#sustainability",
    imageUrl:
      "https://images.unsplash.com/photo-1559128010-7c1ad6e1b6a5?w=1920&q=80",
  },
  {
    id: "sustainability",
    prefix: "/ Sustainability",
    heading: "We help build",
    headingStrong:
      "sustainable tourism ecosystems that protect the natural world while inspiring future generations.",
    body: "As a UNESCO Global Geopark partner, Langkawi Legacy is committed to preserving the archipelago\u2019s 550-million-year-old geological heritage. Every experience we design contributes to conservation, community empowerment, and environmental education across the region.",
    linkText: "Our Green Commitment",
    linkHref: "#experiences",
    imageUrl:
      "https://images.unsplash.com/photo-1446776811953-b23d57bd21aa?w=1920&q=80",
  },
  {
    id: "experiences",
    prefix: "/ Experiences",
    heading: "Our experiences team curates",
    headingStrong:
      "unforgettable journeys across Langkawi\u2019s most spectacular terrain for global travellers.",
    body: "Whether scaling the cascading tiers of Telaga Tujuh, diving the coral gardens of Pulau Payar, or sailing into a crimson sunset aboard a traditional junk rig \u2014 every moment is designed to immerse, inspire, and transform.",
    linkText: "Book an Experience",
    linkHref: "#contact",
    imageUrl:
      "https://images.unsplash.com/photo-1504893524553-b855bce32c67?w=1920&q=80",
  },
];

/* ════════════════════════════════════════════════════════════
   HOOKS
   ════════════════════════════════════════════════════════════ */

function useSectionObserver() {
  const [active, setActive] = useState("hero");
  const refs = useRef<Map<string, HTMLElement>>(new Map());

  const setRef = useCallback(
    (id: string) => (el: HTMLElement | null) => {
      if (el) refs.current.set(id, el);
    },
    []
  );

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) setActive(entry.target.id);
        });
      },
      { threshold: 0.4 }
    );

    refs.current.forEach((el) => observer.observe(el));
    return () => observer.disconnect();
  }, []);

  return { active, setRef };
}

function useCounter(target: number, startOnView = true) {
  const [count, setCount] = useState(0);
  const ref = useRef<HTMLDivElement>(null);
  const animated = useRef(false);

  useEffect(() => {
    const el = ref.current;
    if (!el || !startOnView) return;

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting && !animated.current) {
            animated.current = true;
            let current = 0;
            const step = Math.max(1, Math.floor(target / 30));
            const timer = setInterval(() => {
              current += step;
              if (current >= target) {
                current = target;
                clearInterval(timer);
              }
              setCount(current);
            }, 40);
          }
        });
      },
      { threshold: 0.5 }
    );

    observer.observe(el);
    return () => observer.disconnect();
  }, [target, startOnView]);

  return { count, ref };
}

function useParallax() {
  const ticking = useRef(false);
  const refs = useRef<Map<string, HTMLElement>>(new Map());

  const setPanelRef = useCallback(
    (id: string) => (el: HTMLElement | null) => {
      if (el) refs.current.set(id, el);
    },
    []
  );

  useEffect(() => {
    const handleScroll = () => {
      if (!ticking.current) {
        requestAnimationFrame(() => {
          refs.current.forEach((el) => {
            const rect = el.getBoundingClientRect();
            if (rect.top < window.innerHeight && rect.bottom > 0) {
              const progress = rect.top / window.innerHeight;
              const bg = el.querySelector(
                "[data-parallax-bg]"
              ) as HTMLElement | null;
              if (bg) {
                bg.style.transform = `scale(${1.08 + progress * 0.04})`;
              }
            }
          });
          ticking.current = false;
        });
        ticking.current = true;
      }
    };

    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  return { setPanelRef };
}

/* ════════════════════════════════════════════════════════════
   COMPONENTS
   ════════════════════════════════════════════════════════════ */

function Navigation({
  menuOpen,
  onToggle,
}: {
  menuOpen: boolean;
  onToggle: () => void;
}) {
  return (
    <nav className="fixed top-0 left-0 right-0 z-[1000] flex items-center justify-between px-6 md:px-10 py-7 pointer-events-none">
      <a
        href="#hero"
        className="pointer-events-auto text-base md:text-lg font-extrabold tracking-[0.2em] uppercase text-white no-underline mix-blend-difference"
      >
        LANGKAWI LEGACY
      </a>
      <button
        className="pointer-events-auto relative w-7 h-[18px] flex flex-col justify-between bg-transparent border-none p-0 cursor-pointer z-[1001]"
        onClick={onToggle}
        aria-label="Toggle menu"
      >
        <span
          className={`block w-full h-[1.5px] bg-white transition-all duration-400 ease-[cubic-bezier(0.16,1,0.3,1)] origin-right ${
            menuOpen
              ? "rotate-[-45deg]"
              : "rotate-0"
          }`}
        />
        <span
          className={`block w-full h-[1.5px] bg-white transition-all duration-400 ease-[cubic-bezier(0.16,1,0.3,1)] ${
            menuOpen
              ? "opacity-0 scale-x-0"
              : "opacity-100 scale-x-100"
          }`}
        />
        <span
          className={`block w-full h-[1.5px] bg-white transition-all duration-400 ease-[cubic-bezier(0.16,1,0.3,1)] origin-right ${
            menuOpen
              ? "rotate-[45deg]"
              : "rotate-0"
          }`}
        />
      </button>
    </nav>
  );
}

function FullscreenMenu({
  open,
  onClose,
}: {
  open: boolean;
  onClose: () => void;
}) {
  return (
    <div
      className={`fixed inset-0 z-[950] bg-black flex items-center justify-center transition-all duration-700 ease-[cubic-bezier(0.65,0,0.35,1)] ${
        open ? "menu-clip-open" : "menu-clip-closed"
      }`}
    >
      <div className="text-center flex flex-col gap-2">
        {SECTIONS.map((s) => (
          <a
            key={s.id}
            href={`#${s.id}`}
            onClick={onClose}
            className="block text-[clamp(32px,6vw,64px)] font-extralight text-white/30 no-underline tracking-[0.05em] leading-[1.3] transition-all duration-300 hover:text-white hover:translate-x-2.5"
          >
            <span className="text-[11px] font-medium tracking-[0.15em] text-white/20 mr-3 align-super">
              {s.num}
            </span>
            {s.label}
          </a>
        ))}
      </div>
    </div>
  );
}

function SideDots({
  active,
  onSelect,
}: {
  active: string;
  onSelect: (id: string) => void;
}) {
  const panelSections = SECTIONS.filter((s) => s.id !== "contact");

  return (
    <div className="fixed right-7 top-1/2 -translate-y-1/2 z-[800] hidden md:flex flex-col gap-3.5">
      {panelSections.map((s) => (
        <button
          key={s.id}
          onClick={() => onSelect(s.id)}
          className={`relative w-2 h-2 rounded-full border-[1.5px] cursor-pointer transition-all duration-300 bg-transparent hover:border-white/60 ${
            active === s.id
              ? "border-[#c8a45e] bg-[#c8a45e] shadow-[0_0_8px_rgba(200,164,94,0.4)]"
              : "border-white/25"
          }`}
          aria-label={`Go to ${s.label}`}
        >
          <span className="absolute right-[22px] top-1/2 -translate-y-1/2 text-[9px] font-semibold tracking-[0.15em] uppercase text-white/40 whitespace-nowrap opacity-0 pointer-events-none transition-opacity duration-250 hover:opacity-100">
            {s.label}
          </span>
        </button>
      ))}
    </div>
  );
}

function ScrollCue() {
  return (
    <div className="absolute bottom-9 left-1/2 -translate-x-1/2 z-10 flex flex-col items-center gap-2 animate-cue-in">
      <span className="text-[9px] font-medium tracking-[0.2em] uppercase text-white/30">
        Scroll
      </span>
      <div className="w-px h-9 bg-white/10 relative overflow-hidden animate-scroll-pulse" />
    </div>
  );
}

function StatCounter({
  value,
  display,
  label,
  delayClass,
}: {
  value: number | null;
  display?: string;
  label: string;
  delayClass: string;
}) {
  const { count, ref } = useCounter(value ?? 0);

  return (
    <div
      ref={ref}
      className={`flex-1 px-6 md:px-9 py-6 border-r border-white/[0.06] last:border-r-0 animate-stat-in ${delayClass}`}
    >
      <div className="text-2xl md:text-[26px] font-bold text-[#c8a45e] tracking-tight">
        {value !== null ? count : display}
      </div>
      <div className="text-[9px] font-medium tracking-[0.18em] uppercase text-white/35 mt-1">
        {label}
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   ANIMATION VARIANTS
   ════════════════════════════════════════════════════════════ */

const fadeUp = {
  hidden: { opacity: 0, y: 40 },
  visible: (delay: number) => ({
    opacity: 1,
    y: 0,
    transition: {
      duration: 1.2,
      ease: [0.16, 1, 0.3, 1],
      delay,
    },
  }),
};

const fadeUpShort = {
  hidden: { opacity: 0, y: 30 },
  visible: (delay: number) => ({
    opacity: 1,
    y: 0,
    transition: {
      duration: 0.9,
      ease: [0.16, 1, 0.3, 1],
      delay,
    },
  }),
};

/* ════════════════════════════════════════════════════════════
   MAIN PAGE
   ════════════════════════════════════════════════════════════ */

export default function Home() {
  const [menuOpen, setMenuOpen] = useState(false);
  const { active, setRef } = useSectionObserver();
  const { setPanelRef } = useParallax();

  // Lock body scroll when menu is open
  useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
  }, [menuOpen]);

  // Add langkawi-scroll class to html for scrollbar hiding
  useEffect(() => {
    document.documentElement.classList.add("langkawi-scroll");
  }, []);

  // Escape key closes menu
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === "Escape") setMenuOpen(false);
    };
    document.addEventListener("keydown", handler);
    return () => document.removeEventListener("keydown", handler);
  }, []);

  const handleDotSelect = useCallback((id: string) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: "smooth" });
  }, []);

  return (
    <main className="bg-black text-white overflow-x-hidden">
      {/* ─── NAVIGATION ─── */}
      <Navigation
        menuOpen={menuOpen}
        onToggle={() => setMenuOpen((v) => !v)}
      />

      {/* ─── FULLSCREEN MENU ─── */}
      <FullscreenMenu
        open={menuOpen}
        onClose={() => setMenuOpen(false)}
      />

      {/* ─── SIDE DOTS ─── */}
      <SideDots active={active} onSelect={handleDotSelect} />

      {/* ════════════════════════════════════════════════════
          HERO SECTION
          ════════════════════════════════════════════════════ */}
      <section
        id="hero"
        ref={setPanelRef("hero")}
        className="relative w-full h-screen overflow-hidden scroll-mt-0"
        style={{ scrollSnapAlign: "start" }}
      >
        {/* Video background */}
        <div className="absolute inset-0">
          <video
            autoPlay
            muted
            loop
            playsInline
            poster="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1920&q=80"
            className="w-full h-full object-cover scale-[1.08] transition-transform duration-[12s] ease-out"
          >
            <source src="/video.mp4" type="video/mp4" />
          </video>
        </div>

        {/* Overlay */}
        <div
          className="absolute inset-0"
          style={{
            background:
              "linear-gradient(180deg, rgba(0,0,0,0.3) 0%, rgba(0,0,0,0.15) 30%, rgba(0,0,0,0.4) 70%, rgba(0,0,0,0.7) 100%)",
          }}
        />

        {/* Content */}
        <div className="relative z-10 w-full h-full flex items-center justify-center px-[6%] md:px-[8%]">
          <div className="w-full text-center flex flex-col items-center justify-center">
            <motion.h1
              variants={fadeUp}
              initial="hidden"
              animate="visible"
              custom={0.3}
              className="font-extralight leading-[1.25] tracking-[0.04em] max-w-[900px] text-[clamp(22px,3.8vw,52px)]"
            >
              LANGKAWI LEGACY IS A PREMIER DESTINATION EXPERIENCE COMPANY WITH{" "}
              <strong className="font-bold">MALAYSIAN HERITAGE</strong>
            </motion.h1>

            <motion.div
              variants={fadeUp}
              initial="hidden"
              animate="visible"
              custom={0.7}
              className="flex flex-wrap justify-center gap-6 md:gap-8 mt-8 md:mt-10"
            >
              {CATEGORIES.map((cat) => (
                <span
                  key={cat}
                  className="relative text-[10px] font-semibold tracking-[0.25em] uppercase text-white/50 pb-1.5 cursor-default transition-colors duration-300 hover:text-[#c8a45e] after:content-[''] after:absolute after:bottom-0 after:left-0 after:w-0 after:h-px after:bg-[#c8a45e] after:transition-all after:duration-400 after:ease-out hover:after:w-full"
                >
                  {cat}
                </span>
              ))}
            </motion.div>
          </div>
        </div>

        {/* Scroll cue */}
        <ScrollCue />

        {/* Stats strip */}
        <div className="absolute bottom-0 left-0 right-0 z-10 hidden md:flex border-t border-white/[0.06]">
          {STATS.map((stat, i) => (
            <StatCounter
              key={stat.label}
              value={stat.value}
              display={stat.display}
              label={stat.label}
              delayClass={`animate-stat-delay-${i + 1}`}
            />
          ))}
        </div>
      </section>

      {/* ════════════════════════════════════════════════════
          CONTENT SECTIONS
          ════════════════════════════════════════════════════ */}
      {CONTENT_SECTIONS.map((section) => (
        <section
          key={section.id}
          id={section.id}
          ref={(el) => {
            setRef(section.id)(el);
            setPanelRef(section.id)(el);
          }}
          className="relative w-full h-screen overflow-hidden"
          style={{ scrollSnapAlign: "start" }}
        >
          {/* Background image */}
          <div
            data-parallax-bg
            className="panel-bg absolute inset-0 bg-cover bg-center scale-[1.08]"
            style={{ backgroundImage: `url('${section.imageUrl}')` }}
          />

          {/* Left overlay */}
          <div
            className="absolute inset-0"
            style={{
              background:
                "linear-gradient(90deg, rgba(0,0,0,0.75) 0%, rgba(0,0,0,0.4) 40%, rgba(0,0,0,0.1) 70%, rgba(0,0,0,0.2) 100%)",
            }}
          />

          {/* Content */}
          <div className="relative z-10 w-full h-full flex items-center px-[4%] md:px-[8%]">
            <div className="max-w-[560px] md:max-w-[560px] w-full">
              <motion.div
                variants={fadeUpShort}
                initial="hidden"
                whileInView="visible"
                viewport={{ once: true, amount: 0.3 }}
                custom={0.15}
              >
                <div className="text-xs font-semibold tracking-[0.18em] uppercase text-[#c8a45e] mb-7">
                  {section.prefix}
                </div>
              </motion.div>

              <motion.h2
                variants={fadeUpShort}
                initial="hidden"
                whileInView="visible"
                viewport={{ once: true, amount: 0.3 }}
                custom={0.3}
                className="text-[clamp(26px,3.5vw,44px)] font-light leading-[1.2] tracking-[-0.01em] text-white"
              >
                {section.heading}{" "}
                <strong className="font-bold text-[#c8a45e]">
                  {section.headingStrong}
                </strong>
              </motion.h2>

              <motion.p
                variants={fadeUpShort}
                initial="hidden"
                whileInView="visible"
                viewport={{ once: true, amount: 0.3 }}
                custom={0.5}
                className="text-[15px] font-normal leading-[1.75] text-white/65 mt-6 max-w-[460px]"
              >
                {section.body}
              </motion.p>

              <motion.a
                href={section.linkHref}
                variants={fadeUpShort}
                initial="hidden"
                whileInView="visible"
                viewport={{ once: true, amount: 0.3 }}
                custom={0.65}
                className="inline-flex items-center gap-2.5 mt-9 text-[11px] font-semibold tracking-[0.2em] uppercase text-[#c8a45e] no-underline cursor-pointer transition-all duration-300 hover:gap-[18px] group"
              >
                {section.linkText}
                <ChevronRight className="w-3.5 h-3.5 transition-transform duration-300 group-hover:translate-x-1" />
              </motion.a>
            </div>
          </div>
        </section>
      ))}

      {/* ════════════════════════════════════════════════════
          FOOTER
          ════════════════════════════════════════════════════ */}
      <footer
        id="contact"
        ref={setRef("contact")}
        className="relative min-h-[60vh] bg-[#050505] flex flex-col justify-center px-[6%] md:px-[8%] py-16 md:py-20 mt-auto"
        style={{ scrollSnapAlign: "start" }}
      >
        <div className="flex flex-col md:flex-row justify-between items-start mb-14 gap-8 flex-wrap">
          {/* Brand */}
          <div>
            <div className="text-xl md:text-[22px] font-extrabold tracking-[0.15em] uppercase mb-3">
              LANGKAWI <em className="not-italic text-[#c8a45e]">LEGACY</em>
            </div>
            <p className="text-sm text-white/30 max-w-[280px] leading-[1.6]">
              Curating extraordinary journeys through Malaysia&apos;s finest
              archipelago since 2010.
            </p>
          </div>

          {/* Link columns */}
          <div className="flex gap-10 md:gap-14 flex-wrap">
            <div>
              <h5 className="text-[10px] font-semibold tracking-[0.18em] uppercase text-[#c8a45e] mb-5">
                Explore
              </h5>
              <a
                href="#about"
                className="block text-[13px] text-white/40 no-underline mb-3.5 transition-colors duration-300 hover:text-white leading-[1.5]"
              >
                About Us
              </a>
              <a
                href="#destinations"
                className="block text-[13px] text-white/40 no-underline mb-3.5 transition-colors duration-300 hover:text-white leading-[1.5]"
              >
                Destinations
              </a>
              <a
                href="#experiences"
                className="block text-[13px] text-white/40 no-underline mb-3.5 transition-colors duration-300 hover:text-white leading-[1.5]"
              >
                Experiences
              </a>
              <a
                href="#sustainability"
                className="block text-[13px] text-white/40 no-underline mb-3.5 transition-colors duration-300 hover:text-white leading-[1.5]"
              >
                Sustainability
              </a>
            </div>

            <div>
              <h5 className="text-[10px] font-semibold tracking-[0.18em] uppercase text-[#c8a45e] mb-5">
                Company
              </h5>
              <a
                href="#"
                className="block text-[13px] text-white/40 no-underline mb-3.5 transition-colors duration-300 hover:text-white leading-[1.5]"
              >
                Careers
              </a>
              <a
                href="#"
                className="block text-[13px] text-white/40 no-underline mb-3.5 transition-colors duration-300 hover:text-white leading-[1.5]"
              >
                Press
              </a>
              <a
                href="#"
                className="block text-[13px] text-white/40 no-underline mb-3.5 transition-colors duration-300 hover:text-white leading-[1.5]"
              >
                Partners
              </a>
              <a
                href="#"
                className="block text-[13px] text-white/40 no-underline mb-3.5 transition-colors duration-300 hover:text-white leading-[1.5]"
              >
                Investors
              </a>
            </div>

            <div>
              <h5 className="text-[10px] font-semibold tracking-[0.18em] uppercase text-[#c8a45e] mb-5">
                Contact
              </h5>
              <a
                href="#"
                className="block text-[13px] text-white/40 no-underline mb-3.5 transition-colors duration-300 hover:text-white leading-[1.5]"
              >
                info@langkawilegacy.com
              </a>
              <a
                href="#"
                className="block text-[13px] text-white/40 no-underline mb-3.5 transition-colors duration-300 hover:text-white leading-[1.5]"
              >
                +60 4-955 7000
              </a>
              <a
                href="#"
                className="block text-[13px] text-white/40 no-underline mb-3.5 transition-colors duration-300 hover:text-white leading-[1.5]"
              >
                Langkawi, Kedah, Malaysia
              </a>
            </div>
          </div>
        </div>

        {/* Divider */}
        <div className="w-full h-px bg-white/[0.06]" />

        {/* Bottom */}
        <div className="flex flex-col md:flex-row justify-between items-center pt-7 gap-4 flex-wrap">
          <div className="text-[11px] text-white/20">
            &copy; 2024 Langkawi Legacy Sdn Bhd. All rights reserved.
          </div>
          <div className="flex gap-4">
            {["IG", "FB", "YT", "X"].map((social) => (
              <a
                key={social}
                href="#"
                className="text-white/25 no-underline text-base transition-colors duration-300 hover:text-[#c8a45e]"
                aria-label={social}
              >
                {social}
              </a>
            ))}
          </div>
        </div>
      </footer>
    </main>
  );
}
