// ============================================================
// SettingsPage — 设置页面（Modal 居中叠加，事件驱动显隐）
//
// 核心设计：
//   - 通过 open/onClose props 控制显隐，不使用路由（避免主页面被卸载）
//   - Modal 居中弹出 + 遮罩层，首页内容始终保持挂载不动
//   - destroyOnHidden → 关闭即销毁 DOM，不堆内存
//   - Esc 键可关闭（跨平台统一）
//   - macOS：关闭按钮移至标题左侧（遵循 macOS HIG）
//
// 对应 QT 原版：设置窗口为独立窗口叠加在主窗口之上，主窗口不销毁
// ============================================================

import { useCallback } from 'react';
import { Modal } from 'antd';
import { SettingOutlined, CloseOutlined } from '@ant-design/icons';
import { useAppContext } from '@/contexts/app-context';
import { isMacOS } from '@/utils/platform';
import { ThemeSetting } from './blocks/ThemeSetting';
import { StoragePathSetting } from './blocks/StoragePathSetting';
import { SystemInfoSetting } from './blocks/SystemInfoSetting';
import { UpdateSetting } from './blocks/UpdateSetting';
import { PasswordSetting } from './blocks/PasswordSetting';

interface SettingsPageProps {
   open: boolean;
   onClose: () => void;
}

export function SettingsPage({ open, onClose }: SettingsPageProps) {
   const { edition } = useAppContext();
   const isMac = isMacOS();

   // 关闭后移除焦点，避免跑到导航栏设置按钮上
   const handleAfterClose = useCallback(() => {
      (document.activeElement as HTMLElement)?.blur();
   }, []);

   return (
      <Modal
         open={open}
         width={480}
         onCancel={onClose}
         afterClose={handleAfterClose}
         destroyOnHidden={true}
         mask={{ closable: false }}
         closable={!isMac}
         footer={null}
         title={
            <span className="flex items-center gap-2">
               {isMac && (
                  <CloseOutlined
                     onClick={onClose}
                     className="cursor-pointer text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                  />
               )}
               <SettingOutlined />
               设置
            </span>
         }
         styles={{ body: { padding: 0, maxHeight: '70vh', overflow: 'auto' } }}
      >
         <div className="flex flex-col gap-4 p-4">
            <ThemeSetting />
            <SystemInfoSetting />
            <UpdateSetting />
            <StoragePathSetting edition={edition} />
            <PasswordSetting />
         </div>
      </Modal>
   );
}
