// ============================================================
// NavBar — 自定义顶部导航栏（替代系统菜单）
//
// 逻辑：
//   - 所有导航项默认全部显示（不再按登录状态隐藏）
//   - 未登录时点击需登录的项 → 弹出提示"请先登录"并触发登录 Modal
//   - 登录/注册 与 退出登录 仍按登录状态互斥显示
// ============================================================

import { useState, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { App } from 'antd';

import { useAppContext } from '@/contexts/app-context';
import { useTheme } from '@/hooks/use-theme';
import { emit, EVENTS } from '@/utils/event-bus.ts';
import { NavItem } from './NavItem';
import { AnnouncementDrawer } from './AnnouncementDrawer';
import { personalLeft, personalRight, enterpriseLeft, enterpriseRight } from './nav-config';
import type { NavItemConfig } from './types';

const NAVBAR_HEIGHT = 56;

export function NavBar() {
   const { platform, edition, isLoggedIn, logout } = useAppContext();
   const { isDark } = useTheme();
   const { message } = App.useApp();
   const navigate = useNavigate();

   const [drawerOpen, setDrawerOpen] = useState(false);

   // 根据版本选择导航项
   const { leftItems, rightItems } = useMemo(() => {
      const isEnterprise = edition === 'enterprise';
      return {
         leftItems: isEnterprise ? enterpriseLeft : personalLeft,
         rightItems: isEnterprise ? enterpriseRight : personalRight,
      };
   }, [edition]);

   // 过滤规则：
   //   requireGuest → 仅未登录时可见（登录/注册）
   //   "退出登录"  → 仅已登录时可见
   //   其他所有项   → 始终可见，未登录点击时弹"请先登录"
   const visibleLeft = useMemo(
      () =>
         leftItems.filter((item) => {
            if (item.requireGuest && isLoggedIn) return false;
            return !(item.key === 'logout' && !isLoggedIn);
         }),
      [leftItems, isLoggedIn],
   );
   const visibleRight = useMemo(
      () =>
         rightItems.filter((item) => {
            if (item.requireGuest && isLoggedIn) return false;
            return !(item.key === 'logout' && !isLoggedIn);
         }),
      [rightItems, isLoggedIn],
   );

   // 点击导航项
   const handleNavClick = useCallback(
      (item: NavItemConfig) => {
         // 需要登录但未登录 → 提示并弹出登录 Modal
         if (item.requireLogin && !isLoggedIn) {
            message.warning('请先登录');
            emit(EVENTS.SHOW_LOGIN);
            return;
         }

         switch (item.action) {
            case 'drawer':
               if (item.key === 'announcements') {
                  setDrawerOpen(true);
               }
               break;

            case 'button':
               if (item.key === 'logout') {
                   logout();
               }
               break;

            case 'external':
               if (item.target) {
                  window.open(item.target, '_blank');
               }
               break;

            case 'navigate':
            case 'spa':
               if (item.key === 'auth') {
                  emit(EVENTS.SHOW_LOGIN);
               } else if (item.target) {
                  navigate(item.target);
               }
               break;
         }
      },
      [isLoggedIn, logout, message],
   );

   const macPaddingLeft = platform === 'darwin' ? 80 : 12;

   return (
      <>
         <div
            className="navbar-drag-region flex items-center justify-between select-none"
            style={{
               height: NAVBAR_HEIGHT,
               paddingLeft: macPaddingLeft,
               paddingRight: 12,
               background: isDark
                  ? 'linear-gradient(180deg, #1E1B4B 0%, #1A1730 100%)'
                  : 'linear-gradient(180deg, #FFFFFF 0%, #F5F3FF 100%)',
               borderBottom: `1px solid ${isDark ? '#2E2A4A' : '#E5E7EB'}`,
               boxShadow: isDark ? '0 1px 4px rgba(0,0,0,0.3)' : '0 1px 4px rgba(99,102,241,0.06)',
            }}
         >
            <div className="navbar-no-drag flex items-center gap-0.5">
               {visibleLeft.map((item) => (
                  <NavItem key={item.key} item={item} onClick={handleNavClick} />
               ))}
            </div>

            <div className="navbar-no-drag flex items-center gap-0.5">
               {visibleRight.map((item) => (
                  <NavItem key={item.key} item={item} onClick={handleNavClick} />
               ))}
            </div>
         </div>

         <AnnouncementDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)} />
      </>
   );
}
