import React, { useEffect, useRef, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useAuth } from "../context/AuthContext";

type NavItemProps = {
  label: string;
  onClick: () => void;
  disabled?: boolean;
  active?: boolean;
};

function NavItem({ label, onClick, disabled, active }: NavItemProps) {
  return (
    <button
      type="button"
      className={[
        "bf-nav-item",
        active ? "is-active" : "",
        disabled ? "is-disabled" : "",
      ].join(" ")}
      onClick={onClick}
      disabled={disabled}
    >
      {label}
    </button>
  );
}

export function AppShell({ children }: { children: React.ReactNode }) {
  const nav = useNavigate();
  const location = useLocation();
  const { user, logout } = useAuth();

  const [shouldFadeIn, setShouldFadeIn] = useState(false);
  const prevPathRef = useRef(location.pathname);

  const isCases = location.pathname === "/cases" || location.pathname.startsWith("/cases/");
  const isEditShell = location.pathname.startsWith("/editor");
  const isAdmin = location.pathname.startsWith("/admin");
  const isLanding = location.pathname === "/landing";
  const userIsAdmin = user?.role === "admin";

  useEffect(() => {
    const prevPath = prevPathRef.current;
    prevPathRef.current = location.pathname;

    if (prevPath === "/landing" && location.pathname !== "/landing") {
      setShouldFadeIn(true);
      const t = window.setTimeout(() => setShouldFadeIn(false), 560);
      return () => window.clearTimeout(t);
    }
  }, [location.pathname]);

  const handleLogout = () => {
    logout();
    nav("/");
  };

  return (
    <div className="bf-shell">
      {!isLanding && (
        <header className="bf-header">
          <div className="bf-left">
            <div 
              className="bf-brand" 
              onClick={() => nav("/")} 
              onKeyDown={(e) => e.key === "Enter" && nav("/")}
              role="button" 
              tabIndex={0}
            >
              Brace<span className="bf-brand-accent">iQ</span>
            </div>

            <nav className="bf-nav" aria-label="Primary navigation">
              <NavItem label="Cases" active={isCases} onClick={() => nav("/cases")} />
              <NavItem label="Editor" active={isEditShell} onClick={() => nav("/editor")} />
              {userIsAdmin && (
                <NavItem label="Admin" active={isAdmin} onClick={() => nav("/admin")} />
              )}
            </nav>
          </div>

          <div className="bf-right">
            {user && (
              <div className="bf-user-menu">
                <span className="bf-user-name">{user.fullName || user.username}</span>
                <button className="bf-logout-btn" onClick={handleLogout}>
                  Sign Out
                </button>
              </div>
            )}
          </div>
        </header>
      )}

      <main
        className={[
          "bf-content",
          isLanding ? "bf-content--landing" : "",
          !isLanding && shouldFadeIn ? "bf-content--fade-in" : "",
        ]
          .filter(Boolean)
          .join(" ")}
      >
        {children}
      </main>
    </div>
  );
}
