"use client";

import { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import Link from "next/link";
import { usePathname } from "next/navigation";
// import { FiPhone } from 'react-icons/fi';
import CheckoutButton from "../common/CheckoutButton";
import { STRIPE_PLANS } from "@/data/designshare";
import LogoSVGComponent from "@/public/assets/Logo";
import Cookies from "js-cookie";
import { toast } from "sonner";

export default function Nav() {
  const [isOpen, setIsOpen] = useState(false);
  const [isSubscribed, setIsSubscribed] = useState(false);
  const pathname = usePathname();
  const isHomePage = pathname === "/";

  useEffect(() => {
    const timer = setTimeout(() => {
      if (Cookies.get("isPayment") === "true") {
        setIsSubscribed(true);
      }
    }, 0);

    return () => clearTimeout(timer);
  }, []);

  // Issue 1: Body scroll lock — prevents background from scrolling when menu is open
  useEffect(() => {
    if (isOpen) {
      const scrollY = window.scrollY;
      document.body.style.position = "fixed";
      document.body.style.top = `-${scrollY}px`;
      document.body.style.width = "100%";
      document.body.style.overflow = "hidden";
    } else {
      const scrollY = document.body.style.top;
      document.body.style.position = "";
      document.body.style.top = "";
      document.body.style.width = "";
      document.body.style.overflow = "";
      window.scrollTo(0, parseInt(scrollY || "0") * -1);
    }
    return () => {
      document.body.style.position = "";
      document.body.style.top = "";
      document.body.style.width = "";
      document.body.style.overflow = "";
    };
  }, [isOpen]);

  const handleLoginClick = (e: React.MouseEvent) => {
    if (!process.env.NEXT_PUBLIC_LOGIN_PORTAL_URL) {
      e.preventDefault();
      toast.error(
        "Login portal is currently unavailable. Please contact support.",
      );
    }
  };

  // When on a sub-page prefix with / so the browser navigates to homepage + anchor
  const resolveHref = (hash: string) => (isHomePage ? hash : `/${hash}`);

  const navLinks = [
    { name: "How it works", href: "#how" },
    { name: "Work", href: "#work" },
    { name: "Pricing", href: "#pricing" },
    { name: "FAQ", href: "#faq" },
  ];

  return (
    <div className="nav-wrap">
      <nav id="nav">
        {/* Logo */}
        <Link
          className={`nav-logo transition-opacity duration-300 ${isOpen ? "opacity-0 pointer-events-none" : "opacity-100"}`}
          href="/"
          aria-label="DesignShare home"
        >
          <LogoSVGComponent
            color="#1B70DF"
            style={{ height: "20px", width: "auto", cursor: "pointer" }}
            aria-label="DesignShare"
          />
        </Link>

        {/* Desktop Links */}
        <div className="nav-links">
          {navLinks.map((link) => (
            <Link key={link.name} className="nav-link" href={resolveHref(link.href)}>
              {link.name}
            </Link>
          ))}
          {/* <a href={LOGIN_PORTAL_URL} target="_blank" rel="noopener noreferrer" className="nav-link">
            Login
          </a>
          <Link
            href="https://calendly.com/designshare/meeting"
            className="nav-link"
            target="_blank"
            rel="noopener noreferrer"
          >
            <FiPhone style={{ display: 'inline', marginRight: '4px', verticalAlign: 'middle' }} />
            Book a call
          </Link> */}
        </div>

        {/* Desktop CTA */}
        {isSubscribed ? (
          <Link
            href={process.env.NEXT_PUBLIC_LOGIN_PORTAL_URL as string}
            onClick={handleLoginClick}
            className="nav-cta nav-cta-desktop text-center flex items-center justify-center"
          >
            Login
          </Link>
        ) : (
          <CheckoutButton
            priceId={STRIPE_PLANS.MONTHLY}
            className="nav-cta nav-cta-desktop"
          >
            Join the club
          </CheckoutButton>
        )}

        {/* Mobile Menu Toggle */}
        <button
          className="nav-mobile-toggle"
          onClick={() => setIsOpen(!isOpen)}
          aria-label="Toggle menu"
        >
          <span
            style={{
              transform: isOpen ? "rotate(45deg) translate(1px, -1px)" : "none",
            }}
          />
          <span style={{ opacity: isOpen ? 0 : 1 }} />
          <span
            style={{
              transform: isOpen ? "rotate(-45deg) translate(1px, 1px)" : "none",
            }}
          />
        </button>

      </nav>

      {/* Mobile Menu Overlay — rendered outside <nav> to avoid iOS Safari
          backdrop-filter containment that clips position:fixed children */}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0, x: "100%" }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: "100%" }}
            transition={{ type: "spring", damping: 25, stiffness: 200 }}
            className="nav-mobile-menu"
          >
            {/* Issue 2: Explicit close button inside overlay */}
            <button
              className="nav-mobile-close"
              onClick={() => setIsOpen(false)}
              aria-label="Close menu"
            >
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true">
                <path d="M15 5L5 15M5 5l10 10" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/>
              </svg>
            </button>
            {navLinks.map((link) => (
              <Link
                key={link.name}
                className="nav-mobile-link"
                href={resolveHref(link.href)}
                onClick={() => setIsOpen(false)}
              >
                {link.name}
              </Link>
            ))}
            {/* <a
              href={LOGIN_PORTAL_URL}
              target="_blank"
              rel="noopener noreferrer"
              className="nav-mobile-link"
              onClick={() => setIsOpen(false)}
            >
              Login
            </a> */}
            <div className="nav-mobile-actions">
              {isSubscribed ? (
                <Link
                  href={process.env.NEXT_PUBLIC_LOGIN_PORTAL_URL as string}
                  className="btn-primary w-full text-center flex items-center justify-center rounded-2xl"
                  onClick={(e) => {
                    handleLoginClick(e);
                    if (process.env.NEXT_PUBLIC_LOGIN_PORTAL_URL) {
                      setIsOpen(false);
                    }
                  }}
                >
                  Login
                </Link>
              ) : (
                <CheckoutButton
                  priceId={STRIPE_PLANS.MONTHLY}
                  className="btn-primary w-full text-center flex items-center justify-center rounded-2xl"
                >
                  Join the club
                </CheckoutButton>
              )}
              {/* <Link
                href="https://calendly.com/designshare/meeting"
                className="btn-primary-outline w-full text-center flex items-center justify-center rounded-2xl gap-3 font-bold"
                onClick={() => setIsOpen(false)}
                target="_blank"
                rel="noopener noreferrer"
              >
                <FiPhone />
                Book a call
              </Link> */}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
