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 { FcGlobe } from "react-icons/fc";

/* ----------------- Icons (unchanged) ----------------- */
const SunIcon = ({ className }) => (
  <svg viewBox="0 0 24 24" className={className} fill="none" aria-hidden>
    <path d="M12 4v2" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    <path d="M12 18v2" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    <path d="M4.22 4.22l1.42 1.42" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    <path d="M18.36 18.36l1.42 1.42" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    <path d="M1 12h2" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    <path d="M21 12h2" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    <circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="1.6" />
  </svg>
);
const MoonIcon = ({ className }) => (
  <svg viewBox="0 0 24 24" className={className} fill="none" aria-hidden>
    <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);

/* ----------------- ThemeToggle styles (RESTORED EXACTLY AS ORIGINAL) ----------------- */
/* kept exactly the same as your original ThemeToggle styles so its look didn't change */
const StyledWrapper = styled.div`
  /* Base Styles */
  .switch {
    display: inline-block;
    width: 5.2em;
    height: 2.6em;
    position: relative;
    font-size: 16px;
    user-select: none;
    margin: 0;
    transform-origin: center;
  }

  /* Hide default HTML checkbox */
  .switch input {
    opacity: 0;
    width: 0;
    height: 0;
    position: absolute;
  }

  /* Slider */
  .slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(to right, #87ceeb, #e0f6ff);
    border-radius: 50px;
    transition: all 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    box-shadow:
      0 4px 8px rgba(0, 0, 0, 0.1),
      inset 0 -5px 10px rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }

  /* Inner slider for additional styling */
  .slider-inner {
    position: absolute;
    top: 0.28em;
    left: 0.28em;
    height: 2.1em;
    width: 2.1em;
    border-radius: 50%;
    background-color: #ffd700;
    transition: all 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    box-shadow:
      0 2px 4px rgba(0, 0, 0, 0.2),
      inset 0 -2px 5px rgba(0, 0, 0, 0.2);
  }

  /* Checked state */
  .switch input:checked + .slider {
    background: linear-gradient(to right, #1a237e, #3949ab);
  }

  .switch input:checked + .slider .slider-inner {
    transform: translateX(2.6em);
    background-color: #ffffff;
  }

  /* Focus state */
  .switch input:focus + .slider {
    outline: none;
    box-shadow: 0 0 0.4em rgba(25, 118, 210, 0.5);
  }

  /* Hover and active states */
  .switch:hover .slider {
    background: linear-gradient(to right, #64b5f6, #e3f2fd);
  }

  .switch input:checked:hover + .slider {
    background: linear-gradient(to right, #283593, #5c6bc0);
  }

  /* Animation for slider inner */
  @keyframes sunPulse {
    0%,
    100% {
      box-shadow:
        0 0 0 0 rgba(255, 215, 0, 0.7),
        0 0 0 0 rgba(255, 215, 0, 0.4);
    }
    50% {
      box-shadow:
        0 0 20px 10px rgba(255, 215, 0, 0.7),
        0 0 40px 20px rgba(255, 215, 0, 0.4);
    }
  }

  @keyframes moonPhase {
    0%,
    100% {
      box-shadow:
        inset -10px -5px 0 0 #ddd,
        0 0 20px rgba(255, 255, 255, 0.5);
    }
    50% {
      box-shadow:
        inset 0 0 0 0 #ddd,
        0 0 20px rgba(255, 255, 255, 0.5);
    }
  }

  .switch input:not(:checked) + .slider .slider-inner {
    animation: sunPulse 3s infinite;
  }

  .switch input:checked + .slider .slider-inner {
    animation: moonPhase 5s infinite;
  }

  /* Stars effect */
  @keyframes twinkle {
    0%,
    100% {
      opacity: 0.2;
    }
    50% {
      opacity: 1;
    }
  }

  .slider::before,
  .slider::after {
    content: "";
    position: absolute;
    width: 4px;
    height: 4px;
    background-color: #ffffff;
    border-radius: 50%;
    transition: all 0.6s ease;
    opacity: 0;
  }

  .slider::before {
    top: 20%;
    left: 30%;
  }

  .slider::after {
    bottom: 25%;
    right: 25%;
  }

  .switch input:checked + .slider::before,
  .switch input:checked + .slider::after {
    opacity: 1;
    animation: twinkle 2s infinite;
  }

  .switch input:checked + .slider::before {
    animation-delay: 0.5s;
  }

  /* 3D effect */
  .slider {
    transform-style: preserve-3d;
    perspective: 500px;
  }

  .slider-inner {
    transform: translateZ(5px);
  }

  .switch input:checked + .slider .slider-inner {
    transform: translateX(2.6em) translateZ(5px) rotateY(180deg);
  }

  /* Cloud effect for day mode */
  .slider-inner::before,
  .slider-inner::after {
    content: "";
    position: absolute;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 50%;
    transition: all 0.6s ease;
  }

  .slider-inner::before {
    width: 1em;
    height: 1em;
    top: -0.5em;
    left: -0.2em;
  }

  .slider-inner::after {
    width: 1.2em;
    height: 1.2em;
    bottom: -0.6em;
    right: -0.3em;
  }

  .switch input:checked + .slider .slider-inner::before,
  .switch input:checked + .slider .slider-inner::after {
    opacity: 0;
  }

  /* Crater effect for night mode */
  .switch input:checked + .slider .slider-inner::before {
    width: 0.6em;
    height: 0.6em;
    background-color: rgba(0, 0, 0, 0.2);
    top: 0.3em;
    left: 0.3em;
    opacity: 1;
  }

  .switch input:checked + .slider .slider-inner::after {
    width: 0.4em;
    height: 0.4em;
    background-color: rgba(0, 0, 0, 0.15);
    bottom: 0.5em;
    right: 0.5em;
    opacity: 1;
  }

  /* Accessibility improvements */
  .switch input:focus + .slider {
    outline: 2px solid #4a90e2;
    outline-offset: 2px;
  }

  /* Responsive adjustments */
  @media (max-width: 768px) {
    .switch {
      width: 4.6em;
      height: 2.3em;
    }

    .slider-inner {
      height: 1.85em;
      width: 1.85em;
      top: 0.23em;
      left: 0.23em;
    }

    .switch input:checked + .slider .slider-inner {
      transform: translateX(2.2em) translateZ(5px) rotateY(180deg);
    }
  }

  @media (max-width: 480px) {
    .switch {
      width: 3.8em;
      height: 1.9em;
    }

    .slider-inner {
      height: 1.5em;
      width: 1.5em;
      top: 0.2em;
      left: 0.2em;
    }

    .switch input:checked + .slider .slider-inner {
      transform: translateX(1.8em) translateZ(5px) rotateY(180deg);
    }
  }

  /* High contrast mode */
  @media (forced-colors: active) {
    .slider {
      background: Canvas;
      border: 2px solid ButtonText;
    }

    .switch input:checked + .slider {
      background: Highlight;
    }

    .slider-inner {
      background-color: ButtonFace;
    }

    .switch::before,
    .switch::after {
      color: ButtonText;
    }
  }

  /* Reduced motion preference */
  @media (prefers-reduced-motion: reduce) {
    .switch,
    .slider,
    .slider-inner {
      transition: none;
    }

    .switch input:checked + .slider .slider-inner,
    .switch input:not(:checked) + .slider .slider-inner,
    .switch input:checked + .slider::before,
    .switch input:checked + .slider::after {
      animation: none;
    }
  }
`;

