﻿import { useState, useRef, useEffect } from "react";
/* eslint-disable react-hooks/set-state-in-effect */
import { dashboardHref, Link, useLocation } from "@/lib/nextRouterAdapter";
import { useAuth } from "@/lib/AuthContext";
import { dashboardApi } from "@/api/dashboardClient";
import NotificationBell from "./NotificationBell";
import ProfileAvatar from "./ProfileAvatar";

// Cambridge Veritas — Speech Analyser palette
const BURGUNDY  = "#4A1429";
const GOLD      = "#D4B038";
const WARM_TEXT = "#2B0B14";
const MUTED_WARM = "#6B5D52";
const BORDER_WARM = "#E5DDD5";

const navLinks = [
  { label: "Dashboard", to: "/dashboard" },
  { label: "Courses", to: "/courses" },
  { label: "Templates", to: "/templates" },
  { label: "Community", to: "/community" },
];

const profileLinks = [
  { label: "Learning Journal", to: "/journal" },
  { label: "My Progress", to: "/progress" },
  { label: "Leaderboard", to: "/leaderboard" },
  { label: "Certificates", to: "/certificates" },
  { label: "Settings", to: "/settings" },
];

function isNavigationActive(pathname, destination) {
  const target = dashboardHref(destination);
  if (destination === "/dashboard") return pathname === target;
  if (destination === "/courses") {
    return pathname === target
      || pathname.startsWith("/dashboard/course/")
      || pathname.startsWith("/dashboard/lesson/");
  }
  return pathname === target || pathname.startsWith(`${target}/`);
}

