"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useRef, useState } from "react";

const LIGHT_THEME_ROUTES = [
  "/about",
  "/careers",
  "/contact",
  "/calculator",
  "/privacy",
  "/faq",
  "/aml",
  "/terms",
  "/account"
];

type FeatureItem = {
  label: string;
  href: string;
  iconSrc: string;
  comingSoon?: boolean;
};

function ChevronRight() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden>
      <path
        d="M9 6L15 12L9 18"
        stroke="#9ca3af"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

const featureItems: FeatureItem[] = [
  { label: "Trade Crypto", href: "/crypto", iconSrc: "/assets/icons/crypto.svg" },
  { label: "Buy/Sell giftcard", href: "/giftcards", iconSrc: "/assets/icons/giftcard.svg" },
  { label: "Make Bill Payments", href: "/bills", iconSrc: "/assets/icons/bill.svg" },
  { label: "Send and recieve money", href: "/transfers", iconSrc: "/assets/icons/send.svg" },
  { label: "E-Sim", href: "", iconSrc: "/assets/icons/esim.svg", comingSoon: true },
];

function FeaturesDropdown({ onItemClick }: { onItemClick: () => void }) {
  return (
    <div className="absolute left-0 top-full z-50 mt-3 w-[350px] rounded-2xl bg-white p-3 text-coast-ink shadow-[0_30px_60px_-20px_rgba(2,16,58,0.35)]">
      <ul className="flex flex-col">
        {featureItems.map((item) => (
          <li key={item.label}>
            <Link
              href={item.href}
              onClick={onItemClick}
              className="flex items-center gap-4 rounded-xl px-3 py-3 transition hover:bg-coast-blue-soft/40"
            >
              <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg">
                <Image src={item.iconSrc} alt="" width={20} height={20} className="h-5 w-5" />
              </span>
              <span className="flex flex-1 items-center gap-3 text-[16px] font-semibold">
                {item.label}
                {item.comingSoon && (
                  <span className="rounded-md bg-coast-blue px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider text-white">
                    Coming Soon
                  </span>
                )}
              </span>
              <ChevronRight />
            </Link>
          </li>
        ))}
      </ul>
    </div>
  );
}

type CompanyItem = {
  label: string;
  href: string;
  iconSrc: string;
};


const companyItems: CompanyItem[] = [
  { label: "About", href: "/about", iconSrc: "/assets/icons/about.svg" },
  { label: "Careers", href: "/careers", iconSrc: "/assets/icons/career.svg" },
];

function CompanyDropdown({ onItemClick }: { onItemClick: () => void }) {
  return (
    <div className="absolute left-0 top-full z-50 mt-3 w-[300px] rounded-2xl bg-white p-3 text-coast-ink shadow-[0_30px_60px_-20px_rgba(2,16,58,0.35)]">
      <ul className="flex flex-col">
        {companyItems.map((item) => (
          <li key={item.label}>
            <Link
              href={item.href}
              onClick={onItemClick}
              className="flex items-center gap-4 rounded-xl px-3 py-3 transition hover:bg-coast-blue-soft/40"
            >
              <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg">
                <Image src={item.iconSrc} alt="" width={20} height={20} className="h-5 w-5" />
              </span>
              <span className="flex-1 text-[16px] font-semibold">{item.label}</span>
              <ChevronRight />
            </Link>
          </li>
        ))}
      </ul>
    </div>
  );
}

type SupportItem = {
  label: string;
  href: string;
  iconSrc: string;
};


const supportItems: SupportItem[] = [
  { label: "FAQs", href: "/faq", iconSrc: "/assets/icons/faq.svg" },
  { label: "Contact Us", href: "/contact", iconSrc: "/assets/icons/contact.svg" },
];

