"use client";

import { useEffect, useState } from "react";
import { createPortal } from "react-dom";

const links = [
  { href: "#services", label: "Services" },
  { href: "#approach", label: "Approach" },
  { href: "#projects", label: "Projects" },
  { href: "#name", label: "The name" },
  { href: "#contact", label: "Contact" },
];

export function MobileNav() {
  const [isOpen, setIsOpen] = useState(false);
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  return (
    <>
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        aria-label={isOpen ? "Close menu" : "Open menu"}
        aria-expanded={isOpen}
        className="border-border bg-surface/50 text-text-secondary hover:text-text relative flex h-9 w-9 items-center justify-center border backdrop-blur-md transition md:hidden"
      >
        <MenuIcon className={`h-4 w-4 transition-opacity ${isOpen ? "opacity-0" : "opacity-100"}`} />
        <XIcon
          className={`absolute inset-0 m-auto h-4 w-4 transition-opacity ${isOpen ? "opacity-100" : "opacity-0"}`}
        />
      </button>

      {isMounted &&
        createPortal(
          <div
            className={`bg-bg/60 fixed inset-0 z-40 backdrop-blur-md transition-opacity duration-200 md:hidden ${isOpen ? "opacity-100" : "pointer-events-none opacity-0"}`}
            onClick={() => setIsOpen(false)}
            aria-hidden="true"
          />,
          document.body,
        )}

      <div
        className={`border-border bg-bg/95 absolute inset-x-0 top-full border-b backdrop-blur-md transition-all duration-300 md:hidden ${
          isOpen ? "max-h-[calc(100vh-4rem)] opacity-100" : "max-h-0 opacity-0"
        } overflow-hidden`}
      >
        <nav className="flex flex-col gap-1 px-4 py-4">
          {links.map((link) => (
            <a
              key={link.href}
              href={link.href}
              onClick={() => setIsOpen(false)}
              className="text-text-secondary hover:text-text hover:bg-surface/60 rounded px-3 py-2.5 text-sm font-medium transition"
            >
              {link.label}
            </a>
          ))}
        </nav>
      </div>
    </>
  );
}

function MenuIcon({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      className={className}
      aria-hidden="true"
    >
      <path d="M4 6h16M4 12h16M4 18h16" />
    </svg>
  );
}

function XIcon({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      className={className}
      aria-hidden="true"
    >
      <path d="M6 6l12 12M18 6L6 18" />
    </svg>
  );
}
