import { useQuery } from "@tanstack/react-query"; import { BadgeCheck, ChevronDown, LogOut, Moon, NotebookTabs, ShieldHalf, Sun, User as UserIcon, } from "lucide-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 "../../features/auth/authApi"; import { t } from "../../lib/i18n"; import { resolveProfileRole } from "../../lib/role"; import { shouldAttemptSlidingSessionRenew, shouldAttemptUnlimitedSessionRenew, } from "../../lib/sessionSliding"; import LanguageSelector from "../common/LanguageSelector"; import { Toaster } from "../ui/toaster"; const navItems = [ { labelKey: "ui.dev.nav.clients", labelFallback: "Clients", to: "/clients", icon: ShieldHalf, }, { labelKey: "ui.dev.nav.audit_logs", labelFallback: "Audit Logs", to: "/audit-logs", icon: NotebookTabs, }, ]; 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 [theme, setTheme] = useState<"light" | "dark">(() => { const stored = window.localStorage.getItem("admin_theme"); return stored === "dark" ? "dark" : "light"; }); const [isProfileMenuOpen, setIsProfileMenuOpen] = useState(false); const [isSessionExpiryEnabled, setIsSessionExpiryEnabled] = useState(() => { const stored = window.localStorage.getItem("baron_session_expiry_enabled"); return stored !== "false"; }); const [nowMs, setNowMs] = useState(() => Date.now()); const hasAccessToken = Boolean(auth.user?.access_token); const { data: profile } = useQuery({ queryKey: ["userMe"], queryFn: fetchMe, enabled: hasAccessToken, }); const handleLogout = () => { if (window.confirm(t("msg.dev.logout_confirm", "로그아웃 하시겠습니까?"))) { auth.removeUser(); navigate("/login"); } }; 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 timer = window.setInterval(() => { setNowMs(Date.now()); }, 1000); return () => { window.clearInterval(timer); }; }, []); useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if ( profileMenuRef.current && !profileMenuRef.current.contains(event.target as Node) ) { setIsProfileMenuOpen(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() || auth.user?.profile?.nickname?.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 currentRole = resolveProfileRole( auth.user?.profile as Record | undefined, ); const displayRoleKey = profile?.role || currentRole; 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; }); }; return (

{t("ui.dev.header.plane", "Dev Plane")}

{t("ui.dev.header.subtitle", "Manage your applications")}
{isSessionExpiryEnabled ? ( {sessionText} ) : null}
{isProfileMenuOpen ? (

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

{profileName}

{profileEmail}

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

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

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

) : null}
); } export default AppLayout;