// components/layout/Sidebar.jsx
"use client";

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

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faHouse,
  faFileLines,
  faUsers,
  faGear,
  faRightFromBracket,
  faBars,
  faXmark,
  faChevronDown,
} from "@fortawesome/free-solid-svg-icons";

export default function Sidebar() {
  const pathname = usePathname();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const settingsRef = useRef(null);

  const nav = useMemo(
    () => [
      { href: "/", label: "Anasayfa", icon: faHouse },
      { href: "/Policy", label: "Poliçeler", icon: faFileLines },
      { href: "/Users", label: "Kullanıcılar", icon: faUsers },
    ],
    []
  );

  useEffect(() => {
    const onDown = (e) => {
      if (!settingsRef.current) return;
      if (!settingsRef.current.contains(e.target)) setSettingsOpen(false);
    };
    document.addEventListener("mousedown", onDown);
    return () => document.removeEventListener("mousedown", onDown);
  }, []);

  useEffect(() => {
    setMobileOpen(false);
    setSettingsOpen(false);
  }, [pathname]);

const isActive = (href) => {
  if (!pathname) return false;

  // ✅ Home should only be active on exactly "/"
  if (href === "/") return pathname === "/";

  // ✅ Other routes: active if exact match or child route
  return pathname === href || pathname.startsWith(href + "/");
};

  return (
    <>
      {/* Mobile top bar */}
      <div className="lg:hidden sticky top-0 z-40 bg-white/80 backdrop-blur border-b border-black/10">
        <div className="h-14 px-4 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <button
              onClick={() => setMobileOpen(true)}
              className="h-10 w-10 rounded-xl border border-black/10 bg-white hover:bg-black/[0.02] transition"
              aria-label="Open menu"
            >
              <FontAwesomeIcon icon={faBars} />
            </button>

            {/* Logo (text for now) */}
            <div className="text-lg font-extrabold tracking-tight select-none">
              <span className="text-[#e04a3b]">Polim</span>
              <span className="text-[#98a2b3]">X</span>
            </div>
          </div>

          <div className="text-xs px-2 py-1 rounded-full bg-black/5 text-black/60 border border-black/5">
            Sigorta Paneli
          </div>
        </div>
      </div>

      {/* Desktop sidebar */}
      <aside className="hidden lg:flex lg:fixed lg:inset-y-0 lg:left-0 lg:w-[280px]">
        <SidebarInner
          nav={nav}
          pathname={pathname}
          isActive={isActive}
          settingsOpen={settingsOpen}
          setSettingsOpen={setSettingsOpen}
          settingsRef={settingsRef}
        />
      </aside>

      {/* Mobile drawer */}
      {mobileOpen && (
        <div className="lg:hidden fixed inset-0 z-50">
          <div
            className="absolute inset-0 bg-black/40"
            onClick={() => setMobileOpen(false)}
          />
          <div className="absolute inset-y-0 left-0 w-[86%] max-w-[320px]">
            <div className="h-full bg-white shadow-[0_30px_90px_rgba(0,0,0,0.25)]">
              <div className="h-14 px-4 flex items-center justify-between border-b border-black/10">
                <div className="text-lg font-extrabold tracking-tight select-none">
                  <span className="text-[#e04a3b]">Polim</span>
                  <span className="text-[#98a2b3]">X</span>
                </div>
                <button
                  onClick={() => setMobileOpen(false)}
                  className="h-10 w-10 rounded-xl border border-black/10 bg-white hover:bg-black/[0.02] transition"
                  aria-label="Close menu"
                >
                  <FontAwesomeIcon icon={faXmark} />
                </button>
              </div>

              <SidebarInner
                nav={nav}
                pathname={pathname}
                isActive={isActive}
                settingsOpen={settingsOpen}
                setSettingsOpen={setSettingsOpen}
                settingsRef={settingsRef}
              />
            </div>
          </div>
        </div>
      )}

      {/* Spacer for layout when using fixed desktop sidebar */}
      <div className="hidden lg:block lg:w-[280px]" />
    </>
  );
}

function SidebarInner({
  nav,
  isActive,
  settingsOpen,
  setSettingsOpen,
  settingsRef,
}) {
  const onLogout = () => {
    console.log("logout clicked");
    // later: signOut() from next-auth
  };

  return (
    <div className="w-full h-full flex flex-col border-r border-black/10 bg-white">
      {/* Top */}
      <div className="px-5 py-5">
        <div className="flex items-center justify-between">
          <div className="text-2xl font-extrabold tracking-tight select-none">
            <span className="text-[#e04a3b]">Polim</span>
            <span className="text-[#98a2b3]">X</span>
          </div>
          <span className="text-[11px] px-2 py-1 rounded-full bg-black/5 text-black/60 border border-black/5">
            Sigorta
          </span>
        </div>

        
      </div>

      {/* Nav */}
      <nav className="px-3 pb-3">
        <div className="space-y-1">
          {nav.map((item) => {
            const active = isActive(item.href);
            return (
              <Link
                key={item.href}
                href={item.href}
                className={[
                  "group flex items-center gap-3 rounded-2xl px-4 py-3 text-sm font-semibold transition",
                  active
                    ? "bg-[#e04a3b]/10 text-[#e04a3b]"
                    : "text-black/70 hover:bg-black/[0.03] hover:text-black/85",
                ].join(" ")}
              >
                <span
                  className={[
                    "grid place-items-center h-9 w-9 rounded-xl border transition",
                    active
                      ? "border-[#e04a3b]/20 bg-white text-[#e04a3b]"
                      : "border-black/10 bg-white text-black/55 group-hover:text-black/75",
                  ].join(" ")}
                >
                  <FontAwesomeIcon icon={item.icon} />
                </span>
                <span className="flex-1">{item.label}</span>
                {active && (
                  <span className="h-2 w-2 rounded-full bg-[#e04a3b]" />
                )}
              </Link>
            );
          })}
        </div>
      </nav>

      {/* Bottom (Settings with dropdown) */}
      <div className="mt-auto px-3 pb-4">
        <div
          ref={settingsRef}
          className="relative rounded-2xl border border-black/10 bg-white"
        >
          <button
            onClick={() => setSettingsOpen((v) => !v)}
            className="w-full flex items-center gap-3 px-4 py-3 rounded-2xl text-sm font-semibold text-black/70 hover:bg-black/[0.03] transition"
          >
            <span className="grid place-items-center h-9 w-9 rounded-xl border border-black/10 bg-white text-black/55">
              <FontAwesomeIcon icon={faGear} />
            </span>
            <span className="flex-1 text-left">Ayarlar</span>
            <span
              className={[
                "text-black/45 transition-transform",
                settingsOpen ? "rotate-180" : "",
              ].join(" ")}
            >
              <FontAwesomeIcon icon={faChevronDown} />
            </span>
          </button>

          {settingsOpen && (
            <div className="absolute left-3 right-3 bottom-[56px] rounded-2xl border border-black/10 bg-white shadow-[0_18px_60px_rgba(0,0,0,0.14)] overflow-hidden">
              <button
                onClick={onLogout}
                className="w-full flex items-center gap-3 px-4 py-3 text-sm font-semibold text-black/70 hover:bg-black/[0.03] transition"
              >
                <span className="grid place-items-center h-9 w-9 rounded-xl border border-black/10 bg-white text-black/55">
                  <FontAwesomeIcon icon={faRightFromBracket} />
                </span>
                Çıkış Yap
              </button>
            </div>
          )}
        </div>

        <div className="mt-3 text-[11px] text-black/45 px-1">
          © {new Date().getFullYear()} PolimX
        </div>
      </div>
    </div>
  );
}