"use client";

import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import Logo from "./Logo";
import { useTheme, useCurrency, type Currency } from "./Providers";
import { serviceIconMap } from "./ServiceIcons";

const megaServices = [
  { slug: "sms-marketing", title: "SMS Marketing", desc: "Bulk SMS with custom Sender IDs & OTP", href: "/services/sms-marketing", basePrice: 9.99 },
  { slug: "email-marketing", title: "Email Marketing", desc: "Automated drip campaigns with A/B testing", href: "/services/email-marketing", basePrice: 7.99 },
  { slug: "social-media-marketing", title: "Social Media Marketing", desc: "Schedule & analyse across all platforms", href: "/services/social-media-marketing", basePrice: 14.99 },
  { slug: "pbx-voip", title: "PBX & VoIP", desc: "Cloud PBX, SIP trunking & call centers", href: "/services/pbx-voip", basePrice: 19.99 },
  { slug: "chat-crm-chatbot", title: "Chat CRM & Chatbot", desc: "Live chat, AI chatbots & multi-channel", href: "/services/chat-crm-chatbot", basePrice: 12.99 },
  { slug: "crm", title: "CRM", desc: "Pipelines, automation & AI insights", href: "/services/crm", basePrice: 12.99 },
  { slug: "analytics", title: "Analytics", desc: "Real-time dashboards & campaign analytics", href: "/services/analytics", basePrice: 9.99 },
  { slug: "support-tickets", title: "Support Tickets", desc: "Multi-channel inbox, SLA & unlimited agents", href: "/services/support-tickets", basePrice: 14.99 },
];

const CURRENCIES: { value: Currency; label: string; symbol: string }[] = [
  { value: "usd", label: "USD", symbol: "$" },
  { value: "lkr", label: "LKR", symbol: "Rs." },
  { value: "eur", label: "EUR", symbol: "€" },
];

