/* global React */
/* E-1 Part 2b §2 (§5.11): Teacher 뷰 전용 사이드바.
 *
 * §5.11 구조: 4개 메뉴 ([내 강의] 섹션) + 로그아웃.
 * Admin Sidebar 대비 차이:
 *  - 상단 브랜드 "CRM · 지점" → "CRM · 강사"
 *  - 섹션 "운영/학생·수업/재무/추후 확장" → "내 강의" 단일 섹션
 *  - 하단 지점 뱃지 하단에 강사 이름 (§9.3)
 *
 * Phase 3 연결: 로그아웃 버튼은 Phase 3 auth 엔드포인트. 현재는 toast. */
(function () {
  const { useEffect } = React;

  function TeacherSidebar({ current, mobileOpen, onMobileClose, fromBoard = false }) {
    useEffect(() => { if (window.lucide) window.lucide.createIcons(); });

    /* hotfix4 #4: 공지 섹션 추가 (본사 공지 / 지점 공지 / 자료실).
       Board.html?role=teacher 로 이동 — Admin Board 컴포넌트를 roleMode=teacher 로 재사용. */
    const mySection = [
      { id: 'home',       label: '홈',         icon: 'layout-dashboard', href: 'home.html' },
      { id: 'timetable',  label: '내 시간표',  icon: 'calendar-clock',   href: 'timetable.html' },
      { id: 'students',   label: '내 담당 학생', icon: 'users',          href: 'students.html' },
      { id: 'logs',       label: '내 수업일지', icon: 'clipboard-list',  href: 'session-logs.html' },
    ];
    const boardSection = [
      { id: 'board:notice',    label: '본사 공지',  icon: 'megaphone',
        href: '../admin/Board.html?tab=notice&role=teacher' },
      { id: 'board:free',      label: '지점 공지',  icon: 'clipboard-list',
        href: '../admin/Board.html?tab=free&role=teacher' },
      { id: 'board:resources', label: '자료실',     icon: 'folder-open',
        href: '../admin/Board.html?tab=resources&role=teacher' },
    ];

    const currentUser = (window.RoleSim && window.RoleSim.getCurrentUser()) || null;
    /* hotfix10 TASK 2: 호칭 적용 */
    const teacherName = (() => {
      if (!currentUser) return '강사';
      if (typeof window.getShortHonorificSync === 'function') {
        return window.getShortHonorificSync('u_' + currentUser.id);
      }
      return currentUser.display_name || '강사';
    })();

    const onClick = (it) => {
      onMobileClose && onMobileClose();
      /* fromBoard=true (Board 에서 렌더 중) 이면 상대 경로 보정: ../teacher/home.html */
      if (fromBoard && it.href && !it.href.startsWith('..') && !it.href.startsWith('http')) {
        window.location.href = '../teacher/' + it.href;
      } else {
        window.location.href = it.href;
      }
    };

    const onLogout = () => {
      window.showToast && window.showToast('Phase 3 에서 로그아웃 구현');
    };

    const renderSection = (items, label) => (
      <div className="sb-section">
        <div className="sb-section-label">{label}</div>
        {items.map(it => {
          const isActive = current === it.id;
          return (
            <button
              key={it.id}
              className={`sb-item ${isActive ? 'is-active' : ''}`}
              onClick={() => onClick(it)}
            >
              <i data-lucide={it.icon} className="sb-ic"></i>
              <span>{it.label}</span>
            </button>
          );
        })}
      </div>
    );

    return (
      <aside className={`sb ${mobileOpen ? 'is-open' : ''}`}>
        <div
          className="sb-brand sb-brand-link"
          role="link"
          tabIndex={0}
          onClick={() => { window.location.href = '../teacher/home.html'; }}
          onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); window.location.href = '../teacher/home.html'; } }}
          title="홈으로"
        >
          <div className="sb-mark">
            <img src={fromBoard ? '../assets/logo3-full.png' : '../assets/logo3-full.png'} alt="Challenge200" />
          </div>
          <div>
            <div className="sb-brand-name">챌린지200</div>
            <div className="sb-brand-sub">CRM · 강사</div>
          </div>
        </div>

        <div className="sb-scroll">
          {renderSection(mySection, '내 강의')}
          {renderSection(boardSection, '공지')}
        </div>

        <div className="sb-foot">
          <div className="sb-branch sb-branch-static" aria-label="현재 지점 + 강사">
            <div className="sb-branch-ic">광주</div>
            <div className="sb-branch-label">
              <div className="sb-branch-name">광주봉선지점</div>
              <div className="sb-branch-sub">{teacherName}</div>
            </div>
          </div>
          <button className="sb-logout" onClick={onLogout}>
            <i data-lucide="log-out"></i>
            <span>로그아웃</span>
          </button>
        </div>
      </aside>
    );
  }

  window.TeacherSidebar = TeacherSidebar;
})();
