import { useQuery } from "@tanstack/react-query"; import { Building2, ChevronDown, Key, KeyRound, LayoutDashboard, LogOut, Moon, Network, NotebookTabs, ShieldHalf, Sun, User as UserIcon, Users, } from "lucide-react"; import * as React from "react"; import { useEffect, useRef, useState } from "react"; import { useAuth } from "react-oidc-context"; import { NavLink, Outlet, useLocation, useNavigate } from "react-router-dom"; import { fetchMe } from "../../lib/adminApi"; import { t } from "../../lib/i18n"; import { shouldAttemptSlidingSessionRenew, shouldAttemptUnlimitedSessionRenew, } from "../../lib/sessionSliding"; import { buildAuthenticatedOrgChartUrl } from "../../features/users/orgChartPicker"; import LanguageSelector from "../common/LanguageSelector"; import RoleSwitcher from "./RoleSwitcher"; interface NavItem { label: string; to: string; icon: React.ComponentType<{ size?: number | string }>; isExternal?: boolean; } const staticNavItems: NavItem[] = [ { label: "ui.admin.nav.overview", to: "/", icon: LayoutDashboard }, { label: "ui.admin.nav.users", to: "/users", icon: Users }, { label: "ui.admin.nav.api_keys", to: "/api-keys", icon: Key }, { label: "ui.admin.nav.audit_logs", to: "/audit-logs", icon: NotebookTabs }, { label: "ui.admin.nav.auth_guard", to: "/auth", icon: KeyRound }, ]; function AppLayout() { const auth = useAuth(); const location = useLocation(); const navigate = useNavigate(); const profileMenuRef = useRef(null); const isRenewInFlightRef = useRef(false); const lastRenewAttemptAtRef = useRef(0); const lastVisitedRouteRef = useRef(null); const isDevRoleOverrideEnabled = import.meta.env.MODE === "development" || (window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean }) ._IS_TEST_MODE === true; const isMockRoleEnabled = isDevRoleOverrideEnabled && window.localStorage.getItem("X-Mock-Role-Enabled") === "true"; const mockRoleOverride = isMockRoleEnabled ? window.localStorage.getItem("X-Mock-Role") : null; const [theme, setTheme] = useState<"light" | "dark">(() => { const stored = window.localStorage.getItem("admin_theme"); return stored === "dark" ? "dark" : "light"; }); const [isProfileOpen, setIsProfileOpen] = useState(false); const [isSessionExpiryEnabled, setIsSessionExpiryEnabled] = useState(() => { const stored = window.localStorage.getItem("baron_session_expiry_enabled"); return stored !== "false"; }); const [nowMs, setNowMs] = useState(() => Date.now()); useEffect(() => { const timer = window.setInterval(() => { setNowMs(Date.now()); }, 1000); return () => { window.clearInterval(timer); }; }, []); const { data: profile, isLoading: isProfileLoading, error: profileError, } = useQuery({ queryKey: ["me"], queryFn: async () => { console.debug("[AppLayout] Fetching profile..."); try { const data = await fetchMe(); console.debug("[AppLayout] Profile fetched successfully:", data.email); return data; } catch (err) { console.error("[AppLayout] Failed to fetch profile:", err); throw err; } }, enabled: (auth.isAuthenticated && !auth.isLoading) || import.meta.env.MODE === "development" || (window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean }) ._IS_TEST_MODE === true, }); const navItems = React.useMemo(() => { const items = [...staticNavItems]; const isTest = (window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean }) ._IS_TEST_MODE === true; const effectiveRole = mockRoleOverride || profile?.role; const isSuperAdmin = isTest || effectiveRole === "super_admin"; const isTenantAdmin = effectiveRole === "tenant_admin"; const manageableCount = profile?.manageableTenants?.length ?? 0; const orgfrontUrl = buildAuthenticatedOrgChartUrl( import.meta.env.ORGFRONT_URL || "http://localhost:5175", ); const filteredItems = items.filter((item) => { if (isTest) return true; if (item.to === "/api-keys") return isSuperAdmin; return true; }); if (isSuperAdmin) { filteredItems.splice(1, 0, { label: "ui.admin.nav.tenants", to: "/tenants", icon: Building2, }); filteredItems.splice(2, 0, { label: "ui.admin.nav.org_chart", to: orgfrontUrl, icon: Network, isExternal: true, }); } else if (isTenantAdmin || manageableCount > 0) { if (manageableCount <= 1 && profile?.tenantId) { filteredItems.splice(1, 0, { label: "ui.admin.nav.my_tenant", to: `/tenants/${profile.tenantId}`, icon: Building2, }); } else if (manageableCount > 1) { filteredItems.splice(1, 0, { label: "ui.admin.nav.tenants", to: "/tenants", icon: Building2, }); } filteredItems.splice( manageableCount <= 1 && profile?.tenantId ? 2 : 2, 0, { label: "ui.admin.nav.org_chart", to: orgfrontUrl, icon: Network, isExternal: true, }, ); } else { // 일반 사용자(Tenant Member)도 조직도 메뉴를 볼 수 있도록 추가합니다. filteredItems.splice(1, 0, { label: "ui.admin.nav.org_chart", to: orgfrontUrl, icon: Network, isExternal: true, }); } return filteredItems; }, [mockRoleOverride, profile]); const handleLogout = () => { if ( window.confirm(t("msg.admin.logout_confirm", "로그아웃 하시겠습니까?")) ) { window.localStorage.removeItem("admin_session"); auth.removeUser(); navigate("/login"); } }; useEffect(() => { const isTest = (window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean }) ._IS_TEST_MODE === true; console.debug("[AppLayout] Auth state check:", { isLoading: auth.isLoading, isAuthenticated: auth.isAuthenticated, isTest, }); if (!auth.isLoading && !auth.isAuthenticated && !isTest) { console.warn("[AppLayout] Not authenticated, redirecting to /login"); navigate("/login"); } }, [auth.isLoading, auth.isAuthenticated, navigate]); useEffect(() => { if (auth.user?.access_token) { window.localStorage.setItem("admin_session", auth.user.access_token); } }, [auth.user]); useEffect(() => { const root = document.documentElement; root.classList.remove("light", "dark"); if (theme === "light") { root.classList.add("light"); } else { root.classList.add("dark"); } window.localStorage.setItem("admin_theme", theme); }, [theme]); useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if ( profileMenuRef.current && !profileMenuRef.current.contains(event.target as Node) ) { setIsProfileOpen(false); } }; document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, []); useEffect(() => { const maybeRenewSession = async () => { const now = Date.now(); if ( !shouldAttemptSlidingSessionRenew({ expiresAtSec: auth.user?.expires_at, nowMs: now, isEnabled: isSessionExpiryEnabled, isAuthenticated: auth.isAuthenticated, isLoading: auth.isLoading, isRenewInFlight: isRenewInFlightRef.current, lastAttemptAtMs: lastRenewAttemptAtRef.current, }) ) { return; } isRenewInFlightRef.current = true; lastRenewAttemptAtRef.current = now; try { await auth.signinSilent(); } catch (error) { console.error("세션 자동 연장에 실패했습니다.", error); } finally { isRenewInFlightRef.current = false; } }; const handleUserAction = () => { void maybeRenewSession(); }; window.addEventListener("pointerdown", handleUserAction); window.addEventListener("keydown", handleUserAction); return () => { window.removeEventListener("pointerdown", handleUserAction); window.removeEventListener("keydown", handleUserAction); }; }, [ auth, auth.isAuthenticated, auth.isLoading, auth.user?.expires_at, isSessionExpiryEnabled, ]); useEffect(() => { const maybeKeepSessionAlive = async () => { const now = Date.now(); if ( !shouldAttemptUnlimitedSessionRenew({ expiresAtSec: auth.user?.expires_at, nowMs: now, isEnabled: isSessionExpiryEnabled, isAuthenticated: auth.isAuthenticated, isLoading: auth.isLoading, isRenewInFlight: isRenewInFlightRef.current, lastAttemptAtMs: lastRenewAttemptAtRef.current, }) ) { return; } isRenewInFlightRef.current = true; lastRenewAttemptAtRef.current = now; try { await auth.signinSilent(); } catch (error) { console.error("세션 무제한 유지 갱신에 실패했습니다.", error); } finally { isRenewInFlightRef.current = false; } }; const timer = window.setInterval(() => { void maybeKeepSessionAlive(); }, 30_000); void maybeKeepSessionAlive(); return () => { window.clearInterval(timer); }; }, [ auth, auth.isAuthenticated, auth.isLoading, auth.user?.expires_at, isSessionExpiryEnabled, ]); useEffect(() => { const routeKey = `${location.pathname}${location.search}${location.hash}`; if (lastVisitedRouteRef.current === null) { lastVisitedRouteRef.current = routeKey; return; } if (lastVisitedRouteRef.current === routeKey) { return; } lastVisitedRouteRef.current = routeKey; const now = Date.now(); if ( !shouldAttemptSlidingSessionRenew({ expiresAtSec: auth.user?.expires_at, nowMs: now, isEnabled: isSessionExpiryEnabled, isAuthenticated: auth.isAuthenticated, isLoading: auth.isLoading, isRenewInFlight: isRenewInFlightRef.current, lastAttemptAtMs: lastRenewAttemptAtRef.current, }) ) { return; } isRenewInFlightRef.current = true; lastRenewAttemptAtRef.current = now; void auth .signinSilent() .catch((error) => { console.error("세션 자동 연장에 실패했습니다.", error); }) .finally(() => { isRenewInFlightRef.current = false; }); }, [ auth, auth.isAuthenticated, auth.isLoading, auth.user?.expires_at, isSessionExpiryEnabled, location.hash, location.pathname, location.search, ]); const toggleTheme = () => { setTheme((prev) => (prev === "light" ? "dark" : "light")); }; const profileName = profile?.name?.trim() || auth.user?.profile.name?.toString().trim() || auth.user?.profile.preferred_username?.toString().trim() || t("ui.dev.profile.unknown_name", "Unknown User"); const profileEmail = profile?.email?.trim() || auth.user?.profile.email?.toString().trim() || t("ui.dev.profile.unknown_email", "unknown@example.com"); const profileInitial = profileName.charAt(0).toUpperCase(); const profileRoleKey = mockRoleOverride || profile?.role || "user"; const expiresAtSec = auth.user?.expires_at; const remainingMs = typeof expiresAtSec === "number" ? expiresAtSec * 1000 - nowMs : null; const remainingTotalSec = remainingMs !== null ? Math.max(0, Math.floor(remainingMs / 1000)) : null; const remainingMinutes = remainingTotalSec !== null ? Math.floor(remainingTotalSec / 60) : null; const remainingSeconds = remainingTotalSec !== null ? remainingTotalSec % 60 : null; let sessionToneClass = "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"; let sessionText = t("ui.dev.session.active", "세션 활성"); if (remainingMs === null) { sessionToneClass = "border-border bg-card text-muted-foreground"; sessionText = t("ui.dev.session.unknown", "알 수 없음"); } else if (remainingMs <= 0) { sessionToneClass = "border-rose-500/30 bg-rose-500/10 text-rose-700 dark:text-rose-300"; sessionText = t("ui.dev.session.expired", "세션 만료"); } else if ( remainingMinutes !== null && remainingSeconds !== null && remainingMinutes <= 5 ) { sessionToneClass = "border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300"; sessionText = t( "ui.dev.session.expiring", "만료 임박: {{minutes}}분 {{seconds}}초 남음", { minutes: remainingMinutes, seconds: remainingSeconds, }, ); } else { sessionText = t( "ui.dev.session.remaining", "만료 예정: {{minutes}}분 {{seconds}}초 남음", { minutes: remainingMinutes ?? 0, seconds: remainingSeconds ?? 0, }, ); } const handleSessionExpiryToggle = () => { setIsSessionExpiryEnabled((prev) => { const next = !prev; window.localStorage.setItem("baron_session_expiry_enabled", String(next)); return next; }); }; if (auth.isLoading) { return (
); } return (

{t("ui.admin.header.plane", "ADMIN PLANE")}

{t("ui.admin.header.subtitle", "Manage your organization")}
{isSessionExpiryEnabled ? ( {sessionText} ) : null}
{isProfileOpen ? (

{t("ui.dev.profile.menu_title", "Account")}

{profileName}

{profileEmail}

{t( `ui.admin.role.${profileRoleKey}`, profileRoleKey.toUpperCase(), )}

{t("ui.dev.session.auto_extend", "세션 만료 관리")}

{isSessionExpiryEnabled ? sessionText : t( "ui.dev.session.disabled", "세션 만료 비활성화", )}

{profile?.manageableTenants && profile.manageableTenants.length > 0 ? (

{t( "ui.admin.profile.manageable_tenants", "Manageable Tenants", )}

{profile.manageableTenants.map((tenant) => ( ))}
) : null}
) : null}
); } export default AppLayout;