"use client";

import React, { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { HeaderData } from "@/types/navigation";
import { Logo } from "@/components/common/Logo";
import { NavDropdown } from "./NavDropdown";
import { MobileMenu } from "./MobileMenu";
import { Menu } from "lucide-react";
import type { SearchResult } from "@/app/api/search/route";

interface NavbarProps {
  data: HeaderData;
}

/**
 * Real "Earn Online" icon + markup from `templates/GAH/html/mod_menu/default.php`'s
 * `.affiliate-btn` — genuinely part of the live nav list (`<ul class="MyMenu">`),
 * confirmed by reading that file directly. An earlier pass here removed this
 * button after not finding it in `index.php`/`custom.js`, which was wrong —
 * it lives in the mega-menu module template, not the header shell.
 */
function EarnOnlineIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
      <rect width="18" height="18" rx="3.22388" fill="white" />
      <path
        d="M8.04923 11.7344V12.8763C8.04923 13.8438 7.14923 14.6256 6.0411 14.6256C4.93298 14.6256 4.02734 13.8438 4.02734 12.8763V11.7344C4.02734 12.7019 4.92735 13.3881 6.0411 13.3881C7.14923 13.3881 8.04923 12.6963 8.04923 11.7344Z"
        stroke="#5DA400" strokeWidth="0.8" strokeLinecap="round" strokeLinejoin="round"
      />
      <path
        d="M8.04702 10.189C8.04702 10.4703 7.96826 10.729 7.83326 10.954C7.50139 11.4997 6.82076 11.8428 6.03326 11.8428C5.24576 11.8428 4.56512 11.494 4.23325 10.954C4.09825 10.729 4.01953 10.4703 4.01953 10.189C4.01953 9.7053 4.24452 9.27217 4.60452 8.95717C4.97014 8.63655 5.47075 8.44531 6.02763 8.44531C6.5845 8.44531 7.08514 8.64217 7.45077 8.95717C7.82202 9.26655 8.04702 9.7053 8.04702 10.189Z"
        stroke="#5DA400" strokeWidth="0.8" strokeLinecap="round" strokeLinejoin="round"
      />
      <path
        d="M8.04923 10.1869V11.7337C8.04923 12.7012 7.14923 13.3875 6.0411 13.3875C4.93298 13.3875 4.02734 12.6956 4.02734 11.7337V10.1869C4.02734 9.21937 4.92735 8.4375 6.0411 8.4375C6.59798 8.4375 7.09862 8.63436 7.46424 8.94936C7.82424 9.26436 8.04923 9.70312 8.04923 10.1869Z"
        stroke="#5DA400" strokeWidth="0.8" strokeLinecap="round" strokeLinejoin="round"
      />
      <path
        d="M14.3734 8.41748V9.57626C14.3734 9.88563 14.1259 10.1387 13.8109 10.15H12.7084C12.1009 10.15 11.544 9.70561 11.4934 9.09811C11.4597 8.74374 11.5947 8.41186 11.8309 8.18124C12.039 7.96749 12.3259 7.84375 12.6409 7.84375H13.8109C14.1259 7.855 14.3734 8.1081 14.3734 8.41748Z"
        stroke="#5DA400" strokeWidth="0.8" strokeLinecap="round" strokeLinejoin="round"
      />
      <path
        d="M3.125 8.15625V7.03125C3.125 5.50125 4.0475 4.4325 5.48188 4.2525C5.62813 4.23 5.78 4.21875 5.9375 4.21875H11C11.1462 4.21875 11.2869 4.22437 11.4219 4.24687C12.8731 4.41562 13.8125 5.49 13.8125 7.03125V7.84688H12.6425C12.3275 7.84688 12.0406 7.97062 11.8325 8.18437C11.5962 8.41499 11.4613 8.74687 11.495 9.10125C11.5456 9.70875 12.1025 10.1531 12.71 10.1531H13.8125V10.9688C13.8125 12.6562 12.6875 13.7812 11 13.7812H9.59375"
        stroke="#5DA400" strokeWidth="0.8" strokeLinecap="round" strokeLinejoin="round"
      />
    </svg>
  );
}

