summaryrefslogtreecommitdiff
path: root/components/layout/Header.tsx
blob: 2752948a80390b5d0016f9688af87e794b4188cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
"use client";

import * as React from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuLabel,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
    NavigationMenu,
    NavigationMenuContent,
    NavigationMenuItem,
    NavigationMenuLink,
    NavigationMenuList,
    NavigationMenuTrigger,
    navigationMenuTriggerStyle,
} from "@/components/ui/navigation-menu";
import { SearchIcon } from "lucide-react";
import { useParams, usePathname, useSearchParams  } from "next/navigation";
import { cn } from "@/lib/utils";
import Image from "next/image";
import { 
    mainNav, 
    additionalNav, 
    additional2Nav,
    procurementNav,
    salesNav,
    engineeringNav,
    MenuSection, 
    MenuItem,
    mainNavVendor, 
    additionalNavVendor,
    domainBrandingKeys
} from "@/config/menuConfig";
import { MobileMenu } from "./MobileMenu";
import { CommandMenu } from "./command-menu";
import { useSession } from "next-auth/react";
import { customSignOut } from "@/lib/auth/custom-signout";
import GroupedMenuRenderer from "./GroupedMenuRender";
import { useActiveMenus, filterActiveMenus, filterActiveAdditionalMenus } from "@/hooks/use-active-menus";
import { NotificationDropdown } from "./NotificationDropdown";
import { useTranslation } from '@/i18n/client'

// 환경변수에 따라 숨길 메뉴 키 목록 (수정 및 제거가 용이하도록 상수로 분리)
const HIDDEN_MENU_SECTION_KEYS = [
    "menu.vendor.sales.title",
    "menu.vendor.procurement.title",
];

// partners 도메인에서만 숨길 추가 메뉴 키 목록
const HIDDEN_ADDITIONAL_MENU_KEYS_PARTNERS = [
    "menu.additional.system_settings",
];

/**
 * 환경변수에 따라 메뉴 섹션을 필터링하는 함수
 */
const filterMenusByEnvironment = (sections: MenuSection[]): MenuSection[] => {
    const shouldHideMenus = process.env.NEXT_PUBLIC_HIDE_PARTNERS_MENU_BEFORE_OPEN === 'true';
    
    if (!shouldHideMenus) {
        return sections;
    }
    
    return sections.filter(section => !HIDDEN_MENU_SECTION_KEYS.includes(section.titleKey));
};

/**
 * 환경변수에 따라 추가 메뉴 항목을 필터링하는 함수
 * @param items 필터링할 메뉴 항목 배열
 * @param isPartners partners 도메인 여부
 */
const filterAdditionalMenusByEnvironment = (items: MenuItem[], isPartners: boolean): MenuItem[] => {
    const shouldHideMenus = process.env.NEXT_PUBLIC_HIDE_PARTNERS_MENU_BEFORE_OPEN === 'true';
    
    if (!shouldHideMenus) {
        return items;
    }
    
    // partners 도메인일 때만 system_settings 필터링
    if (isPartners) {
        return items.filter(item => !HIDDEN_ADDITIONAL_MENU_KEYS_PARTNERS.includes(item.titleKey));
    }
    
    return items;
};

