"use client";

import { useEffect } from "react";
import { useAuthStore } from "@/store/auth-store";
import { useMenuStore } from "@/store/menu-store";
import { LogOut, User, BookOpen, Menu as MenuIcon, Shield, Users } from "lucide-react";

export function Header() {
  const { user, logout } = useAuthStore();
  const { topMenus, activeTopMenu, fetchTopMenus, fetchSideMenus, setMobileOpen, viewMode, setViewMode } = useMenuStore();
  const isAdminUser = !!user && (user.isAdmin || user.role === "ADMIN" || user.userType === "A");

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

  // 관리자도 기본은 사용자 모드. 토글로 관리자 메뉴 진입.

  // 초기 로드: "사용자" 메뉴의 사이드바를 불러오기 (관리자 제외)
  useEffect(() => {
    if (topMenus.length > 0 && !activeTopMenu) {
      const userMenu = topMenus.find((m) => m.MENU_NAME_KOR !== "관리자");
      if (userMenu) {
        fetchSideMenus(userMenu.OBJID);
      }
    }
  }, [topMenus, activeTopMenu, fetchSideMenus]);

  return (
    <header className="h-12 bg-white border-b border-gray-200 flex items-center px-3 sm:px-4 shrink-0 gap-2">
      {/* 모바일 햄버거 — lg 이상에서는 숨김 */}
      <button
        onClick={() => setMobileOpen(true)}
        className="lg:hidden p-1.5 -ml-1 text-gray-600 hover:text-emerald-700 rounded"
        aria-label="메뉴 열기"
      >
        <MenuIcon size={20} />
      </button>

      {/* 좌측 여백 */}
      <div className="flex-1" />

      {/* 매뉴얼 보기 (새 탭) */}
      <a
        href="/manual.html"
        target="_blank"
        rel="noreferrer"
        className="inline-flex items-center gap-1 text-xs sm:text-sm text-gray-600 hover:text-emerald-700 hover:underline px-2"
        title="사용 설명서"
      >
        <BookOpen size={14} className="text-gray-400" />
        <span className="hidden sm:inline">매뉴얼</span>
      </a>

      {/* 관리자 모드 토글 (admin 권한자만) */}
      {isAdminUser && (
        <button
          onClick={() => setViewMode(viewMode === "admin" ? "user" : "admin")}
          className={`inline-flex items-center gap-1 h-8 px-2.5 rounded-md text-xs font-bold transition ${
            viewMode === "admin"
              ? "bg-orange-100 text-orange-700 hover:bg-orange-200"
              : "bg-blue-100 text-blue-700 hover:bg-blue-200"
          }`}
          title={viewMode === "admin" ? "사용자 메뉴로 전환" : "관리자 메뉴로 전환"}
        >
          {viewMode === "admin" ? <Shield size={13} /> : <Users size={13} />}
          <span className="hidden sm:inline">{viewMode === "admin" ? "관리자" : "사용자"}</span>
        </button>
      )}

      {/* 우측: 사용자명(프로필 링크) + 로그아웃 */}
      <a
        href="/profile"
        className="flex items-center gap-1.5 text-xs sm:text-sm text-gray-600 hover:text-emerald-700 hover:underline pl-2 border-l border-gray-200 min-w-0"
        title="회원정보 수정"
      >
        <User size={14} className="text-gray-400 shrink-0" />
        <span className="truncate max-w-[110px] sm:max-w-[200px]">
          {user?.userName}
          <span className="hidden sm:inline">{user?.deptName ? ` (${user.deptName})` : ""}</span>
        </span>
      </a>

      <button
        onClick={logout}
        className="p-2 text-gray-500 hover:text-red-500 rounded transition-colors"
        title="로그아웃"
      >
        <LogOut size={16} />
      </button>
    </header>
  );
}