export default function AppNav({ initialProgress = null }) {
  const { user, logout } = useAuth();
  const location = useLocation();
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [userProgress, setUserProgress] = useState(initialProgress);
  const dropdownRef = useRef(null);

  useEffect(() => {
    const handler = (e) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
        setDropdownOpen(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  useEffect(() => { setDrawerOpen(false); }, [location.pathname]);

  useEffect(() => {
    if (!drawerOpen) return undefined;
    const root = document.documentElement;
    const previousOverflow = document.body.style.overflow;
    const previousRootOverflow = root.style.overflow;
    const previousOverscroll = document.body.style.overscrollBehavior;
    document.body.style.overflow = "hidden";
    root.style.overflow = "hidden";
    document.body.style.overscrollBehavior = "none";
    return () => {
      document.body.style.overflow = previousOverflow;
      root.style.overflow = previousRootOverflow;
      document.body.style.overscrollBehavior = previousOverscroll;
    };
  }, [drawerOpen]);

  useEffect(() => {
    if (!drawerOpen) return undefined;
    const closeOnEscape = (event) => {
      if (event.key === "Escape") setDrawerOpen(false);
    };
    window.addEventListener("keydown", closeOnEscape);
    return () => window.removeEventListener("keydown", closeOnEscape);
  }, [drawerOpen]);

  useEffect(() => {
    if (!user?.id) {
      setUserProgress(null);
      return;
    }
    if (initialProgress && String(initialProgress.user_id) === String(user.id)) {
      setUserProgress(initialProgress);
      return;
    }
    dashboardApi.entities.UserProgress.filter({ user_id: user.id }).then((data) => {
      setUserProgress(data[0] || null);
    }).catch(() => {});
  }, [initialProgress, user?.id]);

  const profilePhoto = user?.profile_photo || user?.avatar || "";

  const totalXP = userProgress?.total_xp || 0;
  const streak = userProgress?.current_streak_days || 0;

  return (
    <>
      <nav
        data-dashboard-top-nav
        className="fixed inset-x-0 top-0 z-[100] w-full min-w-0 border-b bg-white shadow-sm"
        style={{ borderColor: "#EAE3DC" }}
      >
        <div className="flex h-16 w-full min-w-0 items-center justify-between gap-3 px-4 md:px-6">

          {/* Left — Logo */}
          <Link to="/dashboard" className="flex min-w-0 flex-shrink-0 items-center gap-2.5">
            <div
              className="w-8 h-8 rounded-lg flex items-center justify-center font-black text-xs flex-shrink-0"
              style={{ backgroundColor: BURGUNDY, color: GOLD }}
            >CV</div>
            <div className="flex flex-col leading-tight hidden sm:flex">
              <span className="font-black tracking-tight text-sm" style={{ color: BURGUNDY }}>Cambridge Veritas</span>
              <span className="text-[10px] tracking-widest font-bold uppercase" style={{ color: GOLD }}>
                Self-Paced Learning
              </span>
            </div>
            <span className="font-black tracking-tight text-sm sm:hidden" style={{ color: BURGUNDY }}>CV Self-Paced</span>
          </Link>

          {/* Centre — Nav links (desktop only) */}
          <div className="hidden min-w-0 flex-1 items-center justify-center gap-1 lg:flex">
            {navLinks.map((link) => {
              const active = isNavigationActive(location.pathname, link.to);
              return (
                <Link
                  key={link.to}
                  to={link.to}
                  aria-current={active ? "page" : undefined}
                  className="whitespace-nowrap rounded-2xl px-3 py-2 text-sm font-semibold transition-all xl:px-4"
                  style={active
                    ? { backgroundColor: "rgba(61,12,17,0.07)", color: BURGUNDY, border: `1px solid rgba(61,12,17,0.12)` }
                    : { color: "#6B5B4E", border: "1px solid transparent" }
                  }
                >
                  {link.label}
                </Link>
              );
            })}
          </div>

          {/* Right */}
          <div className="flex items-center gap-2 md:gap-3 flex-shrink-0">

            {/* Notification Bell */}
            <div style={{ flexShrink: 0 }}>
              <NotificationBell user={user} />
            </div>

            {/* XP Counter — hidden on mobile */}
            <div
              className="hidden sm:flex items-center gap-1.5 px-3 py-1.5 rounded-2xl border"
              style={{ backgroundColor: "rgba(201,151,58,0.08)", borderColor: "rgba(201,151,58,0.3)", overflow: "hidden", flexShrink: 0 }}
            >
              <span className="text-sm">⚡</span>
              <span className="text-xs font-black whitespace-nowrap" style={{ color: BURGUNDY }}>
                {totalXP.toLocaleString()} XP
              </span>
            </div>

            {/* Streak Counter — hidden on mobile */}
            {streak > 0 && (
              <div
                className="hidden sm:flex items-center gap-1.5 px-3 py-1.5 rounded-2xl border"
                style={{ backgroundColor: "rgba(239,68,68,0.06)", borderColor: "rgba(239,68,68,0.2)", overflow: "hidden", flexShrink: 0 }}
              >
                <span className="text-sm">🔥</span>
                <span className="text-xs font-black whitespace-nowrap" style={{ color: "#DC2626" }}>{streak}</span>
              </div>
            )}

            {/* Avatar + Dropdown (desktop) */}
            <div className="relative hidden lg:block" ref={dropdownRef}>
              <button
                onClick={() => setDropdownOpen(!dropdownOpen)}
                aria-expanded={dropdownOpen}
                aria-haspopup="menu"
                aria-label="Open account menu"
                className="flex items-center gap-2 hover:opacity-80 transition-opacity min-h-[44px] min-w-[44px]"
              >
                <ProfileAvatar
                  key={profilePhoto}
                  src={profilePhoto}
                  name={user?.full_name}
                  className="w-9 h-9 rounded-full flex items-center justify-center font-bold text-xs flex-shrink-0"
                  style={{ backgroundColor: BURGUNDY, color: GOLD, border: `2px solid rgba(201,151,58,0.4)` }}
                />
                <span className="text-xs font-bold" style={{ color: MUTED_WARM }}>▾</span>
              </button>

              {dropdownOpen && (
                <div
                  className="absolute right-0 top-12 w-56 rounded-2xl overflow-hidden shadow-2xl z-50 bg-white border"
                  style={{ borderColor: BORDER_WARM }}
                >
                  <div className="px-4 py-3 border-b" style={{ borderColor: BORDER_WARM }}>
                    <div className="font-black text-sm truncate" style={{ color: BURGUNDY }}>{user?.full_name}</div>
                    <div className="text-xs font-medium truncate" style={{ color: MUTED_WARM }}>{user?.email}</div>
                    <div className="flex items-center gap-3 mt-2">
                      <span className="text-xs font-bold" style={{ color: GOLD }}>⚡ {totalXP.toLocaleString()} XP</span>
                      {streak > 0 && <span className="text-xs font-bold" style={{ color: "#E65100" }}>🔥 {streak}d</span>}
                    </div>
                  </div>
                  {profileLinks.map((link) => (
                    <Link
                      key={link.to}
                      to={link.to}
                      onClick={() => setDropdownOpen(false)}
                      className="flex items-center px-4 py-3 text-sm font-semibold transition-colors hover:bg-amber-50"
                      style={{ color: WARM_TEXT }}
                    >
                      {link.label}
                    </Link>
                  ))}
                  <div className="border-t" style={{ borderColor: BORDER_WARM }}>
                    <button
                      onClick={() => logout('/dashboard/login')}
                      className="w-full text-left flex items-center px-4 py-3 text-sm font-semibold transition-colors hover:bg-red-50"
                      style={{ color: "#dc2626" }}
                    >
                      Sign Out
                    </button>
                  </div>
                </div>
              )}
            </div>

            {/* Hamburger (mobile only) */}
            <button
              onClick={() => setDrawerOpen(true)}
              className="flex h-11 w-11 flex-shrink-0 flex-col items-center justify-center gap-1.5 rounded-lg transition-colors hover:bg-gray-50 lg:hidden"
              style={{ border: `1px solid #EAE3DC` }}
              aria-label="Open menu"
            >
              <span className="block w-5 h-0.5 rounded" style={{ backgroundColor: BURGUNDY }} />
              <span className="block w-5 h-0.5 rounded" style={{ backgroundColor: BURGUNDY }} />
              <span className="block w-5 h-0.5 rounded" style={{ backgroundColor: BURGUNDY }} />
            </button>
          </div>
        </div>
      </nav>

      {/* Mobile Drawer Overlay */}
      {drawerOpen && (
        <div
          className="fixed inset-0 z-[110] bg-black/60 lg:hidden"
          onClick={() => setDrawerOpen(false)}
        />
      )}

      {/* Mobile Slide-in Drawer */}
      <div
        aria-hidden={!drawerOpen}
        className={`fixed bottom-0 right-0 top-0 z-[120] min-h-0 max-h-dvh flex-col overflow-hidden bg-white shadow-2xl lg:hidden ${drawerOpen ? "flex" : "hidden"}`}
        style={{
          width: "min(100%, 22rem)",
          height: "100dvh",
          borderLeft: `1px solid ${BORDER_WARM}`,
          backgroundColor: "#FAF5F0",
        }}
      >
        {/* Drawer Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b bg-white" style={{ borderColor: "#EAE3DC" }}>
          <div className="flex items-center gap-2.5">
            <div className="w-7 h-7 rounded-lg flex items-center justify-center font-black text-xs" style={{ backgroundColor: BURGUNDY, color: GOLD }}>CV</div>
            <span className="font-black text-sm" style={{ color: BURGUNDY }}>Menu</span>
          </div>
          <button
            onClick={() => setDrawerOpen(false)}
            aria-label="Close menu"
            className="w-9 h-9 flex items-center justify-center rounded-lg transition-colors hover:bg-gray-50"
            style={{ color: "#6B5B4E" }}
          >✕</button>
        </div>

        {/* User Info */}
        <div className="px-5 py-4 border-b" style={{ borderColor: BORDER_WARM }}>
          <div className="flex items-center gap-3">
            <ProfileAvatar key={profilePhoto} src={profilePhoto} name={user?.full_name}
              className="w-10 h-10 rounded-full flex items-center justify-center font-bold text-sm flex-shrink-0"
              style={{ backgroundColor: GOLD, color: "#1A0508", border: `2px solid rgba(201,151,58,0.4)` }} />
            <div className="min-w-0">
              <div className="font-black text-sm truncate" style={{ color: BURGUNDY }}>{user?.full_name}</div>
              <div className="text-xs truncate" style={{ color: MUTED_WARM }}>{user?.email}</div>
            </div>
          </div>
          <div className="flex items-center gap-3 mt-3">
            <span className="text-xs font-bold" style={{ color: GOLD }}>⚡ {totalXP.toLocaleString()} XP</span>
            {streak > 0 && <span className="text-xs font-bold" style={{ color: "#E65100" }}>🔥 {streak} day streak</span>}
          </div>
        </div>

        {/* Nav Links */}
        <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain py-3" style={{ WebkitOverflowScrolling: "touch" }}>
          <div className="px-3 mb-2">
            <p className="text-[10px] font-bold uppercase tracking-widest px-2 mb-1" style={{ color: MUTED_WARM }}>Navigation</p>
            {navLinks.map((link) => {
              const active = isNavigationActive(location.pathname, link.to);
              return (
                <Link
                  key={link.to}
                  to={link.to}
                  aria-current={active ? "page" : undefined}
                  className="flex items-center gap-3 px-3 py-3 rounded-xl font-semibold text-sm transition-all min-h-[44px]"
                  style={active
                    ? { backgroundColor: "rgba(201,151,58,0.12)", color: BURGUNDY }
                    : { color: WARM_TEXT }
                  }
                >
                  {link.label}
                </Link>
              );
            })}
          </div>

          <div className="px-3 mt-2">
            <p className="text-[10px] font-bold uppercase tracking-widest px-2 mb-1" style={{ color: MUTED_WARM }}>Account</p>
            {profileLinks.map((link) => (
              <Link
                key={link.to}
                to={link.to}
                className="flex items-center gap-3 px-3 py-3 rounded-xl font-semibold text-sm transition-all min-h-[44px]"
                style={{ color: WARM_TEXT }}
              >
                {link.label}
              </Link>
            ))}
          </div>
        </div>

        {/* Sign Out */}
        <div className="p-4 border-t" style={{ borderColor: BORDER_WARM }}>
          <button
            onClick={() => logout('/dashboard/login')}
            className="w-full text-center py-3 rounded-xl text-sm font-semibold transition-colors min-h-[44px] border"
            style={{ color: "#dc2626", borderColor: "rgba(220,38,38,0.3)" }}
          >
            Sign Out
          </button>
        </div>
      </div>
    </>
  );
}