/** Real search SVG from `templates/GAH/index.php`'s desktop `.search-btn`. */
function SearchIcon() {
  return (
    <svg width="19" height="19" viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path
        d="M18.9496 20.2082L12.1145 13.3731C11.5721 13.8071 10.9482 14.1507 10.243 14.4038C9.53781 14.657 8.7874 14.7836 7.99178 14.7836C6.02082 14.7836 4.35292 14.1008 2.98808 12.7352C1.62323 11.3696 0.940451 9.70174 0.939728 7.73151C0.939728 5.76055 1.62251 4.09265 2.98808 2.7278C4.35365 1.36296 6.02155 0.680175 7.99178 0.679452C9.96274 0.679452 11.631 1.36224 12.9966 2.7278C14.3621 4.09337 15.0446 5.76127 15.0438 7.73151C15.0438 8.52712 14.9173 9.27753 14.6641 9.98274C14.411 10.6879 14.0674 11.3118 13.6334 11.8542L20.4685 18.6893L18.9496 20.2082ZM7.99178 12.6137C9.34795 12.6137 10.5009 12.1392 11.4505 11.1903C12.4002 10.2413 12.8747 9.08839 12.874 7.73151C12.874 6.37534 12.3995 5.22278 11.4505 4.27383C10.5016 3.32488 9.34867 2.85004 7.99178 2.84931C6.63562 2.84931 5.48306 3.32415 4.53411 4.27383C3.58515 5.22351 3.11031 6.37607 3.10959 7.73151C3.10959 9.08767 3.58443 10.2406 4.53411 11.1903C5.48378 12.1399 6.63634 12.6144 7.99178 12.6137Z"
        fill="#4E6C2F"
      />
    </svg>
  );
}

/** Real 3-bar hamburger SVG icon from `templates/GAH/index.php`. */
function HamburgerIcon() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M4 6H20" stroke="#2A2A2A" strokeWidth="2.0" strokeLinecap="round" />
      <path d="M4 12H20" stroke="#2A2A2A" strokeWidth="2.0" strokeLinecap="round" />
      <path d="M4 18H20" stroke="#2A2A2A" strokeWidth="2.0" strokeLinecap="round" />
    </svg>
  );
}

// Real "Company" flyout (`.toggle-btn`, `mod_menu/default.php`) — a
// desktop-only dropdown, distinct from the mobile drawer hamburger.
// Hrefs confirmed against the live site's own links.
const COMPANY_SUBMENU_LINKS: { label: string; href: string }[] = [
  { label: "Our Services", href: "/our-services" },
  { label: "Mission & Vision", href: "/vision-and-mission" },
  // The live template's own hardcoded href is "/how-it-works" (plural),
  // but that 404s against this local Joomla install's actual article
  // alias — "/how-it-work" is what really resolves here, so that's what's used.
  { label: "How it Works", href: "/how-it-work" },
  { label: "Reviews", href: "/reviews" },
  { label: "Guarantees", href: "/guarantees" },
  { label: "FAQ", href: "/faq" },
  { label: "About us", href: "/about-us" },
  { label: "Why Choose Us", href: "/why-choose-us" },
  { label: "Contact Us", href: "/contact-us" },
];

const COMPANY_MENU_ROWS: { label: string; href: string }[] = [
  { label: "Company", href: "/our-services" },
  { label: "Pricing", href: "/pricing" },
  { label: "Offers", href: "/offers" },
  { label: "Answers", href: "/answers" },
];

