"use client";

import { motion, useScroll, useSpring } from "framer-motion";
import { useEffect, useState } from "react";
import { InstagramIcon, MailIcon, MenuIcon, CloseIcon } from "@/components/icons";
import { studio } from "@/lib/content";

const SECTIONS = [
  { id: "work", label: "Work" },
  { id: "konnex", label: "Konnex" },
  { id: "about", label: "About" },
  { id: "recognition", label: "Recognition" },
  { id: "journal", label: "Instagram" },
  { id: "contact", label: "Contact" },
];

/**
 * Anchor navigation that works even inside sandboxed preview iframes:
 * - Releases any scroll lock a modal may have left behind.
 * - Scrolls FIRST (computed offset, independent of scroll-margin/padding).
 * - Only touches history in a try/catch, because sandboxed iframes throw a
 *   SecurityError on `history.replaceState` – which previously aborted the
 *   whole handler before scrolling happened.
 */
const HEADER_OFFSET = 96; // matches scroll-margin-top: 6rem

export function navigateToSection(id: string, onNavigate?: () => void) {
  document.body.style.overflow = "";
  document.documentElement.style.overflow = "";

  // Let React start unmounting a possible open slideshow. Errors in onNavigate
  // must not block scrolling, so guard it too.
  try {
    onNavigate?.();
  } catch {
    /* never let history/hydration issues block navigation */
  }

  const performScroll = () => {
    const target = document.getElementById(id);
    if (target) {
      // scrollIntoView works no matter which element is the actual scroll
      // container (window or a wrapping container in a preview iframe).
      // scroll-margin-top: 6rem keeps the section clear of the fixed header.
      try {
        target.scrollIntoView({ behavior: "smooth", block: "start" });
      } catch {
        const scrollTop = window.scrollY ?? document.documentElement.scrollTop ?? 0;
        const top =
          target.getBoundingClientRect().top + scrollTop - HEADER_OFFSET;
        window.scrollTo(0, Math.max(top, 0));
      }
    } else {
      try {
        window.scrollTo({ top: 0, behavior: "smooth" });
      } catch {
        window.scrollTo(0, 0);
      }
    }
    try {
      window.history.replaceState(null, "", target ? `#${id}` : "#top");
    } catch {
      /* sandboxed iframes disallow history changes – ignore */
    }
  };

  // Wait two frames so React has committed the unmount of a closed slideshow
  // and the page is definitely scrollable before we move.
  requestAnimationFrame(() => requestAnimationFrame(performScroll));
}

export default function Nav({ onNavigate }: { onNavigate?: () => void }) {
  const { scrollYProgress } = useScroll();
  const progress = useSpring(scrollYProgress, { stiffness: 120, damping: 24, mass: 0.3 });
  const [active, setActive] = useState("work");
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries
          .filter((e) => e.isIntersecting)
          .sort((a, b) => b.intersectionRatio - a.intersectionRatio);
        if (visible[0]) setActive(visible[0].target.id);
      },
      { rootMargin: "-45% 0px -45% 0px", threshold: [0.01, 0.25, 0.6] },
    );
    SECTIONS.forEach(({ id }) => {
      const el = document.getElementById(id);
      if (el) observer.observe(el);
    });
    return () => observer.disconnect();
  }, []);

  return (
    <>
        <motion.div
          style={{ scaleX: progress }}
          className="fixed left-0 top-0 z-[110] h-[2px] w-full origin-left bg-[#dcdcdc]"
          aria-hidden
        />
      <header
        className={`fixed inset-x-0 top-0 z-[100] transition-all duration-500 ${
          scrolled
            ? "border-b border-[#efefef] bg-white/85 backdrop-blur-xl"
            : "border-b border-transparent bg-transparent"
        }`}
      >
        <nav
          className="mx-auto flex max-w-[1600px] items-center justify-between gap-6 px-5 py-4 md:px-10"
          aria-label="Primary"
        >
          <a
            href="#top"
            onClick={(e) => {
              e.preventDefault();
              navigateToSection("top", onNavigate);
            }}
            className="group flex flex-col leading-none"
            aria-label={`${studio.name} — home`}
          >
            <span className="text-[13px] font-semibold uppercase tracking-[0.2em] transition-opacity group-hover:opacity-60 md:text-[15px]">
              Florian Gross
            </span>
            <span className="mt-1 text-[9.5px] uppercase tracking-[0.3em] text-faint md:text-[10px]">
              Design Studio · Barcelona
            </span>
          </a>

          <ul className="hidden items-center gap-8 lg:flex">
            {SECTIONS.map((section) => (
              <li key={section.id}>
                <a
                  href={`#${section.id}`}
                  onClick={(e) => {
                    e.preventDefault();
                    navigateToSection(section.id, onNavigate);
                  }}
                  className="relative text-[12px] uppercase tracking-[0.18em] transition-colors duration-300"
                  style={{ color: active === section.id ? "#0a0a0a" : "#9c9c9c" }}
                >
                  {section.label}
                  {active === section.id && (
                    <motion.span
                      layoutId="nav-dot"
                      className="absolute -bottom-2 left-1/2 h-[3px] w-[3px] -translate-x-1/2 rounded-full bg-[#0a0a0a]"
                    />
                  )}
                </a>
              </li>
            ))}
          </ul>

          <div className="flex items-center gap-1">
            <a
              href={`mailto:${studio.email}`}
              aria-label="Send an email"
              className="icon-grey rounded-full p-2.5 hover:bg-[#f6f6f6]"
            >
              <MailIcon className="h-[19px] w-[19px]" />
            </a>
            <a
              href={studio.instagram}
              target="_blank"
              rel="noopener noreferrer"
              aria-label={`Instagram ${studio.instagramHandle}`}
              className="icon-grey rounded-full p-2.5 hover:bg-[#f6f6f6]"
            >
              <InstagramIcon className="h-[19px] w-[19px]" />
            </a>
            <button
              type="button"
              onClick={() => setOpen((v) => !v)}
              aria-label="Toggle menu"
              aria-expanded={open}
              className="icon-grey rounded-full p-2.5 hover:bg-[#f6f6f6] lg:hidden"
            >
              {open ? (
                <CloseIcon className="h-[19px] w-[19px]" />
              ) : (
                <MenuIcon className="h-[19px] w-[19px]" />
              )}
            </button>
          </div>
        </nav>

        <motion.div
          initial={false}
          animate={{ height: open ? "auto" : 0, opacity: open ? 1 : 0 }}
          transition={{ duration: 0.4, ease: [0.16, 1, 0.3, 1] }}
          className="overflow-hidden border-t border-[#f0f0f0] bg-white lg:hidden"
        >
          <ul className="px-5 py-4">
            {SECTIONS.map((section, i) => (
              <motion.li
                key={section.id}
                initial={{ opacity: 0, x: -12 }}
                animate={{ opacity: open ? 1 : 0, x: open ? 0 : -12 }}
                transition={{ delay: open ? i * 0.045 : 0, duration: 0.3 }}
              >
                <a
                  href={`#${section.id}`}
                  onClick={(e) => {
                    e.preventDefault();
                    setOpen(false);
                    navigateToSection(section.id, onNavigate);
                  }}
                  className="block border-b border-[#f4f4f4] py-3.5 text-[13px] uppercase tracking-[0.2em] text-ink-soft"
                >
                  {section.label}
                </a>
              </motion.li>
            ))}
          </ul>
        </motion.div>
      </header>
    </>
  );
}
