"use client";

import { useEffect, useId } from "react";
import type { AccountType } from "@/types/auth";
import { DashboardSidebar } from "./DashboardSidebar";

export function DashboardMobileNav({
  open,
  accountType,
  onLogout,
  isLoggingOut,
  onClose,
}: {
  open: boolean;
  accountType: AccountType;
  onLogout: () => void;
  isLoggingOut: boolean;
  onClose: () => void;
}) {
  const drawerTitleId = useId();

  useEffect(() => {
    document.body.classList.toggle("overflow-hidden", open);
    return () => document.body.classList.remove("overflow-hidden");
  }, [open]);

  useEffect(() => {
    if (!open) {
      return;
    }

    function onKey(event: KeyboardEvent) {
      if (event.key === "Escape") {
        onClose();
      }
    }

    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) {
    return null;
  }

  return (
    <div className="fixed inset-0 z-50 lg:hidden">
      <button
        type="button"
        className="absolute inset-0 bg-primary/35"
        aria-label="Close navigation"
        onClick={onClose}
      />
      <aside
        id="dashboard-mobile-nav"
        className="absolute inset-y-0 left-0 flex w-[min(18.5rem,88vw)] flex-col border-r border-line bg-surface shadow-[8px_0_32px_-18px_rgba(23,37,84,0.45)]"
        role="dialog"
        aria-modal="true"
        aria-labelledby={drawerTitleId}
      >
        <p id={drawerTitleId} className="sr-only">
          Dashboard navigation
        </p>
        <DashboardSidebar
          accountType={accountType}
          onLogout={onLogout}
          isLoggingOut={isLoggingOut}
          onNavigate={onClose}
          onClose={onClose}
        />
      </aside>
    </div>
  );
}
