import React, { useState, useEffect, useRef } from "react";
import styled from "styled-components";
import { useTranslation } from "react-i18next";
import { Link, animateScroll as scroll } from "react-scroll";
import { FiSun, FiMoon, FiGlobe } from "react-icons/fi";
import { MdOutlineDarkMode, MdOutlineLightMode } from "react-icons/md";

const StyledWrapper = styled.div`
  .theme-toggle-btn {
    background: transparent;
    border: none;
    color: ${props => props.theme === 'dark' ? '#FFD700' : '#FF8C00'};
    cursor: pointer;
    padding: 0.5rem;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    font-size: 1.5rem;
    
    &:hover {
      background: ${props => props.theme === 'dark' ? 'rgba(255, 215, 0, 0.1)' : 'rgba(255, 140, 0, 0.1)'};
      transform: scale(1.1);
    }
    
    &:active {
      transform: scale(0.95);
    }
  }
`;

const ThemeToggle = ({ currentTheme, toggleTheme }) => {
  const isDark = currentTheme === "dark";

  return (
    <StyledWrapper theme={currentTheme}>
      <button
        onClick={toggleTheme}
        className="theme-toggle-btn"
        aria-label={isDark ? "Switch to light mode" : "Switch to dark mode"}
      >
        {isDark ? <FiSun size={24} /> : <FiMoon size={24} />}
      </button>
    </StyledWrapper>
  );
};

const LanguageSwitcher = ({ i18n }) => {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const current = i18n.language?.startsWith("ar") ? "ar" : "en";

  useEffect(() => {
    const onDocClick = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener("click", onDocClick);
    return () => document.removeEventListener("click", onDocClick);
  }, []);

  const changeLng = (lng) => {
    if (lng !== "ar" && lng !== "en") return;
    i18n.changeLanguage(lng);
    setOpen(false);
  };

  return (
    <div ref={ref} style={{ position: "relative", display: "inline-flex", alignItems: "center" }}>
      <button
        type="button"
        aria-haspopup="true"
        aria-expanded={open}
        onClick={() => setOpen((s) => !s)}
        style={{
          padding: "0.5rem",
          borderRadius: "50%",
          border: "none",
          background: "transparent",
          color: "inherit",
          cursor: "pointer",
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          transition: "all 0.3s ease",
          fontSize: "1.5rem",
        }}
        className="lang-toggle-btn"
      >
        <FiGlobe size={24} />
      </button>

      {open && (
        <div
          role="menu"
          aria-label="Language menu"
          style={{
            position: "absolute",
            top: "calc(100% + 8px)",
            right: 0,
            background: "linear-gradient(180deg,#111827,#0b1220)",
            borderRadius: 8,
            boxShadow: "0 8px 30px rgba(2,6,23,0.5)",
            padding: "6px",
            zIndex: 60,
            minWidth: 96,
          }}
        >
          <button
            onClick={() => changeLng("en")}
            role="menuitem"
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              width: "100%",
              textAlign: "left",
              padding: "8px 10px",
              borderRadius: 6,
              background: current === "en" ? "rgba(255,183,77,0.12)" : "transparent",
              color: "inherit",
              border: "none",
              cursor: "pointer",
              transition: "all 0.2s ease",
            }}
            className={`lang-item ${current === "en" ? "active" : ""}`}
          >
            <span>English</span>
            {current === "en" && <span style={{ fontSize: "0.9rem" }}>✓</span>}
          </button>
          <button
            onClick={() => changeLng("ar")}
            role="menuitem"
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              width: "100%",
              textAlign: "left",
              padding: "8px 10px",
              borderRadius: 6,
              background: current === "ar" ? "rgba(255,183,77,0.12)" : "transparent",
              color: "inherit",
              border: "none",
              cursor: "pointer",
              transition: "all 0.2s ease",
              marginTop: 6,
            }}
            className={`lang-item ${current === "ar" ? "active" : ""}`}
          >
            <span>العربية</span>
            {current === "ar" && <span style={{ fontSize: "0.9rem" }}>✓</span>}
          </button>
        </div>
      )}
    </div>
  );
};

