import { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import SideNav, { keyToPath, pathToKey } from './SideNav';

// 퍼블리시 패널 컴포넌트 재사용
import Panel1Component from '../../publish/pages/Panel1Component';
import Panel2Component from '../../publish/pages/Panel2Component';
import Panel3Component from '../../publish/pages/Panel3Component';
import Panel4Component from '../../publish/pages/Panel4Component';
import Panel5Component from '../../publish/pages/Panel5Component';
import Panel6Component from '../../publish/pages/Panel6Component';
import Panel8Component from '../../publish/pages/Panel8Component';
// DisplayComponent는 스토어 연결된 버전 사용
import DisplayComponent from '../../component/wrap/side/DisplayComponent';
// 구현된 페이지
import ReplayPage from '../../pages/ReplayPage';

/**
 * 사이드바 컴포넌트
 * - 네비게이션 메뉴
 * - 패널 영역 (경로에 따라 다른 패널 표시)
 */
export default function Sidebar() {
  const navigate = useNavigate();
  const location = useLocation();
  // 초기에 메뉴가 선택되지 않았으면 패널도 닫힌 상태
  const initialActiveKey = (() => {
    const path = location.pathname.split('/')[1];
    return path ? pathToKey[path] : null;
  })();
  const [isPanelOpen, setIsPanelOpen] = useState(initialActiveKey !== null);

  // URL에서 활성 메뉴 키 추출 (루트 경로면 비활성)
  const getActiveKey = () => {
    const path = location.pathname.split('/')[1];
    if (!path) return null; // 루트 경로면 비활성
    return pathToKey[path] || null;
  };

  const activeKey = getActiveKey();

  const handleMenuChange = (key) => {
    setIsPanelOpen(true);
    const path = keyToPath[key] || 'ship';
    navigate(`/${path}`);
  };

  const handleTogglePanel = () => {
    setIsPanelOpen((prev) => !prev);
  };

  // 패널 공통 props
  const panelProps = {
    isOpen: isPanelOpen,
    onToggle: handleTogglePanel,
  };

  // 활성 키에 따른 패널 컴포넌트 렌더링
  const renderPanel = () => {
    switch (activeKey) {
      case 'gnb1':
        return <Panel1Component {...panelProps} />;
      case 'gnb2':
        return <Panel2Component {...panelProps} />;
      case 'gnb3':
        return <Panel3Component {...panelProps} />;
      case 'gnb4':
        return <Panel4Component {...panelProps} />;
      case 'gnb5':
        return <Panel5Component {...panelProps} />;
      case 'gnb6':
        return <Panel6Component {...panelProps} />;
      case 'gnb7':
        return <ReplayPage {...panelProps} />;
      case 'gnb8':
        return <Panel8Component {...panelProps} />;
      case 'filter':
        return <DisplayComponent {...panelProps} initialTab="filter" />;
      case 'layer':
        return <DisplayComponent {...panelProps} initialTab="layer" />;
      default:
        return null; // 선택된 메뉴 없으면 패널 없음
    }
  };

  return (
    <section id="sidePanel">
      <SideNav activeKey={activeKey} onChange={handleMenuChange} />
      <div className="sidePanelContent">
        {renderPanel()}
      </div>
    </section>
  );
}