/* ----------------- ThemeToggle component (exactly as original) ----------------- */
const ThemeToggle = ({ currentTheme, toggleTheme }) => {
  const isDark = currentTheme === "dark";

  return (
    <StyledWrapper>
      <label
        role="switch"
        aria-checked={isDark}
        tabIndex={0}
        className="switch"
        onKeyDown={(e) => {
          if (e.key === "Enter" || e.key === " ") {
            e.preventDefault();
            toggleTheme();
          }
        }}
      >
        <input
          type="checkbox"
          checked={isDark}
          onChange={toggleTheme}
          aria-hidden="false"
        />
        <span className="slider" aria-hidden="true">
          <span className="slider-inner" />
        </span>
      </label>
    </StyledWrapper>
  );
};

/* ----------------- Internal LanguageSwitcher (restricted to EN/AR only) ----------------- */
const InternalLanguageSwitcher = ({ className, 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} className={className} style={{ position: "relative", display: "inline-flex", alignItems: "center" }}>
      <button
        type="button"
        aria-haspopup="true"
        aria-expanded={open}
        onClick={() => setOpen((s) => !s)}
        className="lang-switch-btn"
        style={{
          padding: "0.28rem 0.5rem",
          borderRadius: "0.5rem",
          border: "none",
          background: "transparent",
          color: "inherit",
          fontWeight: 700,
          cursor: "pointer",
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <FcGlobe size={28} />
      </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"
            className={`lang-item ${current === "en" ? "active" : ""}`}
            style={{
              display: "block",
              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",
            }}
          >
            English
          </button>
          <button
            onClick={() => changeLng("ar")}
            role="menuitem"
            className={`lang-item ${current === "ar" ? "active" : ""}`}
            style={{
              display: "block",
              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",
              marginTop: 6,
            }}
          >
            العربية
          </button>
        </div>
      )}
    </div>
  );
};

/* ----------------- Navbar component ----------------- */
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-switch-btn {
          background: transparent;
          border: none;
          color: inherit;
          font-weight: 700;
          cursor: pointer;
          padding: 0.25rem 0.45rem;
          border-radius: 0.4rem;
        }
      `}</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">
                <InternalLanguageSwitcher 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} />
                      <InternalLanguageSwitcher 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} />
                      <InternalLanguageSwitcher 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;
