'use client';

/**
 * 공통 헤더 컴포넌트
 * 
 * 모든 페이지에서 공통으로 사용되는 상단 헤더입니다.
 * - 로고
 * - 검색 바 (Ctrl+K 단축키)
 * - 사용자 정보 및 로그아웃
 */

import { useState, useRef, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import AISettingsModal from './AISettingsModal';
import { useReviewPermission } from '@/hooks/useReviewPermission';
import { useReviewQueueListener } from '@/hooks/useReviewQueueListener';

interface GlobalHeaderProps {
    variant?: 'wiki' | 'my' | 'daily';
    onTabChange?: (tab: 'wiki' | 'my' | 'daily') => void;
}

export default function GlobalHeader({ variant = 'wiki', onTabChange }: GlobalHeaderProps) {
    const { user, userRole, signOut } = useAuth();
    const router = useRouter();
    const [isMenuOpen, setIsMenuOpen] = useState(false);
    const [isAISettingsOpen, setIsAISettingsOpen] = useState(false);
    const menuRef = useRef<HTMLDivElement>(null);
    const { canViewReviewQueue } = useReviewPermission();
    const { items: reviewItems } = useReviewQueueListener(canViewReviewQueue);

    // 메뉴 외부 클릭 시 닫기
    useEffect(() => {
        function handleClickOutside(event: MouseEvent) {
            if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
                setIsMenuOpen(false);
            }
        }
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const handleSignOut = async () => {
        try {
            await signOut();
            router.push('/login');
        } catch (error) {
            console.error('로그아웃 에러:', error);
        }
    };

    if (!user) return null;

    return (
        <>
            <header className="bg-white/80 backdrop-blur-md shadow-sm border-b border-gray-200 sticky top-0 z-20">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-14 md:h-16 flex items-center justify-between gap-4">
                    {/* 1. 왼쪽 영역: 로고 및 토글 (Flex-1 for equal width) */}
                    <div className="flex items-center gap-2 sm:gap-6 flex-1 justify-start min-w-0">
                        <Link href="/?tab=wiki" className="flex items-center gap-2 hover:opacity-80 transition-opacity flex-shrink-0">
                            <span className={`text-lg md:text-xl font-bold transition-colors ${variant === 'daily' ? 'text-emerald-600' : variant === 'my' ? 'text-violet-600' : 'text-indigo-600'}`}>InsuWiki</span>
                            <span className="hidden xs:inline text-[10px] px-1.5 py-0.5 rounded-full bg-gray-100 text-gray-500 border border-gray-200 font-medium">Beta</span>
                        </Link>

                        {/* 헤더 미니 토글 (부장님 요청: 라벨 가시성 확보) */}
                        <div className="relative flex p-0.5 sm:p-1 bg-gray-100 rounded-xl items-center shadow-inner flex-shrink-0">
                            <button
                                onClick={() => onTabChange?.('wiki')}
                                className={`flex items-center gap-1 px-2 sm:px-3 py-1 sm:py-1.5 text-[11px] sm:text-xs font-bold rounded-lg transition-all duration-200 ${variant === 'wiki'
                                    ? 'bg-white text-indigo-600 shadow-sm'
                                    : 'text-gray-500 hover:text-gray-700'
                                    }`}
                            >
                                <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
                                </svg>
                                <span className="hidden sm:inline">Wiki</span>
                            </button>
                            <button
                                onClick={() => onTabChange?.('my')}
                                className={`flex items-center gap-1 px-2 sm:px-3 py-1 sm:py-1.5 text-[11px] sm:text-xs font-bold rounded-lg transition-all duration-200 ${variant === 'my'
                                    ? 'bg-white text-violet-600 shadow-sm'
                                    : 'text-gray-500 hover:text-gray-700'
                                    }`}
                            >
                                <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                                </svg>
                                <span className="hidden sm:inline">My</span>
                            </button>
                            <button
                                onClick={() => onTabChange?.('daily')}
                                className={`flex items-center gap-1 px-2 sm:px-3 py-1 sm:py-1.5 text-[11px] sm:text-xs font-bold rounded-lg transition-all duration-200 ${variant === 'daily'
                                    ? 'bg-white text-emerald-600 shadow-sm'
                                    : 'text-gray-500 hover:text-gray-700'
                                    }`}
                            >
                                <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                </svg>
                                <span className="hidden sm:inline">Daily</span>
                            </button>
                            {/* 슬라이딩 인디케이터 바 */}
                            <div
                                className={`absolute bottom-0 h-0.5 rounded-full transition-all duration-300 ${
                                    variant === 'wiki'
                                        ? 'bg-indigo-600'
                                        : variant === 'my'
                                        ? 'bg-violet-600'
                                        : 'bg-emerald-500'
                                }`}
                                style={{
                                    width: `${100 / 3}%`,
                                    left: `${(variant === 'wiki' ? 0 : variant === 'my' ? 1 : 2) * (100 / 3)}%`,
                                }}
                            />
                        </div>
                    </div>

                    {/* 2. 중앙 영역: 검색 바 (Flex-0, 고정 너비, 겹침 없음) */}
                    <div className="hidden lg:flex w-full max-w-sm xl:max-w-md px-4 justify-center">
                        <button
                            onClick={() => window.dispatchEvent(new CustomEvent('open-search'))}
                            className="w-full h-10 px-4 bg-gray-50 border border-gray-200 rounded-xl text-gray-400 text-sm flex items-center justify-between hover:bg-white hover:border-gray-300 hover:shadow-sm transition-all group pointer-events-auto"
                        >
                            <div className="flex items-center gap-2">
                                <svg className="w-4 h-4 text-gray-400 group-hover:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                                </svg>
                                <span>지식 탐색...</span>
                            </div>
                            <div className="hidden xl:flex items-center gap-1">
                                <kbd className="px-1.5 py-0.5 bg-white border border-gray-200 rounded-md text-[10px] font-bold text-gray-500 shadow-sm">Ctrl</kbd>
                                <kbd className="px-1.5 py-0.5 bg-white border border-gray-200 rounded-md text-[10px] font-bold text-gray-500 shadow-sm">K</kbd>
                            </div>
                        </button>
                    </div>

                    {/* 3. 오른쪽 영역: 사용자 정보 및 모바일 검색 (Flex-1) */}
                    <div className="flex items-center justify-end gap-2 sm:gap-3 flex-1">
                        {/* 모바일 검색 버튼 (돋보기) */}
                        <button
                            onClick={() => window.dispatchEvent(new CustomEvent('open-search'))}
                            className="lg:hidden p-2 text-gray-500 hover:text-indigo-600 hover:bg-gray-100 rounded-lg transition-colors"
                            aria-label="검색 열기"
                        >
                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                            </svg>
                        </button>

                        {/* 검토 큐 아이콘 (reviewer 이상) */}
                        {canViewReviewQueue && (
                            <button
                                onClick={() => router.push('/review')}
                                className="relative flex items-center gap-1 p-2 text-gray-500 hover:text-indigo-600 hover:bg-gray-100 rounded-lg transition-colors"
                                aria-label="검토 대기열"
                            >
                                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
                                </svg>
                                <span className="hidden sm:inline text-xs font-bold">Review</span>
                                {reviewItems.length > 0 && (
                                    <span className="absolute -top-0.5 -right-1.5 min-w-[16px] h-4 bg-red-500 text-white text-[10px] font-bold rounded-full flex items-center justify-center px-0.5 leading-none">
                                        {reviewItems.length > 99 ? '99+' : reviewItems.length}
                                    </span>
                                )}
                            </button>
                        )}

                        {/* 사용자 드롭다운 메뉴 */}
                        <div className="relative" ref={menuRef}>
                            <button
                                onClick={() => setIsMenuOpen(!isMenuOpen)}
                                className="flex items-center gap-2 pl-2 sm:pl-3 focus:outline-none"
                            >
                                {user.photoURL ? (
                                    <img src={user.photoURL} alt="User" className={`w-8 h-8 rounded-full border border-gray-200 transition-all ${isMenuOpen ? 'ring-2 ring-indigo-500 ring-offset-2' : ''}`} />
                                ) : (
                                    <div className={`w-8 h-8 rounded-full flex items-center justify-center font-bold text-xs sm:text-sm transition-all ${isMenuOpen ? 'ring-2 ring-indigo-500 ring-offset-2' : ''} ${variant === 'daily' ? 'bg-emerald-100 text-emerald-600' : variant === 'my' ? 'bg-violet-100 text-violet-600' : 'bg-indigo-100 text-indigo-600'}`}>
                                        {user.displayName?.[0] || 'U'}
                                    </div>
                                )}
                            </button>

                            {/* 드롭다운 메뉴 */}
                            {isMenuOpen && (
                                <div className="absolute right-0 mt-2 w-52 bg-white rounded-xl shadow-lg border border-gray-100 py-1 animate-fade-in-up origin-top-right z-50">
                                    <div className="px-4 py-3 border-b border-gray-100">
                                        <p className="text-sm font-semibold text-gray-900 truncate">{user.displayName}</p>
                                        <p className="text-xs text-gray-500 truncate">{user.email}</p>
                                    </div>

                                    {/* AI 설정 */}
                                    <button
                                        onClick={() => {
                                            setIsMenuOpen(false);
                                            setIsAISettingsOpen(true);
                                        }}
                                        className="w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 transition-colors flex items-center gap-2.5"
                                    >
                                        <svg className="w-4 h-4 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                        </svg>
                                        AI 설정
                                    </button>

                                    {/* 휴지통 */}
                                    <Link
                                        href="/trash"
                                        onClick={() => setIsMenuOpen(false)}
                                        className="w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 transition-colors flex items-center gap-2.5"
                                    >
                                        <svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                        </svg>
                                        휴지통
                                    </Link>

                                    {/* 관리자 패널 (admin 전용) */}
                                    {userRole === 'admin' && (
                                        <Link
                                            href="/admin"
                                            onClick={() => setIsMenuOpen(false)}
                                            className="w-full text-left px-4 py-2.5 text-sm text-indigo-700 hover:bg-indigo-50 transition-colors flex items-center gap-2.5"
                                        >
                                            <svg className="w-4 h-4 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                            </svg>
                                            관리자 패널
                                        </Link>
                                    )}

                                    <div className="border-t border-gray-100 mt-1">
                                        <button
                                            onClick={handleSignOut}
                                            className="w-full text-left px-4 py-2.5 text-sm text-red-600 hover:bg-red-50 hover:text-red-700 transition-colors flex items-center gap-2.5"
                                        >
                                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                                            </svg>
                                            로그아웃
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </header>

            <AISettingsModal
                isOpen={isAISettingsOpen}
                onClose={() => setIsAISettingsOpen(false)}
            />
        </>
    );
}
