/**
 * @copyright nhcarrigan
 * @license Naomi's Public License
 * @author Naomi Carrigan
 */
"use client";
import {
  faBars,
  faTimes,
  faSun,
  faMoon,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Image from "next/image";
import { usePathname } from "next/navigation";
import React, { type JSX, useState, useEffect, useCallback } from "react";
import { NavItems } from "../config/NavItems";
import { Rule } from "./rule";

/**
 * Conditionally renders the navigation component when
 * not on the home page.
 * @returns A JSX element.
 */
export const Navigation = (): JSX.Element | null => {
  const [ isOpen, setIsOpen ] = useState(false);
  const [ isDarkMode, setIsDarkMode ] = useState(false);

  useEffect(() => {
    const storedTheme = localStorage.getItem("theme");
    if (storedTheme === "dark") {
      document.documentElement.classList.add("dark");
      setIsDarkMode(true);
    } else {
      document.documentElement.classList.remove("dark");
      setIsDarkMode(false);
    }
  }, []);

  const toggleMenu = useCallback((): void => {
    setIsOpen(!isOpen);
  }, [ isOpen ]);

  const toggleDarkMode = useCallback((): void => {
    document.documentElement.classList.toggle("dark", !isDarkMode);
    localStorage.setItem("theme", isDarkMode
      ? "light"
      : "dark");
    setIsDarkMode(!isDarkMode);
  }, [ isDarkMode ]);

  const pathname = usePathname();
  const isRootPath = pathname === "/";

  if (isRootPath) {
    return null;
  }

  return (
    <div className="fixed w-full top-0 z-50">
      <nav
        className="w-full flex justify-between
        items-center h-14 px-4 bg-[--background] text-[--foreground]"
      >
        <a href="/">
          <Image
            alt="nhcarrigan's logo"
            height={50}
            src="https://cdn.nhcarrigan.com/logo.png"
            width={50}
          />
        </a>
        <div className="flex items-center">
          <button className="mr-4" onClick={toggleDarkMode} type="button">
            <FontAwesomeIcon icon={isDarkMode
              ? faSun
              : faMoon} size="lg" />
          </button>
          <button onClick={toggleMenu} type="button">
            <FontAwesomeIcon icon={isOpen
              ? faTimes
              : faBars} size="2x" />
          </button>
        </div>
      </nav>
      {isOpen
        ? <div className="bg-[--background] text-[--foreground]">
          {NavItems.map((item, index) => {
            return (
              <a
                className="block py-2 px-4 text-2xl hover:bg-[--foreground]
                hover:text-[--background]"
                href={item.href}
                key={item.href}
                onClick={toggleMenu}
              >
                {index % 2 === 1
                  ? "🩷"
                  : "🩵"} {item.text}
              </a>
            );
          })}
        </div>
        : null}
      <Rule />
    </div>
  );
};
