/* global React */
// Phase 4 HQ: 지점별 메뉴 가시성 토글 (본사가 지점별로 메뉴 on/off 제어)
// Phase F: 챌린저AI / 챌린지북 = 별도 도메인 외부 확장 앱, SSO 연결
// Phase C-2: 강의실 href 활성화 / C-3: 챌린저AI href / C-4a: 마이페이지 서브메뉴
// Phase C-2.1-fix: ≤1024 햄버거 토글 연동 — window CustomEvent('s-sidebar:toggle'), ESC·백드롭·메뉴 클릭 시 닫힘
// Phase C-4a: 마이페이지 아코디언 — current 가 'mypage' 혹은 'mypage-*' 로 시작하면 자동 펼침
function StudentSidebar({ current, onNavigate }) {
  const { useState, useEffect, useCallback } = React;
  const [isOpen, setIsOpen] = useState(false);

  const close = useCallback(() => setIsOpen(false), []);

  useEffect(() => {
    const onToggle = () => setIsOpen(v => !v);
    const onKey = (e) => { if (e.key === 'Escape') setIsOpen(false); };
    const onResize = () => { if (window.innerWidth > 1024) setIsOpen(false); };
    window.addEventListener('s-sidebar:toggle', onToggle);
    window.addEventListener('keydown', onKey);
    window.addEventListener('resize', onResize);
    return () => {
      window.removeEventListener('s-sidebar:toggle', onToggle);
      window.removeEventListener('keydown', onKey);
      window.removeEventListener('resize', onResize);
    };
  }, []);

  const sections = [
    { group: '학습 서비스', items: [
      { id: 'home',       label: '홈',         icon: 'home',        href: 'student-home.html' },
      { id: 'classroom',  label: '강의실',     icon: 'play-circle', href: 'classroom.html' },
      { id: 'ai',         label: '챌린저AI',   icon: 'sparkles',    moon: true, href: 'challenger-ai.html' },
      { id: 'board',      label: '게시판',     icon: 'megaphone',   href: 'board.html', badgeKey: 'posts7d' },
      { id: 'mypage',     label: '마이페이지', icon: 'circle-user', href: 'mypage.html',
        sub: [
          { id: 'mypage-profile',  label: '내 정보 변경',    href: 'mypage-profile.html' },
          { id: 'mypage-scores',   label: '모의고사 성적표', href: 'mypage-scores.html' },
          { id: 'mypage-qna',      label: '학습 정리',       href: 'mypage-qna.html' },
          { id: 'mypage-payments', label: '결제 내역',       href: 'mypage-payments.html' },
          { id: 'mypage-terms',    label: '약관 및 동의',    href: 'mypage-terms.html' },
          { id: 'mypage-support',  label: '고객센터',        href: 'mypage-support.html' },
        ]
      },
    ]},
    { group: '학습 도우미', items: [
      { id: 'quick',      label: '빠른 채점',  icon: 'check-circle', phaseMsg: '빠른 채점은 Phase C-5에서 구현됩니다' },
      { id: 'listening',  label: '리스닝',     icon: 'headphones',   phaseMsg: '리스닝 파트 다시 듣기는 Phase C-5에서 구현됩니다' },
    ]},
    { group: '결제', items: [
      { id: 'pass-pay',   label: '수강권 결제', icon: 'credit-card', phaseMsg: '수강권 결제는 Phase C-6에서 구현됩니다' },
      { id: 'book-buy',   label: '교재 구매',   icon: 'book-open',   phaseMsg: '교재 구매는 Phase F (챌린지북)에서 구현됩니다' },
    ]},
  ];

  const ext = [
    { id: 'ai-app',   label: '챌린저AI', icon: 'sparkles', phaseMsg: '챌린저AI SSO 연결은 Phase F에서 구현됩니다' },
    { id: 'book-app', label: '챌린지북', icon: 'book',     phaseMsg: '챌린지북 SSO 연결은 Phase F에서 구현됩니다' },
  ];

  const cur = current || '';
  const isInMypage = cur === 'mypage' || cur.startsWith('mypage-');

  /* C-5a: 게시판 메뉴 배지 — 최근 7일 이내 공지 개수 (window.POSTS_MOCK 로드된 페이지에서만) */
  const posts7dCount = (() => {
    try {
      if (!Array.isArray(window.POSTS_MOCK)) return 0;
      const cut = Date.now() - 7 * 86400000;
      return window.POSTS_MOCK.filter(p => {
        if (p.boardType !== 'notice' && p.boardType !== 'branch') return false;
        const t = new Date(p.createdAt.replace(' ', 'T')).getTime();
        return !isNaN(t) && t >= cut;
      }).length;
    } catch (_) { return 0; }
  })();

  const handleClick = (item) => {
    setIsOpen(false);
    if (current === item.id) {
      if (onNavigate) onNavigate(item.id);
      return;
    }
    if (item.href) {
      window.location.href = item.href;
      return;
    }
    if (window.showToast) window.showToast(item.phaseMsg || item.notImplementedMsg || 'Phase 3에서 구현됩니다');
  };

  const handleSubClick = (sub) => {
    setIsOpen(false);
    if (sub.href) {
      window.location.href = sub.href;
      return;
    }
    if (window.showToast) window.showToast(sub.notImplementedMsg || 'Phase 3에서 구현됩니다');
  };

  return (
    <>
      <aside className={`s-sb ${isOpen ? 'is-open' : ''}`}>
        <div className="s-sb-scroll">
          {sections.map((sec, i) => (
            <div key={i} className="s-sb-section">
              <div className="s-sb-group">{sec.group}</div>
              {sec.items.map(it => {
                const hasSub = Array.isArray(it.sub) && it.sub.length > 0;
                const expanded = hasSub && (isInMypage && it.id === 'mypage');
                return (
                  <React.Fragment key={it.id}>
                    <button
                      className={`s-sb-item ${current === it.id ? 'is-active' : ''}`}
                      onClick={() => handleClick(it)}
                    >
                      <i data-lucide={it.icon}></i>
                      <span>{it.label}</span>
                      {it.moon && <span className="s-sb-moon" title="다크 테마 메뉴">🌙</span>}
                      {it.badgeKey === 'posts7d' && posts7dCount > 0 && <span className="s-sb-counter-dot">{posts7dCount}</span>}
                      {hasSub && <i data-lucide={expanded ? 'chevron-down' : 'chevron-right'} className="s-sb-chev"></i>}
                    </button>
                    {hasSub && expanded && (
                      <div className="s-sb-sub">
                        {it.sub.map(sub => (
                          <button
                            key={sub.id}
                            className={`s-sb-subitem ${current === sub.id ? 'is-active' : ''}`}
                            onClick={() => handleSubClick(sub)}
                          >
                            <span>{sub.label}</span>
                          </button>
                        ))}
                      </div>
                    )}
                  </React.Fragment>
                );
              })}
            </div>
          ))}

          <div className="s-sb-divider"></div>

          <div className="s-sb-section">
            <div className="s-sb-group">확장 앱</div>
            {ext.map(it => (
              <button
                key={it.id}
                className="s-sb-item"
                onClick={() => {
                  setIsOpen(false);
                  if (window.showToast) window.showToast(it.phaseMsg);
                }}
              >
                <i data-lucide={it.icon}></i>
                <span>{it.label}</span>
                <i data-lucide="external-link" className="s-sb-ext"></i>
              </button>
            ))}
          </div>
        </div>

        <div className="s-sb-foot">
          <button
            className="s-sb-logout"
            onClick={() => {
              setIsOpen(false);
              if (window.showToast) window.showToast('로그아웃은 Phase G (공식 홈페이지)에서 구현됩니다');
            }}
          >
            <i data-lucide="log-out"></i>
            <span>로그아웃</span>
          </button>
        </div>
      </aside>
      <div
        className={`s-sb-backdrop ${isOpen ? 'is-open' : ''}`}
        onClick={close}
        aria-hidden="true"
      />
    </>
  );
}
window.StudentSidebar = StudentSidebar;