export default function Navbar() {
  const { theme, toggle } = useTheme();
  const { currency, setCurrency, meta } = useCurrency();

  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [megaOpen, setMegaOpen] = useState(false);
  const [currencyOpen, setCurrencyOpen] = useState(false);
  const [mobileServicesOpen, setMobileServicesOpen] = useState(false);

  const megaRef = useRef<HTMLLIElement>(null);
  const currencyRef = useRef<HTMLDivElement>(null);
  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

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

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (megaRef.current && !megaRef.current.contains(e.target as Node)) setMegaOpen(false);
      if (currencyRef.current && !currencyRef.current.contains(e.target as Node)) setCurrencyOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const handleMegaEnter = () => { if (closeTimer.current) clearTimeout(closeTimer.current); setMegaOpen(true); };
  const handleMegaLeave = () => { closeTimer.current = setTimeout(() => setMegaOpen(false), 120); };

  const isDark = theme === "dark";

  return (
    <header
      className="fixed top-0 left-0 right-0 z-50 transition-all duration-300"
      style={{
        background: scrolled ? "var(--nav-scrolled)" : "transparent",
        backdropFilter: scrolled ? "blur(14px)" : "none",
        borderBottom: scrolled ? "1px solid var(--border)" : "none",
        boxShadow: scrolled ? "0 2px 20px rgba(0,0,0,0.08)" : "none",
      }}
    >
      <nav className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-20 flex items-center justify-between gap-4">
        {/* Logo */}
        <Link href="/" className="flex items-center flex-shrink-0">
          <Logo markSize={36} showText={true} />
        </Link>

        {/* Desktop Nav */}
        <ul className="hidden md:flex items-center gap-0.5 flex-1 justify-center">
          <li>
            <Link href="/" className="px-3.5 py-2 rounded-lg text-sm font-medium transition-all duration-200" style={{ color: "var(--fg2)" }}
              onMouseEnter={e => (e.currentTarget.style.color = "var(--fg1)")}
              onMouseLeave={e => (e.currentTarget.style.color = "var(--fg2)")}>
              Home
            </Link>
          </li>
          <li>
            <Link href="/about" className="px-3.5 py-2 rounded-lg text-sm font-medium transition-all duration-200" style={{ color: "var(--fg2)" }}
              onMouseEnter={e => { e.currentTarget.style.color = "var(--fg1)"; e.currentTarget.style.background = "var(--card-bg)"; }}
              onMouseLeave={e => { e.currentTarget.style.color = "var(--fg2)"; e.currentTarget.style.background = "transparent"; }}>
              About
            </Link>
          </li>

          {/* Services mega trigger */}
          <li ref={megaRef} className="relative" onMouseEnter={handleMegaEnter} onMouseLeave={handleMegaLeave}>
            <button
              onClick={() => setMegaOpen(!megaOpen)}
              className="flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-sm font-medium transition-all duration-200"
              style={{ color: megaOpen ? "var(--fg1)" : "var(--fg2)", background: megaOpen ? "var(--card-bg)" : "transparent" }}
            >
              Services
              <svg className={`w-3.5 h-3.5 transition-transform duration-200 ${megaOpen ? "rotate-180" : ""}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M19 9l-7 7-7-7" />
              </svg>
            </button>

            {megaOpen && (
              <div
                className="absolute top-full left-1/2 -translate-x-1/2 mt-3 w-[720px] rounded-2xl shadow-2xl overflow-hidden"
                style={{ background: "var(--bg2)", border: "1px solid var(--border)" }}
                onMouseEnter={handleMegaEnter}
                onMouseLeave={handleMegaLeave}
              >
                <div className="px-6 py-4 flex items-center justify-between" style={{ borderBottom: "1px solid var(--border)" }}>
                  <div>
                    <p className="font-bold text-sm" style={{ color: "var(--fg1)" }}>All Services</p>
                    <p className="text-xs" style={{ color: "var(--fg3)" }}>8 powerful tools in one platform</p>
                  </div>
                  <Link href="/services" onClick={() => setMegaOpen(false)} className="text-[#28c76f] text-xs font-semibold hover:text-[#22b965] transition-colors flex items-center gap-1">
                    View all →
                  </Link>
                </div>

                <div className="grid grid-cols-2 gap-px" style={{ background: "var(--border)" }}>
                  {megaServices.map((s) => {
                    const Icon = serviceIconMap[s.slug];
                    return (
                    <Link key={s.title} href={s.href} onClick={() => setMegaOpen(false)}
                      className="flex items-start gap-3 p-4 group transition-colors"
                      style={{ background: "var(--bg2)" }}
                      onMouseEnter={e => (e.currentTarget.style.background = "var(--bg3)")}
                      onMouseLeave={e => (e.currentTarget.style.background = "var(--bg2)")}
                    >
                      <span className="flex-shrink-0 w-9 h-9 mt-0.5">{Icon && <Icon size={36} />}</span>
                      <div>
                        <p className="text-sm font-semibold group-hover:text-[#28c76f] transition-colors" style={{ color: "var(--fg1)" }}>{s.title}</p>
                        <p className="text-xs mt-0.5" style={{ color: "var(--fg3)" }}>{s.desc}</p>
                        <p className="text-xs font-medium mt-1.5 text-[#28c76f]">From {meta.symbol}{meta.label === "LKR" ? Math.round(s.basePrice * 325).toLocaleString() : meta.label === "EUR" ? (s.basePrice * 0.92).toFixed(2) : s.basePrice.toFixed(2)}/mo</p>
                      </div>
                    </Link>
                    );
                  })}
                </div>

                <div className="px-6 py-4 flex items-center justify-between" style={{ borderTop: "1px solid var(--border)", background: "var(--bg1)" }}>
                  <p className="text-xs" style={{ color: "var(--fg3)" }}>
                    Bundle all 8 services and <span className="text-[#28c76f] font-semibold">save 40%+</span>
                  </p>
                  <Link href="/pricing" onClick={() => setMegaOpen(false)} className="px-4 py-2 rounded-lg bg-[#28c76f] hover:bg-[#22b965] text-white text-xs font-semibold transition-all shadow-md shadow-[#28c76f]/20">
                    See Combo Plans →
                  </Link>
                </div>
              </div>
            )}
          </li>

          <li>
            <Link href="/pricing" className="px-3.5 py-2 rounded-lg text-sm font-medium transition-all duration-200" style={{ color: "var(--fg2)" }}
              onMouseEnter={e => { e.currentTarget.style.color = "var(--fg1)"; e.currentTarget.style.background = "var(--card-bg)"; }}
              onMouseLeave={e => { e.currentTarget.style.color = "var(--fg2)"; e.currentTarget.style.background = "transparent"; }}>
              Pricing
            </Link>
          </li>
          <li>
            <Link href="/contact" className="px-3.5 py-2 rounded-lg text-sm font-medium transition-all duration-200" style={{ color: "var(--fg2)" }}
              onMouseEnter={e => { e.currentTarget.style.color = "var(--fg1)"; e.currentTarget.style.background = "var(--card-bg)"; }}
              onMouseLeave={e => { e.currentTarget.style.color = "var(--fg2)"; e.currentTarget.style.background = "transparent"; }}>
              Contact
            </Link>
          </li>
        </ul>

        {/* Right controls */}
        <div className="hidden md:flex items-center gap-2">
          {/* Currency switcher */}
          <div ref={currencyRef} className="relative">
            <button
              onClick={() => setCurrencyOpen(!currencyOpen)}
              className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-semibold transition-all duration-200"
              style={{ color: "var(--fg1)", background: "var(--card-bg)", border: "1px solid var(--border)" }}
            >
              <span className="text-[#28c76f]">{meta.symbol}</span>
              {meta.label}
              <svg className={`w-3 h-3 transition-transform ${currencyOpen ? "rotate-180" : ""}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M19 9l-7 7-7-7" />
              </svg>
            </button>
            {currencyOpen && (
              <div className="absolute top-full right-0 mt-2 w-32 rounded-xl overflow-hidden shadow-xl z-50" style={{ background: "var(--bg2)", border: "1px solid var(--border)" }}>
                {CURRENCIES.map((c) => (
                  <button
                    key={c.value}
                    onClick={() => { setCurrency(c.value); setCurrencyOpen(false); }}
                    className="w-full flex items-center gap-2 px-4 py-2.5 text-sm font-medium transition-colors"
                    style={{
                      color: currency === c.value ? "#28c76f" : "var(--fg2)",
                      background: currency === c.value ? "rgba(40,199,111,0.08)" : "transparent",
                    }}
                    onMouseEnter={e => { if (currency !== c.value) e.currentTarget.style.background = "var(--card-bg)"; }}
                    onMouseLeave={e => { if (currency !== c.value) e.currentTarget.style.background = "transparent"; }}
                  >
                    <span className="font-bold w-6">{c.symbol}</span>
                    {c.label}
                    {currency === c.value && (
                      <svg className="w-3 h-3 ml-auto text-[#28c76f]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
                      </svg>
                    )}
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Theme toggle */}
          <button
            onClick={toggle}
            className="p-2 rounded-lg transition-all duration-200"
            style={{ background: "var(--card-bg)", border: "1px solid var(--border)", color: "var(--fg2)" }}
            aria-label="Toggle theme"
          >
            {isDark ? (
              <svg className="w-4.5 h-4.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364-6.364l-.707.707M6.343 17.657l-.707.707M17.657 17.657l-.707-.707M6.343 6.343l-.707-.707M12 5a7 7 0 100 14A7 7 0 0012 5z" />
              </svg>
            ) : (
              <svg className="w-4.5 h-4.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
              </svg>
            )}
          </button>

          <a
            href="https://app.paid2marketing.com/"
            target="_blank"
            rel="noopener noreferrer"
            className="px-4 py-2.5 rounded-xl text-sm font-semibold transition-all duration-200"
            style={{ color: "var(--fg1)", border: "1px solid var(--border)" }}
          >
            Log In
          </a>
          <a
            href="https://app.paid2marketing.com/register"
            target="_blank"
            rel="noopener noreferrer"
            className="px-5 py-2.5 rounded-xl bg-[#28c76f] hover:bg-[#22b965] text-white text-sm font-semibold transition-all duration-200 shadow-lg shadow-[#28c76f]/20"
          >
            Get Started
          </a>
        </div>

        {/* Mobile menu button */}
        <button onClick={() => setMenuOpen(!menuOpen)} className="md:hidden p-2 rounded-lg transition-all" style={{ color: "var(--fg2)" }} aria-label="Toggle menu">
          {menuOpen ? (
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
          ) : (
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" /></svg>
          )}
        </button>
      </nav>

      {/* Mobile Menu */}
      {menuOpen && (
        <div className="md:hidden px-4 py-4 max-h-[85vh] overflow-y-auto" style={{ background: "var(--bg2)", borderTop: "1px solid var(--border)" }}>
          {/* Mobile theme + currency row */}
          <div className="flex items-center gap-2 mb-4">
            <button onClick={toggle} className="flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium flex-1 justify-center" style={{ background: "var(--card-bg)", border: "1px solid var(--border)", color: "var(--fg2)" }}>
              {isDark ? "☀️ Light Mode" : "🌙 Dark Mode"}
            </button>
            {CURRENCIES.map((c) => (
              <button key={c.value} onClick={() => setCurrency(c.value)}
                className="px-3 py-2 rounded-lg text-xs font-bold transition-all"
                style={{ background: currency === c.value ? "#28c76f" : "var(--card-bg)", color: currency === c.value ? "#fff" : "var(--fg2)", border: "1px solid var(--border)" }}>
                {c.label}
              </button>
            ))}
          </div>

          <ul className="flex flex-col gap-1">
            {[{ href: "/", label: "Home" }, { href: "/about", label: "About" }].map((l) => (
              <li key={l.href}>
                <Link href={l.href} onClick={() => setMenuOpen(false)} className="block px-4 py-3 rounded-lg text-sm font-medium transition-all" style={{ color: "var(--fg2)" }}>{l.label}</Link>
              </li>
            ))}

            <li>
              <button onClick={() => setMobileServicesOpen(!mobileServicesOpen)} className="w-full flex items-center justify-between px-4 py-3 rounded-lg text-sm font-medium transition-all" style={{ color: "var(--fg2)" }}>
                Services
                <svg className={`w-4 h-4 transition-transform ${mobileServicesOpen ? "rotate-180" : ""}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M19 9l-7 7-7-7" />
                </svg>
              </button>
              {mobileServicesOpen && (
                <div className="ml-4 pl-4 space-y-1" style={{ borderLeft: "1px solid var(--border)" }}>
                  <Link href="/services" onClick={() => { setMenuOpen(false); setMobileServicesOpen(false); }} className="block py-2 text-xs font-semibold text-[#28c76f]">→ View All Services</Link>
                  {megaServices.map((s) => {
                    const Icon = serviceIconMap[s.slug];
                    return (
                    <Link key={s.title} href={s.href} onClick={() => { setMenuOpen(false); setMobileServicesOpen(false); }} className="flex items-center gap-3 py-2.5 px-2 rounded-lg transition-all" style={{ color: "var(--fg2)" }}>
                      <span className="w-7 h-7 flex-shrink-0">{Icon && <Icon size={28} />}</span>
                      <div>
                        <p className="text-xs font-medium" style={{ color: "var(--fg1)" }}>{s.title}</p>
                        <p className="text-[#28c76f] text-xs">From {meta.symbol}{meta.label === "LKR" ? Math.round(s.basePrice * 325).toLocaleString() : (s.basePrice * (meta.label === "EUR" ? 0.92 : 1)).toFixed(2)}/mo</p>
                      </div>
                    </Link>
                    );
                  })}
                </div>
              )}
            </li>

            {[{ href: "/pricing", label: "Pricing" }, { href: "/contact", label: "Contact" }].map((l) => (
              <li key={l.href}>
                <Link href={l.href} onClick={() => setMenuOpen(false)} className="block px-4 py-3 rounded-lg text-sm font-medium" style={{ color: "var(--fg2)" }}>{l.label}</Link>
              </li>
            ))}
            <li className="pt-2 flex flex-col gap-2">
              <a
                href="https://app.paid2marketing.com/"
                target="_blank"
                rel="noopener noreferrer"
                onClick={() => setMenuOpen(false)}
                className="block px-4 py-3 rounded-xl text-sm font-semibold text-center transition-all"
                style={{ border: "1px solid var(--border)", color: "var(--fg1)" }}
              >
                Log In
              </a>
              <a
                href="https://app.paid2marketing.com/register"
                target="_blank"
                rel="noopener noreferrer"
                onClick={() => setMenuOpen(false)}
                className="block px-4 py-3 rounded-xl bg-[#28c76f] hover:bg-[#22b965] text-white text-sm font-semibold text-center transition-all"
              >
                Get Started
              </a>
            </li>
          </ul>
        </div>
      )}
    </header>
  );
}
