'use client';

import Styles from '../styles/layout.module.scss';
import { useCallback } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import useAuth from '@/hooks/useAuth';
import useDragScroll from '@/hooks/useDragScroll';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faBars, faXmark, faCartShopping, faChevronLeft, faChevronRight } from '@fortawesome/free-solid-svg-icons';
import NotificationBell from '@/app/component/NotificationBell';
import HeaderSearch from '@/app/component/HeaderSearch';
import SearchCommand from '@/app/component/SearchCommand';
import Profile from '@/app/component/Profile';
import Logo from '@/app/component/Logo';
import PointChargeIcon from '@/public/icons/layout/point.svg';
import useCart from '@/hooks/useCart';
import { FEATURE_CHANNEL } from '@/constants/features';

// 채널/방송 메뉴(생방송·크리에이터)는 채널 기능 ON 일 때만 노출
const channelNavItems = [
	{ href: '/live', label: '생방송' },
	{ href: '/creators', label: '크리에이터' }
];

const baseNavItems = [
	{ href: '/market', label: '시장' },
	{ href: '/stock', label: '종목' },
	{ href: '/paper', label: '모의투자' },
	{ href: '/games', label: '게임' },
	{ href: '/board/briefing', label: '장전 시황' },
	{ href: '/board/proof', label: '수익인증' },
	{ href: '/feed/all', label: '피드' },
	{ href: '/store', label: '상점' },
	{ href: '/attendance', label: '출석부' },
	{ href: '/board/notice', label: '고객지원' }
];

const navItems = FEATURE_CHANNEL ? [...channelNavItems, ...baseNavItems] : baseNavItems;

const SCROLL_AMOUNT = 120;

type Props = {
	sidebarOpen: boolean;
	onToggle: () => void;
	// 좌측 사이드바 노출 여부 — false 면 모바일 햄버거(사이드바 토글)도 숨김
	showAside?: boolean;
};

export default function Header({ sidebarOpen, onToggle, showAside = true }: Props)
{
	const { isAuthenticated } = useAuth();
	const { totalCount: cartCount } = useCart();
	const pathname = usePathname();
	const dragScroll = useDragScroll<HTMLDivElement>();

	const scrollTabs = useCallback((dir: 'left' | 'right') => {
		const el = dragScroll.ref.current;
		if (!el) {
			return;
		}

		el.scrollBy({ left: dir === 'left' ? -SCROLL_AMOUNT : SCROLL_AMOUNT, behavior: 'smooth' });
	}, [dragScroll.ref]);

	const handlePopupCharge = useCallback(() => {
		const w = 450, h = 635;
		const left = window.screenX + (window.outerWidth - w) / 2;
		const top = window.screenY + (window.outerHeight - h) / 2;
		window.open('/charge', 'charge', `width=${w},height=${h},left=${left},top=${top},scrollbars=no,resizable=no`);
	}, []);

	return (
		<header id='header' className={Styles.header}>

			{/* 1줄: 로고 + 우측 아이콘 (PC에서는 전체 내비) */}
			<div className={Styles.headerRow1}>
				{/* 햄버거 — 좌측 사이드바(채널 or 관심종목) 슬라이드 토글 (모바일 전용). 사이드바 없는 페이지에선 미표시 */}
				{showAside && (
					<button type='button' className={Styles.hamburger} onClick={onToggle} aria-label='메뉴' aria-expanded={sidebarOpen}>
						<FontAwesomeIcon icon={sidebarOpen ? faXmark : faBars} />
					</button>
				)}

				<Link href='/' className={Styles.logo} aria-label="개미투자 홈">
					<Logo size="sm" />
				</Link>

				{/* PC 내비게이션 */}
				<nav className={Styles.pcNav} aria-label='주요 메뉴'>
					<ul className='flex gap-4'>
						{navItems.map(item => (
							<li key={item.label}>
								<Link href={item.href}>{item.label}</Link>
							</li>
						))}
					</ul>
				</nav>

				{/* 중앙 통합 검색 — 디바운스 suggest + combobox (Ctrl+K/'/' 포커스 포함) */}
				<HeaderSearch />

				{/* 우측 아이콘 (항상 표시) */}
				<div className={Styles.headerActions}>
					<Link href="/cart" className={Styles.cartBtn} title="장바구니" aria-label="장바구니">
						<FontAwesomeIcon icon={faCartShopping} />
						{cartCount > 0 && (
							<span className={Styles.cartBadge}>{cartCount > 99 ? '99+' : cartCount}</span>
						)}
					</Link>
					{isAuthenticated && (
						<>
							<button type="button" className={Styles.chargeBtn} onClick={handlePopupCharge} title="캐시 충전">
								<PointChargeIcon width={24} height={24} />
							</button>
							<NotificationBell />
						</>
					)}
					<Profile />
				</div>
			</div>

			{/* 2줄: 모바일 전용 가로 스크롤 탭 */}
			<nav className={Styles.headerRow2} aria-label='주요 메뉴 (모바일)'>
				<button type='button' className={Styles.scrollArrow} onClick={() => scrollTabs('left')} aria-label='왼쪽 스크롤'>
					<FontAwesomeIcon icon={faChevronLeft} />
				</button>
				<div
					className={Styles.mobileTabScroll}
					ref={dragScroll.ref}
					onMouseDown={dragScroll.onMouseDown}
					onMouseMove={dragScroll.onMouseMove}
					onMouseUp={dragScroll.onMouseUp}
					onMouseLeave={dragScroll.onMouseLeave}
				>
					{navItems.map(item => (
						<Link
							key={item.label}
							href={item.href}
							className={`${Styles.mobileTab}${pathname === item.href || (item.href !== '/' && pathname.startsWith(item.href)) ? ` ${Styles.mobileTabActive}` : ''}`}
						>
							{item.label}
						</Link>
					))}
				</div>
				<button type='button' className={Styles.scrollArrow} onClick={() => scrollTabs('right')} aria-label='오른쪽 스크롤'>
					<FontAwesomeIcon icon={faChevronRight} />
				</button>
			</nav>

			{/* 지수 티커 스트립 — TradingView 임베드 컨테이너 (규격만, 내용 주입 전까지 :empty 로 미표시) */}
			<div id='header-ticker' className={Styles.tickerStrip} aria-hidden='true' />

			{/* Ctrl+K / ⌘K 커맨드 팔레트 — 전역 (렌더 없음, 열릴 때만 표시) */}
			<SearchCommand />
		</header>
	);
}