// frontend-react/src/components/SideBarLeft/SideBarLeft.jsx
import React, { useRef } from 'react';
import './SideBarLeft.css';
import { useSideBarLeftStore } from '../../Store/indexStore';
import usePresetStore from '../../Store/SideBarLeft/PresetSlice';
import useApiConfigStore from '../../Store/SideBarLeft/ApiConfigSlice';
import Gallery from './tabs/Gallery';
import CharacterCard from './tabs/CharacterCard';
import ApiConfig from './tabs/ApiConfig';
import Presets from './tabs/Presets';
import WorldBook from './tabs/WorldBook';
import TokenUsage from './tabs/TokenUsage/TokenUsage';

const SideBarLeft = () => {
  const { activeTab, tabs, setActiveTab } = useSideBarLeftStore();
  const { fetchPresets } = usePresetStore();
  const { fetchProfiles } = useApiConfigStore();
  const contextMenuRef = useRef(null);

  // ✅ 右键菜单状态
  const [contextMenu, setContextMenu] = React.useState({
    visible: false,
    x: 0,
    y: 0,
    tab: null
  });

  // 处理标签切换
  const handleTabClick = (tabId) => {
    setActiveTab(tabId);
    
    // 如果切换到预设标签，刷新预设列表
    if (tabId === 'presets') {
      fetchPresets();
    }
    
    // 如果切换到API配置标签，刷新配置文件列表
    if (tabId === 'api') {
      fetchProfiles();
    }
  };

  // ✅ 显示右键菜单
  const handleContextMenu = (e, tab) => {
    e.preventDefault();
    setContextMenu({
      visible: true,
      x: e.clientX,
      y: e.clientY,
      tab: tab
    });
  };

  // ✅ 关闭右键菜单
  const closeContextMenu = () => {
    setContextMenu({ visible: false, x: 0, y: 0, tab: null });
  };

  // ✅ 点击菜单项后自动切换到对应标签
  const handleSwitchToTab = (tabId) => {
    handleTabClick(tabId);
    closeContextMenu();
  };

  return (
    <div className="sidebar-left">
      <div className="sidebar-tabs">
        {tabs.map(tab => (
          <button
            key={tab.id}
            className={`tab-button ${activeTab === tab.id ? 'active' : ''}`}
            onClick={() => handleTabClick(tab.id)}
            onContextMenu={(e) => handleContextMenu(e, tab)}  // ✅ 添加右键菜单
            // ✅ 移除 title，改用右键菜单显示详情
          >
            {tab.label}
          </button>
        ))}
      </div>

      <div className="sidebar-content">
        {activeTab === 'gallery' && <Gallery />}
        {activeTab === 'character' && <CharacterCard />}
        {activeTab === 'api' && <ApiConfig />}
        {activeTab === 'presets' && <Presets />}
        {activeTab === 'worldbook' && <WorldBook />}
        {activeTab === 'tokenUsage' && <TokenUsage />}
      </div>

      {/* ✅ 右键菜单 */}
      {contextMenu.visible && contextMenu.tab && (
        <div 
          className="context-menu-overlay"
          onClick={closeContextMenu}
        >
          <div 
            className="context-menu sidebar-tab-context-menu"
            ref={contextMenuRef}
            style={{ left: `${contextMenu.x}px`, top: `${contextMenu.y}px` }}
            onClick={(e) => e.stopPropagation()}
          >
            {/* 菜单标题 - 显示标签名称 */}
            <div className="context-menu-header">
              <span className="menu-title">{contextMenu.tab.label}</span>
            </div>
            
            {/* 菜单描述 */}
            <div className="context-menu-description">
              {contextMenu.tab.title}
            </div>
            
            <div className="context-menu-divider"></div>
            
            {/* 操作项 */}
            <div className="context-menu-item" onClick={() => handleSwitchToTab(contextMenu.tab.id)}>
              <span className="menu-icon">📂</span>
              <span className="menu-label">打开</span>
            </div>
            
            {/* 根据标签类型显示不同的快捷操作 */}
            {contextMenu.tab.id === 'character' && (
              <>
                <div className="context-menu-item" onClick={() => { handleSwitchToTab('character'); setTimeout(() => document.querySelector('.create-character-btn')?.click(), 100); }}>
                  <span className="menu-icon">➕</span>
                  <span className="menu-label">新建角色</span>
                </div>
              </>
            )}
            
            {contextMenu.tab.id === 'presets' && (
              <>
                <div className="context-menu-item" onClick={() => { handleSwitchToTab('presets'); setTimeout(() => document.querySelector('.create-preset-btn')?.click(), 100); }}>
                  <span className="menu-icon">➕</span>
                  <span className="menu-label">新建预设</span>
                </div>
              </>
            )}
            
            {contextMenu.tab.id === 'worldbook' && (
              <>
                <div className="context-menu-item" onClick={() => { handleSwitchToTab('worldbook'); setTimeout(() => document.querySelector('.action-btn')?.click(), 100); }}>
                  <span className="menu-icon">➕</span>
                  <span className="menu-label">新建世界书</span>
                </div>
              </>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default SideBarLeft;
