import { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Menu, X, ChevronDown, ChevronUp, ArrowUp } from "lucide-react";
import LoginModal from "./LoginModal";
import logo from "../../assets/images/logo_plain.png";

const UniversalNavbar = () => {
  const navigate = useNavigate();
  const location = useLocation();

  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [openDropdown, setOpenDropdown] = useState(null);
  const [loginOpen, setLoginOpen] = useState(false);
  const [showScrollTop, setShowScrollTop] = useState(false);

  // Menu structure
  const menuItems = {
    sell: {
      label: "Sell Online",
      basePath: "/becomeaseller",
      items: [
        { label: "Create Account", path: "/becomeaseller#create" },
        { label: "List Products", path: "/becomeaseller#list" },
        { label: "Storage & Shipping", path: "/becomeaseller#storage" },
        { label: "Receive Payments", path: "/becomeaseller#payments" },
        { label: "Help & Support", path: "/becomeaseller#support" },
      ],
    },
    fee: {
      label: "Fee & Commission",
      basePath: "/feeandcom",
      items: [
        { label: "Payment Cycle", path: "/feeandcom#payment" },
        { label: "Fulfilment", path: "/feeandcom#fulfilment" },
        { label: "Calculate Margin", path: "/feeandcom#calculate" },
      ],
    },
    grow: {
      label: "Grow",
      basePath: "/grow",
      items: [
        { label: "Insights & Tools", path: "/grow#insights" },
        { label: "E-Sahakara Ads", path: "/grow#ads" },
        { label: "Shopping Festivals", path: "/grow#festivals" },
      ],
    },
    learn: {
      label: "Learn",
      basePath: "/learn",
      items: [
        { label: "Selling Tips", path: "/learn#tips" },
        { label: "Tools & Insights", path: "/learn#tools" },
        { label: "FAQs", path: "/learn#faqs" },
      ],
    },
  };

  // Toggle dropdown (closes others)
  const toggleDropdown = (key) => {
    setOpenDropdown((prev) => (prev === key ? null : key));
  };

  // Navigate to a path (path may include hash). We navigate to the full path,
  // then attempt to scroll to the hash (if any) after a tiny delay.
  const handleNavigation = (path) => {
    if (!path) return;
    // navigate to full path (including hash if provided)
    navigate(path);
    setMobileMenuOpen(false);
    setOpenDropdown(null);

    // If there's a hash, schedule scroll. The useEffect below will also handle it,
    // but scheduling here makes it snappier when clicking from the navbar.
    const hash = path.split("#")[1];
    if (hash) {
      setTimeout(() => {
        const el = document.getElementById(hash);
        if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
      }, 120);
    } else {
      // if no hash, scroll to top for cleanliness
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  };

  // When the location changes (including hash changes), if a hash exists,
  // scroll to it. This covers refresh / direct-link / same-route hash changes.
  useEffect(() => {
    const { hash } = location;
    if (hash) {
      const id = hash.replace("#", "");
      // small timeout to allow page/render to mount
      setTimeout(() => {
        const el = document.getElementById(id);
        if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
      }, 120);
    }
  }, [location.pathname, location.hash]);

  // Show back-to-top button after scrolling a bit
  useEffect(() => {
    const onScroll = () => setShowScrollTop(window.scrollY > 200);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const renderDropdown = (key, items, isMobile = false) => {
    const isOpen = openDropdown === key;
    return (
      <div key={key} className={`relative ${isMobile ? "" : "group"}`}>
        <div className={`flex items-center justify-between ${isMobile ? "py-2" : "cursor-pointer"}`}>
          {/* Main label — click navigates to basePath */}
          <button
            onClick={() => handleNavigation(menuItems[key].basePath)}
            className={`hover:text-orange-600 ${isMobile ? "text-left w-full" : ""}`}
          >
            {menuItems[key].label}
          </button>

          {/* Chevron toggle — visible on hover (desktop) or always on mobile; clicking chevron toggles dropdown */}
          <button
            onClick={(e) => {
              // stop main click from firing when chevron is clicked
              e.stopPropagation();
              toggleDropdown(key);
            }}
            className={`ml-2 transition-opacity ${isMobile ? "" : "opacity-0 group-hover:opacity-100"}`}
            aria-expanded={isOpen}
            aria-controls={`${key}-dropdown`}
          >
            {isOpen ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
          </button>
        </div>

        {/* Dropdown Menu */}
        {isOpen && (
          <div
            id={`${key}-dropdown`}
            className={`${
              isMobile
                ? "flex flex-col ml-3 mt-1"
                : "absolute top-full mt-2 bg-white border border-gray-200 rounded-lg shadow-lg py-1 w-56 z-30"
            }`}
          >
            {items.map((item) => (
              <button
                key={item.label}
                onClick={() => handleNavigation(item.path)}
                className={`text-left px-2 py-2 hover:text-orange-600 text-sm ${isMobile ? "block" : "w-full px-4 hover:bg-orange-50"}`}
              >
                {item.label}
              </button>
            ))}
          </div>
        )}
      </div>
    );
  };

  return (
    <>
      <nav className="bg-white shadow-md sticky top-0 z-50">
        <div className="flex items-center justify-between px-4 md:px-8 py-3">
          {/* Logo */}
          <div
            className="flex items-center gap-2 cursor-pointer"
            onClick={() => handleNavigation("/becomeaseller")}
          ><img src={logo} alt="Logo" className="w-10 h-10 object-contain" />


            <div className="flex flex-col leading-tight">
              <span className="font-bold text-2xl bg-gradient-to-r from-orange-600 to-yellow-400 bg-clip-text text-transparent">
                ESAHAKARA
              </span>
              <span className="font-bold text-sm text-gray-600">Products</span>
            </div>
          </div>

          {/* Desktop Menu */}
          <div className="hidden md:flex items-center space-x-6 font-medium text-gray-700">
            {Object.entries(menuItems).map(([key, value]) => renderDropdown(key, value.items))}
          </div>

          {/* Right Buttons */}
          <div className="hidden md:flex items-center space-x-3">
            <button
              onClick={() => setLoginOpen(true)}
              className="bg-orange-500 hover:bg-orange-600 text-white font-semibold px-4 py-2 rounded-lg shadow"
            >
              Login
            </button>
            <button
              onClick={() => handleNavigation("/startselling")}
              className="border border-orange-500 px-4 py-2 rounded-lg hover:text-orange-600 font-medium"
            >
              Start Selling
            </button>
          </div>

          {/* Mobile Toggle */}
          <button className="md:hidden ml-2" onClick={() => setMobileMenuOpen((s) => !s)}>
            {mobileMenuOpen ? <X size={24} /> : <Menu size={24} />}
          </button>
        </div>

        {/* Mobile Menu */}
        {mobileMenuOpen && (
          <div className="md:hidden flex flex-col space-y-1 px-4 pb-4">
            {Object.entries(menuItems).map(([key, value]) => renderDropdown(key, value.items, true))}

            <button
              onClick={() => setLoginOpen(true)}
              className="w-full bg-orange-500 text-white px-3 py-2 rounded-lg hover:bg-orange-600 mt-2"
            >
              Login
            </button>
            <button
              onClick={() => handleNavigation("/startselling")}
              className="w-full border border-orange-500 px-3 py-2 rounded-lg hover:text-orange-600"
            >
              Start Selling
            </button>
          </div>
        )}
      </nav>

      {/* Scroll to Top Button */}
      {showScrollTop && (
        <button
          onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
          className="fixed bottom-6 right-6 bg-orange-500 text-white p-3 rounded-full shadow-lg hover:bg-orange-600 transition-all"
          aria-label="Back to top"
        >
          <ArrowUp size={20} />
        </button>
      )}

      {/* Login Modal */}
      <LoginModal isOpen={loginOpen} onClose={() => setLoginOpen(false)} />
    </>
  );
};

export default UniversalNavbar;