export const Navbar: React.FC<NavbarProps> = ({ data }) => {
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [searchResults, setSearchResults] = useState<SearchResult[] | null>(null);
  // Real threshold + toggle from `custom.js`'s scroll handler (`scrollTop() <= 5`);
  // `.sticky`'s `animation: mymove 0.8s ease-in-out` replays each time the class
  // is (re)added, reproduced here via the `header-sticky` CSS class (app/header-animations.css).
  const [isScrolled, setIsScrolled] = useState(false);
  const [isCompanyMenuOpen, setIsCompanyMenuOpen] = useState(false);
  const [isCompanyRowHovered, setIsCompanyRowHovered] = useState(false);
  const searchBoxRef = useRef<HTMLDivElement>(null);
  const companyMenuRef = useRef<HTMLDivElement>(null);

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

  // Real behavior: debounced live search against the Joomla search index
  // (see app/api/search/route.ts), falling back to the site's real popular
  // searches (data.popularSearches, itself derived from the live mega menu)
  // when the box is empty — matching the live template's "Popular Search"
  // panel shown before the visitor types anything.
  useEffect(() => {
    if (!isSearchOpen) return;
    if (!searchQuery.trim()) {
      setSearchResults(null);
      return;
    }
    const controller = new AbortController();
    const timeout = setTimeout(async () => {
      try {
        const res = await fetch(`/api/search?q=${encodeURIComponent(searchQuery)}`, {
          signal: controller.signal,
        });
        const json = await res.json();
        setSearchResults(json.results || []);
      } catch {
        // Keep whatever was shown before; a transient failure isn't worth flashing an error here.
      }
    }, 600); // matches the live template's debounce
    return () => {
      clearTimeout(timeout);
      controller.abort();
    };
  }, [searchQuery, isSearchOpen]);

  useEffect(() => {
    if (!isSearchOpen) return;
    const onClickOutside = (e: MouseEvent) => {
      if (searchBoxRef.current && !searchBoxRef.current.contains(e.target as Node)) {
        setIsSearchOpen(false);
      }
    };
    const onEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape") setIsSearchOpen(false);
    };
    document.addEventListener("click", onClickOutside);
    document.addEventListener("keydown", onEscape);
    return () => {
      document.removeEventListener("click", onClickOutside);
      document.removeEventListener("keydown", onEscape);
    };
  }, [isSearchOpen]);

  useEffect(() => {
    if (!isCompanyMenuOpen) return;
    const onClickOutside = (e: MouseEvent) => {
      if (companyMenuRef.current && !companyMenuRef.current.contains(e.target as Node)) {
        setIsCompanyMenuOpen(false);
      }
    };
    const onEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape") setIsCompanyMenuOpen(false);
    };
    document.addEventListener("click", onClickOutside);
    document.addEventListener("keydown", onEscape);
    return () => {
      document.removeEventListener("click", onClickOutside);
      document.removeEventListener("keydown", onEscape);
    };
  }, [isCompanyMenuOpen]);

  // There's no dedicated `/search` results page in this app yet (the live
  // template's own `searchwithinput()` just redirects to one) — until that
  // exists, "submit" goes to the closest real thing available: the top live
  // match already fetched for this query.
  const submitSearch = () => {
    const topResult = searchResults?.[0];
    if (topResult) {
      window.location.href = topResult.href;
    }
  };

  const suggestions = searchResults ?? data.popularSearches;
  const suggestionsLabel = searchResults ? "Search results" : "Popular Search";

  return (
    <nav
      className={`bg-white transition-shadow ${isScrolled ? "shadow-[0_3px_6px_rgba(0,0,0,0.16)] header-sticky" : ""
        }`}
    >
      <div className="max-w-7xl mx-auto max-[359px]:px-2 px-4 sm:px-6 lg:px-8">
        {/* Single row — real `.menu-mainnew`/`.MyMenu` (`display:flex; align-items:center`):
            logo, then nav links, `.affiliate-btn`, `.login-sticky`, `.order_btn`,
            search and the hamburger all as flex siblings of one row — not split
            across two rows as an earlier pass here assumed. */}
        <div className="flex items-center justify-between h-16 lg:h-[72px] max-[359px]:gap-1 gap-3">
          <div className="flex-shrink-0 flex items-center">
            <Logo />
          </div>

          <div className="hidden lg:flex items-center space-x-1 xl:space-x-2">
            {data.mainNav.map((item) => (
              <NavDropdown key={item.id} item={item} />
            ))}
          </div>

          <div className="flex items-center shrink-0 max-[359px]:gap-1 gap-2 sm:gap-3">
            {/* Real `.affiliate-btn` — gradient + constant diagonal shine sweep */}
            <Link
              href={data.cta.earnOnlineUrl}
              className="header-shine-btn hidden xl:inline-flex items-center gap-1.5 whitespace-nowrap text-xs font-bold text-white px-[7px] py-1.5 rounded-[3px]"
              style={{
                background: "linear-gradient(90deg, #639E15 0%, #506634 100%)",
                boxShadow: "0px 1px 2px -1px rgba(0,0,0,0.1), 0px 1px 3px 0px rgba(0,0,0,0.1)",
              }}
            >
              <EarnOnlineIcon />
              <span>Earn Online</span>
            </Link>

            {/* Real `.login-new` — gradient fill, border-draw-on-hover SVG outline */}
            <Link
              href={data.cta.loginUrl}
              className="header-login-group hidden sm:inline-flex relative items-center px-4 py-1.5 rounded-[3px] text-white text-xs font-bold overflow-visible"
              style={{ background: "linear-gradient(96.16deg, #456228 11.84%, #5F8F2D 97.09%)" }}
            >
              <svg
                className="absolute inset-0 w-full h-full pointer-events-none"
                viewBox="0 0 77.5 26"
                preserveAspectRatio="none"
                fill="none"
              >
                <polyline points="76.5,1 76.5,25 1,25 1,1 76.5,1" stroke="rgba(255,255,255,0.25)" strokeWidth="1" />
                <polyline
                  points="76.5,1 76.5,25 1,25 1,1 76.5,1"
                  stroke="#ffe002"
                  strokeWidth="2"
                  className="header-login-border"
                />
              </svg>
              <span className="relative">Login</span>
            </Link>

            {/* Real `.order_btn a` — continuously pulsing orange pill */}
            <Link
              href={data.cta.orderNowUrl}
              className="header-order-pulse inline-flex items-center justify-center whitespace-nowrap text-xs font-bold text-white bg-[#f58e0e] hover:bg-[#e78e21] max-[359px]:px-2.5 px-4 py-1.5 rounded-full transition-colors"
            >
              Order Now
            </Link>

            {/* Search — real `.search-field` trigger + `.recent-box` card */}
            <div className="relative" ref={searchBoxRef}>
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  setIsSearchOpen((v) => !v);
                }}
                className="p-1.5 rounded-full hover:bg-slate-100 transition-colors"
                aria-label="Search"
              >
                <SearchIcon />
              </button>

              {isSearchOpen && (
                <div
                  className="absolute right-0 top-[calc(100%+8px)] w-[320px] sm:w-[380px] rounded-[10px] bg-white p-[15px] z-50"
                  style={{ boxShadow: "0px 0px 4px 0px rgba(0,0,0,0.25)" }}
                  onClick={(e) => e.stopPropagation()}
                >
                  <div className="flex items-center gap-2 border border-[#B3B3B3] rounded-[18px] px-3 py-2">
                    <input
                      type="text"
                      placeholder="Search..."
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      onKeyDown={(e) => e.key === "Enter" && submitSearch()}
                      autoFocus
                      className="flex-1 bg-transparent text-sm text-[#2A2A2A] placeholder-[#B5B5B5] focus:outline-none"
                    />
                    <button onClick={submitSearch} aria-label="Submit search" className="shrink-0">
                      <SearchIcon />
                    </button>
                  </div>

                  {suggestions.length > 0 && (
                    <div className="mt-3 flex flex-col gap-2.5">
                      <p className="text-[13px] font-semibold text-[#4a8406]">{suggestionsLabel}</p>
                      {suggestions.slice(0, 8).map((item) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          onClick={() => setIsSearchOpen(false)}
                          className="text-[13px] text-[#727070] hover:text-[#4E6C2F]"
                        >
                          {item.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* Real `.toggle-btn` "Company" flyout — desktop-only, bars
                morph into an X on hover/open, distinct from the mobile
                drawer hamburger below. */}
            <div
              className="relative hidden lg:block"
              ref={companyMenuRef}
              onMouseEnter={() => setIsCompanyMenuOpen(true)}
              onMouseLeave={() => {
                setIsCompanyMenuOpen(false);
                setIsCompanyRowHovered(false);
              }}
            >
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  setIsCompanyMenuOpen((v) => !v);
                }}
                className={`toggle-btn p-1.5 flex flex-col items-center justify-center cursor-pointer ${isCompanyMenuOpen ? "is-open" : ""
                  }`}
                aria-label="Company menu"
                aria-expanded={isCompanyMenuOpen}
              >
                <span className="toggle-bar toggle-bar-1" />
                <span className="toggle-bar toggle-bar-2" />
                <span className="toggle-bar toggle-bar-3" />
              </button>

              {isCompanyMenuOpen && (
                <div
                  className="absolute right-0 top-[calc(100%-2px)] flex rounded-[10px] bg-white p-[15px] gap-8 z-50"
                  style={{ boxShadow: "0px 0px 4px 0px rgba(0,0,0,0.25)" }}
                  onClick={(e) => e.stopPropagation()}
                >
                  {/* Submenu — only appears while hovering the "Company" row itself */}
                  {isCompanyRowHovered && (
                    <div className="flex flex-col gap-2 min-w-[140px]">
                      {COMPANY_SUBMENU_LINKS.map((link) => (
                        <Link
                          key={link.href}
                          href={link.href}
                          onClick={() => setIsCompanyMenuOpen(false)}
                          className="rounded-[6px] px-2 py-1.5 text-sm text-black hover:bg-[#4E6C2F] hover:text-white"
                        >
                          {link.label}
                        </Link>
                      ))}
                    </div>
                  )}

                  <div className="flex flex-col gap-2 min-w-[140px]">
                    {COMPANY_MENU_ROWS.map((row) => {
                      const isCompanyRow = row.label === "Company";
                      return (
                        <Link
                          key={row.href}
                          href={row.href}
                          onClick={() => setIsCompanyMenuOpen(false)}
                          onMouseEnter={() => setIsCompanyRowHovered(isCompanyRow)}
                          className={`rounded-[6px] px-2 py-1.5 text-sm whitespace-nowrap transition-colors ${isCompanyRow && isCompanyRowHovered
                            ? "bg-[#4E6C2F] text-white"
                            : "text-[#2a2a2a] hover:bg-[#4E6C2F] hover:text-white"
                            }`}
                        >
                          {row.label}
                        </Link>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>

            {/* Hamburger — real `.menubtn`: static icon, no morph on open */}
            <button
              onClick={() => setIsMobileMenuOpen(true)}
              className="lg:hidden p-1.5 rounded-md text-[#2a2a2a] hover:bg-slate-100 transition-colors flex items-center justify-center cursor-pointer"
              aria-label="Open Navigation Menu"
            >
              <HamburgerIcon />
            </button>
          </div>
        </div>
      </div>

      {/* Mobile Navigation Drawer */}
      <MobileMenu
        isOpen={isMobileMenuOpen}
        onClose={() => setIsMobileMenuOpen(false)}
        menuItems={data.mainNav}
        topBarData={data.topBar}
        ctaData={data.cta}
      />
    </nav>
  );
};