function SupportDropdown({ onItemClick }: { onItemClick: () => void }) {
  return (
    <div className="absolute left-0 top-full z-50 mt-3 w-[300px] rounded-2xl bg-white p-3 text-coast-ink shadow-[0_30px_60px_-20px_rgba(2,16,58,0.35)]">
      <ul className="flex flex-col">
        {supportItems.map((item) => (
          <li key={item.label}>
            <Link
              href={item.href}
              onClick={onItemClick}
              className="flex items-center gap-4 rounded-xl px-3 py-3 transition hover:bg-coast-blue-soft/40"
            >
              <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg">
                <Image src={item.iconSrc} alt="" width={20} height={20} className="h-5 w-5" />
              </span>
              <span className="flex-1 text-[16px] font-semibold">{item.label}</span>
              <ChevronRight />
            </Link>
          </li>
        ))}
      </ul>
    </div>
  );
}

function ChevronDown({ className = "" }: { className?: string }) {
  return (
    <svg className={className} width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden>
      <path
        d="M2.5 4.5L6 8L9.5 4.5"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export default function Navbar() {
  const [mobileOpen, setMobileOpen] = useState(false);
  const [openMenu, setOpenMenu] = useState<string | null>(null);
  const navRef = useRef<HTMLElement>(null);
  const pathname = usePathname();
  const isLightTheme = LIGHT_THEME_ROUTES.some(
    (route) => pathname === route || pathname?.startsWith(`${route}/`),
  );
  const logoSrc = isLightTheme
    ? "/assets/images/logo-black.svg"
    : "/assets/images/coast-logo.svg";
  const linkClass = isLightTheme
    ? "text-coast-navy/85 hover:text-coast-navy"
    : "text-white/90 hover:text-white";
  const chevronOpacity = isLightTheme ? "opacity-60" : "opacity-70";
  const mobileButtonClass = isLightTheme ? "text-coast-navy" : "text-white";

  useEffect(() => {
    if (!openMenu) return;
    function onClick(e: MouseEvent) {
      if (navRef.current && !navRef.current.contains(e.target as Node)) {
        setOpenMenu(null);
      }
    }
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") setOpenMenu(null);
    }
    document.addEventListener("mousedown", onClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [openMenu]);

  const navLinks = [
    { label: "Products", hasMenu: true },
    { label: "Company", hasMenu: true },
    { label: "Support", hasMenu: true },
    { label: "Blog", hasMenu: false, href: "https://blog.coast.ng/" },
    { label: "Calculator", hasMenu: false, href: "/calculator" },
  ];

  return (
    <header className="relative w-full" ref={navRef}>
      <nav className="mx-auto flex max-w-[1280px] items-center justify-between px-5 py-5 md:px-10 md:py-7">
        <Link href="/" aria-label="Coast home" className="shrink-0">
          <Image
            src={logoSrc}
            alt="Coast"
            width={120}
            height={28}
            priority
            className="h-7 w-auto md:h-8"
          />
        </Link>

        <ul className="hidden items-center gap-8 lg:flex">
          {navLinks.map((link) => {
            if (!link.hasMenu) {
              return (
                <li key={link.label}>
                  <Link
                    href={link.href ?? "#"}
                    className={`text-[15px] font-medium transition ${linkClass}`}
                  >
                    {link.label}
                  </Link>
                </li>
              );
            }
            const isOpen = openMenu === link.label;
            return (
              <li key={link.label} className="relative">
                <button
                  type="button"
                  aria-expanded={isOpen}
                  onClick={() => setOpenMenu(isOpen ? null : link.label)}
                  className={`flex items-center gap-1.5 text-[15px] font-medium transition ${linkClass}`}
                >
                  {link.label}
                  <ChevronDown
                    className={`${chevronOpacity} transition-transform ${isOpen ? "rotate-180" : ""}`}
                  />
                </button>
                {isOpen && link.label === "Products" && (
                  <FeaturesDropdown onItemClick={() => setOpenMenu(null)} />
                )}
                {isOpen && link.label === "Company" && (
                  <CompanyDropdown onItemClick={() => setOpenMenu(null)} />
                )}
                {isOpen && link.label === "Support" && (
                  <SupportDropdown onItemClick={() => setOpenMenu(null)} />
                )}
              </li>
            );
          })}
        </ul>

        <div className="hidden lg:block">
          <Link
            href="https://apps.apple.com/us/app/coast-trade-digital-assets/id6444920508"
            className="inline-flex items-center justify-center rounded-xl bg-coast-blue px-6 py-3 text-[15px] font-semibold text-white shadow-[0_8px_24px_-8px_rgba(31,92,255,0.6)] transition hover:bg-coast-blue/90"
          >
            Download App
          </Link>
        </div>

        <button
          type="button"
          aria-label="Toggle menu"
          aria-expanded={mobileOpen}
          onClick={() => setMobileOpen((v) => !v)}
          className={`inline-flex h-10 w-10 items-center justify-center rounded-lg lg:hidden ${mobileButtonClass}`}
        >
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" aria-hidden>
            {mobileOpen ? (
              <path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
            ) : (
              <>
                <path d="M4 7H20" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                <path d="M4 12H20" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                <path d="M4 17H20" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
              </>
            )}
          </svg>
        </button>
      </nav>

      {mobileOpen && (
        <div
          className={`mx-5 mb-4 rounded-2xl p-4 lg:hidden ${isLightTheme ? "bg-coast-navy/5" : "bg-white/5 backdrop-blur"
            }`}
        >
          <ul className="flex flex-col">
            {navLinks.map((link) => {
              if (!link.hasMenu) {
                return (
                  <li key={link.label}>
                    <Link
                      href={link.href ?? "#"}
                      onClick={() => setMobileOpen(false)}
                      className={`flex w-full items-center justify-between py-3 text-[15px] font-medium ${linkClass}`}
                    >
                      {link.label}
                    </Link>
                  </li>
                );
              }

              const isOpen = openMenu === link.label;
              const items =
                link.label === "Products"
                  ? featureItems
                  : link.label === "Company"
                    ? companyItems
                    : link.label === "Support"
                      ? supportItems
                      : [];

              return (
                <li key={link.label}>
                  <button
                    type="button"
                    onClick={() => setOpenMenu(isOpen ? null : link.label)}
                    aria-expanded={isOpen}
                    className={`flex w-full items-center justify-between py-3 text-[15px] font-medium ${linkClass}`}
                  >
                    <span>{link.label}</span>
                    <ChevronDown
                      className={`${chevronOpacity} transition-transform ${isOpen ? "rotate-180" : ""}`}
                    />
                  </button>
                  {isOpen && (
                    <ul className="mb-2 ml-2 flex flex-col gap-1 border-l-2 border-coast-blue/30 pl-3">
                      {items.map((item) => (
                        <li key={item.label}>
                          <Link
                            href={item.href}
                            onClick={() => {
                              setOpenMenu(null);
                              setMobileOpen(false);
                            }}
                            className={`flex items-center gap-3 rounded-lg px-2 py-2.5 text-[14px] font-medium ${linkClass}`}
                          >
                            <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded">
                              <Image
                                src={item.iconSrc}
                                alt=""
                                width={16}
                                height={16}
                                className="h-4 w-4"
                              />
                            </span>
                            <span className="flex-1">{item.label}</span>
                            {(item as FeatureItem).comingSoon ? (
                              <span className="rounded-md bg-coast-blue px-2 py-0.5 text-[9px] font-bold uppercase tracking-wider text-white">
                                Soon
                              </span>
                            ) : null}
                          </Link>
                        </li>
                      ))}
                    </ul>
                  )}
                </li>
              );
            })}
            <li className="pt-3">
              <Link
                href="#download"
                onClick={() => setMobileOpen(false)}
                className="block w-full rounded-xl bg-coast-blue px-6 py-3 text-center text-[15px] font-semibold text-white"
              >
                Download App
              </Link>
            </li>
          </ul>
        </div>
      )}
    </header>
  );
}