export function Header() {
    const params = useParams();
    const lng = params?.lng as string;
    const pathname = usePathname();
    const { data: session } = useSession();
    const { activeMenus, isLoading } = useActiveMenus();
    const { t } = useTranslation(lng, 'menu');


    const userName = session?.user?.name || ""; 
    const initials = userName
        .split(" ")
        .map((word) => word[0]?.toUpperCase())
        .join("");

    const [isMobileMenuOpen, setIsMobileMenuOpen] = React.useState(false);
    const [openMenuKey, setOpenMenuKey] = React.useState<string>("");

    const toggleMobileMenu = () => {
        setIsMobileMenuOpen(!isMobileMenuOpen);
    };

    const toggleMenu = React.useCallback((menuKey: string) => {
        setOpenMenuKey(prev => prev === menuKey ? "" : menuKey);
    }, []);

    // 페이지 이동 시 메뉴 닫기
    React.useEffect(() => {
        setOpenMenuKey("");
    }, [pathname]);

    // 도메인별 메뉴 및 브랜딩 정보 가져오기
    // session.user.domain이 있으면 그것을 우선적으로 따르고, 없으면 pathname을 따릅니다.
    const userDomain = (session?.user as { domain?: string } | undefined)?.domain;

    const getDomainConfig = (pathname: string | null, domain?: string) => {
        // 1. 세션 도메인 기반 설정
        if (domain) {
            if (domain === "partners") {
                return {
                    main: mainNavVendor,
                    additional: additionalNavVendor,
                    logoHref: `/${lng}/partners`,
                    brandNameKey: domainBrandingKeys.partners,
                    basePath: `/${lng}/partners`
                };
            }
            if (domain === "procurement") {
                return {
                    main: procurementNav,
                    additional: additional2Nav,
                    logoHref: `/${lng}/procurement`,
                    brandNameKey: domainBrandingKeys.procurement,
                    basePath: `/${lng}/procurement`
                };
            }
            if (domain === "sales") {
                return {
                    main: salesNav,
                    additional: additional2Nav,
                    logoHref: `/${lng}/sales`,
                    brandNameKey: domainBrandingKeys.sales,
                    basePath: `/${lng}/sales`
                };
            }
            if (domain === "engineering") {
                return {
                    main: engineeringNav,
                    additional: additional2Nav,
                    logoHref: `/${lng}/engineering`,
                    brandNameKey: domainBrandingKeys.engineering,
                    basePath: `/${lng}/engineering`
                };
            }
            if (domain === "evcp") {
                return {
                    main: mainNav,
                    additional: additionalNav,
                    logoHref: `/${lng}/evcp`,
                    brandNameKey: domainBrandingKeys.evcp,
                    basePath: `/${lng}/evcp`
                };
            }
        }

        // 2. 경로 기반 설정 (Fallback)
        if (pathname?.includes("/partners")) {
            return {
                main: mainNavVendor,
                additional: additionalNavVendor,
                logoHref: `/${lng}/partners`,
                brandNameKey: domainBrandingKeys.partners,
                basePath: `/${lng}/partners`
            };
        }
        
        if (pathname?.includes("/procurement")) {
            return {
                main: procurementNav,
                additional: additional2Nav,
                logoHref: `/${lng}/procurement`,
                brandNameKey: domainBrandingKeys.procurement,
                basePath: `/${lng}/procurement`
            };
        }
        
        if (pathname?.includes("/sales")) {
            return {
                main: salesNav,
                additional: additional2Nav,
                logoHref: `/${lng}/sales`,
                brandNameKey: domainBrandingKeys.sales,
                basePath: `/${lng}/sales`
            };
        }
        
        if (pathname?.includes("/engineering")) {
            return {
                main: engineeringNav,
                additional: additional2Nav,
                logoHref: `/${lng}/engineering`,
                brandNameKey: domainBrandingKeys.engineering,
                basePath: `/${lng}/engineering`
            };
        }
        
        // 기본값: /evcp (전체 메뉴)
        return {
            main: mainNav,
            additional: additionalNav,
            logoHref: `/${lng}/evcp`,
            brandNameKey: domainBrandingKeys.evcp,
            basePath: `/${lng}/evcp`
        };
    };

    const { main: originalMain, additional: originalAdditional, logoHref, brandNameKey, basePath } = getDomainConfig(pathname, userDomain);

    // partners 도메인 여부 확인
    const isPartners = pathname?.includes("/partners") ?? false;

    // 1단계: 환경변수에 따른 메뉴 필터링
    const envFilteredMain = filterMenusByEnvironment(originalMain);
    const envFilteredAdditional = filterAdditionalMenusByEnvironment(originalAdditional, isPartners);

    // 2단계: 활성 메뉴만 필터링 (로딩 중이거나 에러 시에는 환경변수 필터링만 적용)
    const main = isLoading ? envFilteredMain : filterActiveMenus(envFilteredMain, activeMenus);
    const additional = isLoading ? envFilteredAdditional : filterActiveAdditionalMenus(envFilteredAdditional, activeMenus);


    return (
        <>
            <header className="border-grid sticky top-0 z-40 w-full border-b bg-slate-100 backdrop-blur supports-[backdrop-filter]:bg-background/60">
                <div className="container-wrapper">
                    <div className="container flex h-14 items-center">
                        {/* 햄버거 메뉴 버튼 (모바일) */}
                        <Button
                            onClick={toggleMobileMenu}
                            variant="ghost"
                            className="-ml-2 mr-2 h-8 w-8 px-0 text-base hover:bg-transparent focus-visible:bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0 md:hidden"
                        >
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                fill="none"
                                viewBox="0 0 24 24"
                                strokeWidth="1.5"
                                stroke="currentColor"
                                className="!size-6"
                            >
                                <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    d="M3.75 9h16.5m-16.5 6.75h16.5"
                                />
                            </svg>
                            <span className="sr-only">{t('menu.toggle_menu')}</span>
                        </Button>

                        {/* 로고 영역 - 도메인별 브랜딩 (번역된) */}
                        <div className="mr-4 flex-shrink-0 flex items-center gap-2 lg:mr-6">
                            <Link href={logoHref} className="flex items-center gap-2">
                                <Image
                                    className="dark:invert"
                                    src="/images/vercel.svg"
                                    alt="EVCP Logo"
                                    width={20}
                                    height={20}
                                />
                                <span className="hidden font-bold lg:inline-block">
                                    {t(brandNameKey)}
                                </span>
                            </Link>
                        </div>
                            
                        {/* 네비게이션 메뉴 - 도메인별 활성화된 메뉴만 표시 (번역된) */}
                        <div className="hidden md:block flex-1 min-w-0">
                            <NavigationMenu 
                                className="relative z-50" 
                                value={openMenuKey}
                                onValueChange={setOpenMenuKey}
                            >
                                <div className="w-full overflow-x-auto pb-1">
                                    <NavigationMenuList className="flex-nowrap w-max">
                                        {main.map((section: MenuSection) => (
                                            <NavigationMenuItem key={section.titleKey} value={section.titleKey}>
                                                <NavigationMenuTrigger 
                                                    className="px-2 xl:px-3 text-sm whitespace-nowrap"
                                                    onClick={(e) => {
                                                        e.preventDefault();
                                                        e.stopPropagation();
                                                        toggleMenu(section.titleKey);
                                                    }}
                                                    onPointerEnter={(e) => e.preventDefault()}
                                                    onPointerMove={(e) => e.preventDefault()}
                                                    onPointerLeave={(e) => e.preventDefault()}
                                                >
                                                    {t(section.titleKey)}
                                                </NavigationMenuTrigger>
                                                
                                                {/* 그룹핑이 필요한 메뉴의 경우 GroupedMenuRenderer 사용 */}
                                                {section.useGrouping ? (
                                                    <NavigationMenuContent 
                                                        className="max-h-[80vh] overflow-y-auto"
                                                        onPointerEnter={(e) => e.preventDefault()}
                                                        onPointerLeave={(e) => e.preventDefault()}
                                                        forceMount={openMenuKey === section.titleKey ? true : undefined}
                                                    >
                                                        <GroupedMenuRenderer
                                                            items={section.items}
                                                            lng={lng}
                                                            activeMenus={activeMenus}
                                                            t={t}
                                                            onItemClick={() => setOpenMenuKey("")}
                                                        />
                                                    </NavigationMenuContent>
                                                ) : (
                                                    <NavigationMenuContent 
                                                        className="max-h-[70vh] overflow-y-auto"
                                                        onPointerEnter={(e) => e.preventDefault()}
                                                        onPointerLeave={(e) => e.preventDefault()}
                                                        forceMount={openMenuKey === section.titleKey ? true : undefined}
                                                    >
                                                        <ul className="grid w-[400px] gap-3 p-4 md:w-[500px] md:grid-cols-2 lg:w-[600px] ">
                                                            {section.items.map((item) => (
                                                                <ListItem
                                                                    key={item.titleKey}
                                                                    title={t(item.titleKey)}
                                                                    href={`/${lng}${item.href}`}
                                                                    onClick={() => setOpenMenuKey("")}
                                                                >
                                                                    {item.descriptionKey && t(item.descriptionKey)}
                                                                </ListItem>
                                                            ))}
                                                        </ul>
                                                    </NavigationMenuContent>
                                                )}
                                            </NavigationMenuItem>
                                        ))}

                                        {/* 추가 네비게이션 항목 - 도메인별 활성화된 것만 (번역된) */}
                                        {additional.map((item) => (
                                            <NavigationMenuItem key={item.titleKey}>
                                                <Link href={`/${lng}${item.href}`} legacyBehavior passHref>
                                                    <NavigationMenuLink 
                                                        className={cn(
                                                            navigationMenuTriggerStyle(), 
                                                            "px-2 xl:px-3 text-sm whitespace-nowrap"
                                                        )}
                                                        onPointerEnter={(e) => e.preventDefault()}
                                                        onPointerLeave={(e) => e.preventDefault()}
                                                    >
                                                        {t(item.titleKey)}
                                                    </NavigationMenuLink>
                                                </Link>
                                            </NavigationMenuItem>
                                        ))}
                                    </NavigationMenuList>
                                </div>
                            </NavigationMenu>
                        </div>

                        {/* 우측 영역 */}
                        <div className="ml-auto flex flex-shrink-0 items-center space-x-2">
                            {/* 데스크탑에서는 CommandMenu, 모바일에서는 검색 아이콘만 */}
                            <div className="hidden md:block md:w-auto">
                                <CommandMenu />
                            </div>
                            <Button variant="ghost" size="icon" className="md:hidden" aria-label={t('common.search')}>
                                <SearchIcon className="h-5 w-5" />
                            </Button>

                            {/* 알림 버튼 */}
                            <NotificationDropdown />

                            {/* 사용자 메뉴 (번역된) */}
                            <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                    <Avatar className="cursor-pointer h-8 w-8">
                                        <AvatarImage src={`${session?.user?.image}`||"/user-avatar.jpg"} alt="User Avatar" />
                                        <AvatarFallback>
                                            {initials || "?"}
                                        </AvatarFallback>
                                    </Avatar>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent className="w-48" align="end">
                                    <DropdownMenuLabel>{t('user.my_account')}</DropdownMenuLabel>
                                    <DropdownMenuSeparator />
                                    <DropdownMenuItem asChild>
                                        <Link href={`${basePath}/settings`}>{t('user.settings')}</Link>
                                    </DropdownMenuItem>
                                    <DropdownMenuSeparator />
                                    <DropdownMenuItem onSelect={() => customSignOut({ callbackUrl: `${window.location.origin}${basePath}` })}>
                                        {t('user.logout')}
                                    </DropdownMenuItem>
                                </DropdownMenuContent>
                            </DropdownMenu>
                        </div>
                    </div>
                </div>

                {/* 모바일 메뉴 - 도메인별 활성화된 메뉴만 전달 (환경변수 필터링 적용) */}
                {isMobileMenuOpen && (
                    <MobileMenu 
                        lng={lng} 
                        onClose={toggleMobileMenu}
                        activeMenus={activeMenus}
                        domainMain={envFilteredMain}
                        domainAdditional={envFilteredAdditional}
                        t={t}
                    />
                )}
            </header>
        </>
    );
}

const ListItem = React.forwardRef<
    React.ElementRef<"a">,
    React.ComponentPropsWithoutRef<"a">
>(({ className, title, children, ...props }, ref) => {
    return (
        <li>
            <NavigationMenuLink asChild>
                <a
                    ref={ref}
                    className={cn(
                        "block select-none space-y-1 rounded-md p-3 leading-none no-underline outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground",
                        className
                    )}
                    {...props}
                >
                    <div className="text-sm font-medium leading-none">{title}</div>
                    {children && (
                        <p className="line-clamp-2 text-sm leading-snug text-muted-foreground">
                            {children}
                        </p>
                    )}
                </a>
            </NavigationMenuLink>
        </li>
    );
});
ListItem.displayName = "ListItem";

export function RouteLogger() {
    const path = usePathname();
    const qs   = useSearchParams()?.toString();
    React.useEffect(() => {
      console.log("[URL]", path + (qs ? "?" + qs : ""));
    }, [path, qs]);
    return null;
  }