const Navbar = ({ toggleTheme, currentTheme }) => {
  const { t, i18n } = useTranslation();
  const [menuOpen, setMenuOpen] = useState(false);
  const [activeSection, setActiveSection] = useState("home");
  const isRtl = i18n.language?.startsWith("ar");

  useEffect(() => {
    const handleScroll = () => {
      const sections = ["home", "services", "about", "contact"];
      const scrollPosition = window.scrollY + 140;

      for (const section of sections) {
        const element = document.getElementById(section) || document.querySelector(`[name="${section}"]`);
        if (element) {
          const offsetTop = element.offsetTop;
          const offsetHeight = element.offsetHeight;
          if (scrollPosition >= offsetTop && scrollPosition < offsetTop + offsetHeight) {
            setActiveSection(section);
            break;
          }
        }
      }
    };

    handleScroll();
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  useEffect(() => {
    if (i18n.language === "ar") {
      document.documentElement.dir = "rtl";
      document.documentElement.lang = "ar";
    } else {
      document.documentElement.dir = "ltr";
      document.documentElement.lang = i18n.language;
    }
  }, [i18n.language]);

  const navItems = [
    { key: "home", label: t("nav.home") || "Home" },
    { key: "services", label: t("nav.services") || "Services" },
    { key: "about", label: t("nav.about") || "About" },
    { key: "contact", label: t("nav.contact") || "Contact" },
  ];

  return (
    <>
      <style>{`
        html, body, a, button {
          -webkit-tap-highlight-color: transparent;
          -webkit-touch-callout: none;
        }

        .nav-link, .nav-link *, .mobile-drawer a, .mobile-drawer a * {
          text-decoration: none !important;
          background-image: none !important;
          -webkit-text-decoration-skip: none !important;
          text-decoration-skip-ink: none !important;
        }

        .nav-link::after, .nav-link:after {
          display: none !important;
          content: none !important;
        }

        .glass-nav {
          background: linear-gradient(180deg, rgba(75,85,99,0.96), rgba(55,65,81,0.9));
          color: #e6e6e6;
          border-bottom: 1px solid rgba(255,255,255,0.05);
          backdrop-filter: blur(8px);
          -webkit-backdrop-filter: blur(8px);
        }

        .nav-link {
          position: relative;
          padding-bottom: 6px;
          transition: transform .18s cubic-bezier(.2,.9,.2,1), color .15s ease, text-shadow .15s ease;
          color: rgba(229,231,235,0.95);
          display: inline-block;
        }

        .nav-pill {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          padding: 0.32rem 0.6rem;
          border-radius: 999px;
          transition:
            transform .18s cubic-bezier(.2,.9,.2,1),
            background .14s ease,
            box-shadow .14s ease,
            color .12s ease;
          background: transparent;
          color: inherit;
          line-height: 1;
          font-weight: 600;
          will-change: transform, box-shadow;
        }

        .nav-link:hover .nav-pill {
          transform: translateY(-6px) scale(1.06);
          box-shadow:
            0 14px 40px rgba(2,6,23,0.28),
            0 6px 20px rgba(255,122,24,0.08);
          background: linear-gradient(90deg, #ffd27a, #ff8a00);
          color: #050505;
        }

        .nav-link.active .nav-pill,
        .mobile-drawer .nav-pill.active {
          background: radial-gradient(circle at 30% 30%, #ffb347, #ff7a18) !important;
          color: #0b0b0b !important;
          transform: translateY(-3px) scale(1.03);
          box-shadow: 0 8px 26px rgba(255, 122, 24, 0.16), 0 2px 6px rgba(0,0,0,0.12);
        }

        .nav-link:active .nav-pill,
        .mobile-drawer a:active .nav-pill {
          transition-duration: 0s !important;
          transform: translateY(-3px) scale(1.03) !important;
          background: radial-gradient(circle at 30% 30%, #ffb347, #ff7a18) !important;
          color: #0b0b0b !important;
          box-shadow: 0 8px 26px rgba(255, 122, 24, 0.16) !important;
        }

        .nav-link:focus-visible .nav-pill,
        .mobile-drawer a:focus-visible .nav-pill {
          outline: none;
          box-shadow: 0 0 0 6px rgba(255,165,0,0.14), 0 8px 30px rgba(255,122,24,0.12);
          background: radial-gradient(circle at 30% 30%, #ffb347, #ff7a18);
          color: #0b0b0b;
          transform: translateY(-3px) scale(1.02);
        }

        .glass-nav button:focus-visible,
        .mobile-drawer button:focus-visible {
          outline: none;
          box-shadow: 0 0 0 6px rgba(255,165,0,0.12);
        }

        .nav-link:hover, .nav-link:visited, .mobile-drawer a:hover, .mobile-drawer a:visited {
          text-decoration: none !important;
          background: transparent !important;
        }

        @media (prefers-reduced-motion: reduce) {
          .nav-pill, .nav-link {
            transition: none !important;
          }
        }

        .mobile-left-slot { display:flex; align-items:center; gap:0.5rem; }
        .mobile-right-slot { display:flex; align-items:center; gap:0.5rem; }

        .lang-toggle-btn {
          background: transparent;
          border: none;
          color: inherit;
          cursor: pointer;
          padding: 0.5rem;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: all 0.3s ease;
          font-size: 1.5rem;
        }
        
        .lang-toggle-btn:hover {
          background: rgba(255, 255, 255, 0.1);
          transform: scale(1.1);
        }
        
        .theme-toggle-btn:hover {
          background: rgba(255, 255, 255, 0.1);
          transform: scale(1.1);
        }
      `}</style>

      <nav
        className="fixed top-0 left-0 right-0 z-50 w-full glass-nav px-4 md:px-8 lg:px-16 py-3"
        aria-label="Main navigation"
        role="navigation"
      >
        <div className="mx-auto max-w-screen-xl">
          <div className="flex items-center justify-between h-14 px-2 md:px-4">
            <div className="flex items-center gap-3">
              <div aria-hidden className="logo-placeholder" style={{ width: 36, height: 36 }} />
              <div className="hidden md:flex items-center space-x-6 rtl:space-x-reverse ml-6">
                <ul className="flex items-center gap-6">
                  {navItems.map((item) => {
                    const isActive = activeSection === item.key;
                    return (
                      <li key={item.key}>
                        <Link
                          to={item.key}
                          smooth
                          duration={600}
                          spy={true}
                          offset={-110}
                          onSetActive={() => setActiveSection(item.key)}
                          onClick={() => {
                            setActiveSection(item.key);
                            if (item.key === "home") scroll.scrollToTop({ duration: 600 });
                            if (menuOpen) setMenuOpen(false);
                          }}
                          className={`nav-link cursor-pointer text-sm md:text-lg ${isActive ? "active" : "text-slate-200 dark:text-slate-200/90"}`}
                          aria-current={isActive ? "page" : undefined}
                        >
                          <span className={`nav-pill ${isActive ? "active" : ""}`}>{item.label}</span>
                        </Link>
                      </li>
                    );
                  })}
                </ul>
              </div>
            </div>

            <div className="flex items-center gap-3 md:gap-5">
              <div className="hidden md:flex items-center gap-3">
                <LanguageSwitcher i18n={i18n} />
                <ThemeToggle currentTheme={currentTheme} toggleTheme={toggleTheme} />
              </div>

              <div className="md:hidden w-full">
                {!isRtl ? (
                  <div style={{ display: "flex", alignItems: "center", width: "100%" }}>
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <button
                        onClick={() => setMenuOpen((s) => !s)}
                        aria-controls="mobile-menu"
                        aria-expanded={menuOpen}
                        className="p-2 rounded-md focus:outline-none transition-transform hover:scale-105"
                        style={{ marginRight: 8 }}
                      >
                        <span className="sr-only">Open main menu</span>
                        <svg className="h-6 w-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
                          {menuOpen ? <path d="M6 18L18 6M6 6l12 12" /> : <><path d="M3 6h18" /><path d="M3 12h18" /><path d="M3 18h18" /></>}
                        </svg>
                      </button>
                    </div>

                    <div style={{ flex: 1 }} />

                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <ThemeToggle currentTheme={currentTheme} toggleTheme={toggleTheme} />
                      <LanguageSwitcher i18n={i18n} />
                    </div>
                  </div>
                ) : (
                  <div style={{ display: "flex", alignItems: "center", width: "100%" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <ThemeToggle currentTheme={currentTheme} toggleTheme={toggleTheme} />
                      <LanguageSwitcher i18n={i18n} />
                    </div>

                    <div style={{ flex: 1 }} />

                    <div>
                      <button
                        onClick={() => setMenuOpen((s) => !s)}
                        aria-controls="mobile-menu"
                        aria-expanded={menuOpen}
                        className="p-2 rounded-md focus:outline-none transition-transform hover:scale-105"
                        style={{ marginLeft: 8 }}
                      >
                        <span className="sr-only">Open main menu</span>
                        <svg className="h-6 w-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
                          {menuOpen ? <path d="M6 18L18 6M6 6l12 12" /> : <><path d="M3 6h18" /><path d="M3 12h18" /><path d="M3 18h18" /></>}
                        </svg>
                      </button>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>

          <div
            id="mobile-menu"
            className={`md:hidden overflow-hidden transition-[max-height,opacity] duration-300 ease-in-out ${menuOpen ? "max-h-[420px] opacity-100" : "max-h-0 opacity-0"}`}
          >
            <div className="mobile-drawer px-4 pb-6 pt-3 rounded-b-2xl">
              <ul className="flex flex-col gap-2">
                {navItems.map((item) => {
                  const isActive = activeSection === item.key;
                  return (
                    <li key={item.key}>
                      <Link
                        to={item.key}
                        smooth
                        duration={600}
                        spy={true}
                        offset={-110}
                        onSetActive={() => setActiveSection(item.key)}
                        onClick={() => {
                          setActiveSection(item.key); 
                          if (item.key === "home") scroll.scrollToTop({ duration: 600 });
                          setMenuOpen(false);
                        }}
                        className={`block w-full text-right px-3 py-2 rounded-md font-semibold text-base ${isActive ? "text-amber-400" : "text-slate-200 hover:text-amber-400"}`}
                        aria-current={isActive ? "page" : undefined}
                      >
                        <span className={`nav-pill ${isActive ? "active" : ""}`}>{item.label}</span>
                      </Link>
                    </li>
                  );
                })}
              </ul>
            </div>
          </div>
        </div>
      </nav>
    </>
  );
};

export default Navbar;