import React, { useState, useEffect, useRef } from 'react';
import useAppLayoutStore from '../../../../Store/AppLayoutSlice';
import './PageModeToggle.css';

const PAGE_MODES = [
  { id: 'chat', label: '聊天', icon: '💬' },
  { id: 'studio', label: '工作室', icon: '🎭' },
  { id: 'novel', label: '爽文', icon: '📖' },
  { id: 'room', label: '房间', icon: '🏠' },
];

const PageModeToggle = () => {
  const [isOpen, setIsOpen] = useState(false);
  const panelRef = useRef(null);

  const { activePage, setActivePage } = useAppLayoutStore();

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (panelRef.current && !panelRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen]);

  const handleModeSelect = (modeId) => {
    setActivePage(modeId);
    setIsOpen(false);
  };

  const currentMode = PAGE_MODES.find((m) => m.id === activePage) || PAGE_MODES[0];

  return (
    <div className="page-mode-toggle-wrapper" ref={panelRef}>
      <button
        className="action-btn page-mode-toggle"
        onClick={() => setIsOpen(!isOpen)}
        title={`当前模式：${currentMode.label}`}
        aria-haspopup="listbox"
        aria-expanded={isOpen}
      >
        {currentMode.icon}
      </button>

      {isOpen && (
        <div className="page-mode-selector-panel" role="listbox" aria-label="应用模式">
          <div className="page-mode-selector-header">
            <span className="page-mode-selector-title">应用模式</span>
          </div>
          <div className="page-mode-list">
            {PAGE_MODES.map((mode) => (
              <button
                key={mode.id}
                type="button"
                role="option"
                aria-selected={activePage === mode.id}
                className={`page-mode-item ${activePage === mode.id ? 'active' : ''}`}
                onClick={() => handleModeSelect(mode.id)}
              >
                <span className="page-mode-item-icon">{mode.icon}</span>
                <span className="page-mode-item-label">{mode.label}</span>
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default PageModeToggle;
