/* global React */
/* hotfix6 + Roadmap 7.5 Part B.0 (2026-04-24):
 *   상단 탭 클릭 시 실제 네비게이션·toast + 우측 사용자명 RoleSim 기반 동적 렌더.
 *
 *  - learn    : 역할 기준 홈으로 이동 (branch_admin → admin/Home.html, teacher → teacher/home.html)
 *  - ai       : toast "AI 기능은 Phase 3에서 구현 예정"
 *  - service  : toast "설정·구독 관리는 Phase 3에서 구현 예정"
 *  - onTab 은 하위 호환 (activeTab 시각 상태 업데이트용).
 *
 *  Part B.0: 하드코딩 "류준형님" 제거 → RoleSim.getCurrentUser().display_name 기반.
 *   - 같은 탭 Tweaks 전환 시: window.dispatchEvent(new Event('c200-role-change')) 감청
 *   - 다른 탭 전환 시: storage 이벤트 감청 (sessionStorage 는 storage 이벤트 발생 안 하지만, Part E/F 학부모 때 localStorage 사용 가능성 대비) */
const { useState: useTB, useEffect: useTBE, useRef: useTBR } = React;

function TopBar({ tabs, activeTab, onTab, onToggleMobile }) {
  const [tick, setTick] = useTB(0);
  /* hotfix15 + Part C.2.5 TASK 5-B: 알림 벨 상태 */
  const [notifications, setNotifications] = useTB([]);
  const [showNotiDropdown, setShowNotiDropdown] = useTB(false);
  const bellRef = useTBR(null);

  useTBE(() => {
    const onRoleChange = () => setTick(t => t + 1);
    const onStorage = (e) => {
      if (e.key === 'c200-admin.role' || e.key === 'c200-admin.teacherId') {
        setTick(t => t + 1);
      }
      if (e.key === 'c200-admin.notifications') {
        loadNotifications();
      }
    };
    window.addEventListener('c200-role-change', onRoleChange);
    window.addEventListener('storage', onStorage);
    return () => {
      window.removeEventListener('c200-role-change', onRoleChange);
      window.removeEventListener('storage', onStorage);
    };
  }, []);

  function _currentUserId() {
    const u = window.RoleSim && window.RoleSim.getCurrentUser && window.RoleSim.getCurrentUser();
    if (!u) return null;
    return u.role === 'parent' ? u.id : 'u_' + u.id;
  }

  function loadNotifications() {
    if (typeof window.getNotifications !== 'function') { setNotifications([]); return; }
    const uid = _currentUserId();
    if (!uid) { setNotifications([]); return; }
    let list = window.getNotifications(uid) || [];
    list = list.filter(function (n) { return !n.resolved_at; });
    list.sort(function (a, b) { return (b.created_at || '').localeCompare(a.created_at || ''); });
    setNotifications(list);
  }

  /* 알림 로드 + 변경 감지 */
  useTBE(() => {
    loadNotifications();
    const onNotiChange = () => loadNotifications();
    const onRoleChange = () => loadNotifications();
    window.addEventListener('c200-notifications-change', onNotiChange);
    window.addEventListener('c200-role-change', onRoleChange);
    return () => {
      window.removeEventListener('c200-notifications-change', onNotiChange);
      window.removeEventListener('c200-role-change', onRoleChange);
    };
  }, [tick]);

  /* 드롭다운 외부 클릭 닫기 */
  useTBE(() => {
    if (!showNotiDropdown) return;
    const onDoc = (e) => {
      if (bellRef.current && !bellRef.current.contains(e.target)) setShowNotiDropdown(false);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [showNotiDropdown]);

  function _formatRelTime(iso) {
    if (!iso) return '';
    const diff = (Date.now() - new Date(iso).getTime()) / 1000;
    if (diff < 60) return '방금';
    if (diff < 3600) return Math.floor(diff / 60) + '분 전';
    if (diff < 86400) return Math.floor(diff / 3600) + '시간 전';
    return Math.floor(diff / 86400) + '일 전';
  }

  function handleNotiClick(noti) {
    if (typeof window.markNotificationRead === 'function') window.markNotificationRead(noti.id);
    setShowNotiDropdown(false);
    /* hotfix16 TASK 6: session_unassigned 우선 (ssot). 학생 단위는 호환만 */
    if (noti.action_type === 'reassign_unassigned_sessions') {
      if (typeof window.openSessionReassignModal === 'function') {
        window.openSessionReassignModal(null);
      }
    } else if (noti.action_type === 'reassign_unassigned') {
      /* hotfix15 호환 — 학생 단위 알림 */
      const path = window.location.pathname;
      const target = path.indexOf('/admin/') >= 0 ? 'Students.html?filter=unassigned' : '../admin/Students.html?filter=unassigned';
      window.location.href = target;
    } else if (noti.action_url) {
      window.location.href = noti.action_url;
    }
    loadNotifications();
  }

  function handleStudentLinkClick(studentUid, ev) {
    ev.stopPropagation();
    if (typeof window.openReassignModal === 'function') {
      window.openReassignModal(studentUid);
      setShowNotiDropdown(false);
      return;
    }
    /* 모달 컴포넌트 마운트 안 된 페이지 — 학생 목록으로 이동하며 자동 오픈 */
    const path = window.location.pathname;
    const sid = studentUid.startsWith('u_') ? studentUid.slice(2) : studentUid;
    const target = (path.indexOf('/admin/') >= 0 ? '' : '../admin/') + 'Students.html?reassign=' + sid;
    window.location.href = target;
  }

  const unreadCount = notifications.filter(function (n) { return !n.read_at; }).length;

  const currentUser = (window.RoleSim && window.RoleSim.getCurrentUser()) || null;
  /* hotfix10 TASK 2: 호칭 시스템 적용 — role.honorific 기반 동적 렌더.
   *  - teacher/staff/branch_admin: 'u_' + teacher.id 로 user_id 구성
   *  - parent: user.id 이미 u_pNNN */
  const displayText = (() => {
    if (!currentUser) return '사용자';
    if (typeof window.getFullHonorificSync !== 'function') {
      return (currentUser.display_name || currentUser.name || '사용자') + '님';
    }
    let uid;
    if (currentUser.role === 'parent') {
      uid = currentUser.id;
    } else {
      uid = 'u_' + currentUser.id;
    }
    return window.getFullHonorificSync(uid);
  })();
  const avatarChar = (currentUser?.name || '?')[0] || '?';

  const handleTabClick = (id) => {
    if (typeof onTab === 'function') onTab(id);
    if (id === 'ai') {
      window.showToast && window.showToast('AI 기능은 Phase 3에서 구현 예정');
      return;
    }
    if (id === 'service') {
      window.showToast && window.showToast('설정·구독 관리는 Phase 3에서 구현 예정');
      return;
    }
    if (id === 'learn') {
      const role = (window.RoleSim && window.RoleSim.getRole()) || 'branch_admin';
      const isOnTeacher = window.location.pathname.includes('/teacher/');
      const target = role === 'teacher' ? 'teacher/home.html' : 'admin/Home.html';
      const prefix = isOnTeacher ? '../' : '../';
      const dest = prefix + target;
      if (window.location.pathname.endsWith(target.split('/').pop())
          && window.location.pathname.includes(target.split('/')[0])) {
        return;
      }
      window.location.href = dest;
    }
  };

  return (
    <header className="tb">
      <button className="tb-hamburger" onClick={onToggleMobile} aria-label="메뉴 열기">
        <i data-lucide="menu"></i>
      </button>
      <div className="tb-tabs">
        {tabs.map((t) => (
          <button
            key={t.id}
            className={`tb-tab ${activeTab === t.id ? 'is-active' : ''}`}
            onClick={() => handleTabClick(t.id)}
          >
            {t.icon && <i data-lucide={t.icon}></i>}
            {t.label}
          </button>
        ))}
      </div>
      <div className="tb-right">
        <div className="tb-search">
          <i data-lucide="search"></i>
          <input placeholder="메뉴 / 학생 검색" />
          <kbd>⌘K</kbd>
        </div>
        {/* hotfix15 + Part C.2.5 TASK 5-B: 알림 벨 + 빨간 배지 + 드롭다운 */}
        <div className="tb-bell-wrap" ref={bellRef}>
          <button
            className={'tb-iconbtn tb-bell ' + (showNotiDropdown ? 'is-open' : '')}
            aria-label="알림"
            onClick={() => setShowNotiDropdown(v => !v)}
          >
            <i data-lucide="bell"></i>
            {unreadCount > 0 && (
              <span className="bell-badge">{unreadCount > 9 ? '9+' : unreadCount}</span>
            )}
          </button>
          {showNotiDropdown && (
            <div className="noti-dropdown" role="menu">
              <div className="noti-header">알림 ({notifications.length})</div>
              {notifications.length === 0 && (
                <div className="noti-empty">새로운 알림이 없습니다</div>
              )}
              {notifications.slice(0, 10).map((n) => {
                const isUnread = !n.read_at;
                return (
                  <div
                    key={n.id}
                    className={'noti-item ' + (isUnread ? 'is-unread' : '') + ' severity-' + (n.severity || 'info')}
                    onClick={() => handleNotiClick(n)}
                  >
                    <div className="noti-title">
                      {n.severity === 'warning' ? '⚠️ ' : n.severity === 'error' ? '🚨 ' : ''}
                      {n.title}
                    </div>
                    <div className="noti-message">{n.message}</div>
                    {/* hotfix15: 학생 단위 (deprecated, 잔존 알림 호환) */}
                    {n.type === 'student_unassigned' && Array.isArray(n.related_user_ids) && n.related_user_ids.length > 0 && (
                      <div className="noti-students">
                        {n.related_user_ids.map((sid) => {
                          const su = (window.mockUsers || {})[sid];
                          const sname = su ? su.name : sid;
                          return (
                            <button
                              key={sid}
                              className="noti-student-link"
                              onClick={(e) => handleStudentLinkClick(sid, e)}
                            >
                              <span>{sname}</span>
                              <span className="noti-student-meta">→ 재배정</span>
                            </button>
                          );
                        })}
                      </div>
                    )}
                    {/* hotfix16 TASK 6-B: 강의 단위 (ssot) — 강의 카드 chip + "재배정 시작" */}
                    {n.type === 'session_unassigned' && Array.isArray(n.session_summaries) && n.session_summaries.length > 0 && (
                      <div className="noti-sessions">
                        {n.session_summaries.map((sum) => (
                          <div key={sum.session_id} className="noti-session-chip">
                            <span className="noti-session-course">{sum.course_name}</span>
                            <span className="noti-session-meta">
                              {sum.schedule}{typeof sum.student_count === 'number' ? ' · 학생 ' + sum.student_count + '명' : ''}
                            </span>
                          </div>
                        ))}
                        <button
                          type="button"
                          className="btn-noti-action"
                          onClick={(e) => {
                            e.stopPropagation();
                            if (typeof window.markNotificationRead === 'function') window.markNotificationRead(n.id);
                            if (typeof window.openSessionReassignModal === 'function') {
                              window.openSessionReassignModal(null);
                            }
                            setShowNotiDropdown(false);
                          }}
                        >
                          → 재배정 시작
                        </button>
                      </div>
                    )}
                    <div className="noti-time">{_formatRelTime(n.created_at)}</div>
                  </div>
                );
              })}
              {notifications.length > 10 && (
                <div className="noti-footer">
                  <span>최근 10건만 표시됨 · 전체 {notifications.length}건</span>
                </div>
              )}
            </div>
          )}
        </div>
        <button className="tb-iconbtn" aria-label="도움말">
          <i data-lucide="circle-help"></i>
        </button>
        <button className="tb-user" title={currentUser?.id || ''}>
          <span className="av">{avatarChar}</span>
          <span className="tb-user-name">{displayText}</span>
          <i data-lucide="chevron-down"></i>
        </button>
      </div>
    </header>
  );
}
window.TopBar = TopBar;
