"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuthStore } from "@/store/auth-store";
import { useMenuStore } from "@/store/menu-store";
import { Sidebar } from "@/components/layout/sidebar";
import { Header } from "@/components/layout/header";
import { Loading } from "@/components/ui/loading";

export default function MainLayout({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const { user, isLoading, fetchUser } = useAuthStore();
  const { mobileOpen, setMobileOpen } = useMenuStore();

  useEffect(() => { fetchUser(); }, [fetchUser]);

  useEffect(() => {
    if (!isLoading && !user) router.push("/login");
  }, [isLoading, user, router]);

  if (isLoading) return <Loading message="로딩 중..." />;
  if (!user) return null;

  return (
    <div className="flex h-screen overflow-hidden">
      {/* 사이드바 — 데스크탑은 정상, 모바일은 오버레이로 등장 */}
      <div
        className={
          "fixed inset-y-0 left-0 z-50 shadow-2xl transition-transform duration-200 " +
          "lg:static lg:shadow-none lg:translate-x-0 " +
          (mobileOpen ? "translate-x-0" : "-translate-x-full lg:translate-x-0")
        }
      >
        <Sidebar />
      </div>

      {/* 모바일 오버레이 배경 — 사이드바 펼쳤을 때 어둡게 */}
      {mobileOpen && (
        <button
          aria-label="사이드바 닫기"
          onClick={() => setMobileOpen(false)}
          className="fixed inset-0 bg-slate-900/40 z-40 lg:hidden"
        />
      )}

      {/* 메인 영역 */}
      <div className="flex-1 flex flex-col overflow-hidden">
        <Header />
        <main className="flex-1 overflow-auto p-3 sm:p-4 flex flex-col min-h-0">
          {children}
        </main>
      </div>
    </div>
  );
}
