"use client";

import { useEffect, useState, type ReactNode } from "react";
import { usePathname } from "next/navigation";
import { Menu } from "lucide-react";

import { LogoMark } from "@/components/ui/LogoMark";
import { cn } from "@/lib/utils";

/**
 * Dashboard layout shell with a responsive sidebar: a normal static column on
 * desktop (lg+), and an off-canvas drawer with a hamburger top bar on mobile.
 *
 * The closed-state transform is applied only via `max-lg:` so there is no `lg:`
 * transform to conflict with — this sidesteps the RTL/`lg:` specificity trap
 * (see AdminShell) and works for both fa (RTL) and en (LTR).
 */
export function DashboardSidebarDrawer({
  sidebar,
  children,
}: {
  sidebar: ReactNode;
  children: ReactNode;
}) {
  const [open, setOpen] = useState(false);
  const pathname = usePathname();

  // Close the drawer after navigating (the dashboard layout persists across routes).
  useEffect(() => setOpen(false), [pathname]);

  return (
    <div className="flex min-h-screen bg-neutral-50">
      <div
        className={cn(
          "shrink-0 transition-transform max-lg:fixed max-lg:inset-y-0 max-lg:start-0 max-lg:z-50",
          open ? "max-lg:translate-x-0" : "max-lg:-translate-x-full max-lg:rtl:translate-x-full",
        )}
      >
        {sidebar}
      </div>

      {open && (
        <div
          className="fixed inset-0 z-40 bg-black/40 lg:hidden"
          onClick={() => setOpen(false)}
          aria-hidden
        />
      )}

      <div className="flex min-h-screen min-w-0 flex-1 flex-col">
        {/* Mobile top bar with hamburger */}
        <div className="sticky top-0 z-30 flex h-14 items-center gap-3 border-b border-gray-100 bg-white/95 px-4 backdrop-blur lg:hidden">
          <button
            type="button"
            onClick={() => setOpen(true)}
            aria-label="menu"
            className="rounded-lg border border-gray-200 p-1.5 text-neutral-600 hover:bg-neutral-100"
          >
            <Menu className="h-5 w-5" aria-hidden />
          </button>
          <LogoMark size={28} />
          <span className="font-heading text-base font-bold text-neutral-900">FlatRender</span>
        </div>

        {children}
      </div>
    </div>
  );
}
