// shell.jsx — sidebar + topbar + page wrapper

const { Icon, Pill, Avatar } = window.RAlly;

const NAV_GROUPS = [
  {
    label: 'Workspace',
    items: [
      { key: 'intake',    icon: 'flag', label: '시작하기' },
      // AI 어시스턴트의 주 진입점은 우측 상주 패널. 이 메뉴는 넓은 화면에서 대화만 크게 보고 싶을 때 쓰는 전체화면 뷰.
      { key: 'chat',      icon: 'message', label: 'AI 대화 · 전체화면',
        title: 'AI 어시스턴트는 오른쪽 패널에 항상 떠 있습니다. 이 메뉴는 대화만 크게 보는 전체화면 뷰입니다.' },
      { key: 'dashboard', icon: 'home', label: '대시보드' },
      { key: 'tracks',    icon: 'layers', label: '트랙' },
    ],
  },
  {
    label: 'Documents & Quality',
    items: [
      { key: 'docs',      icon: 'file', label: '문서' },
      { key: 'fill',      icon: 'edit', label: '정보 입력' },
      { key: 'templates', icon: 'bookmark', label: '템플릿' },
      { key: 'audit',     icon: 'shield', label: '가상 심사' },
      { key: 'capa',      icon: 'beaker', label: 'CAPA', dot: true },
    ],
  },
  {
    label: 'Certification',
    items: [
      { key: 'cert',      icon: 'trophy', label: '인증 패키지' },
      { key: 'share',     icon: 'link', label: '외부 공유' },
    ],
  },
];

// Mapping nav item key → app screen
const NAV_TO_SCREEN = {
  intake: 'intake',
  chat: 'chat',
  dashboard: 'dashboard',
  tracks: 'track',
  docs: 'kanban',
  fill: 'fill',
  templates: 'templates',
  audit: 'audit',
  risk: 'risk',
  capa: 'capa',
  cert: 'cert',
  share: 'share',
};

const Sidebar = ({ screen, go, user, logout }) => {
  const u = user || (window.RAlly.getUser && window.RAlly.getUser()) ||
            { name: '사용자', roleLabel: '', org: '', initials: '··' };
  // Compute the active nav key from current screen
  const screenToNav = {
    intake: 'intake',
    chat: 'chat',
    dashboard: 'dashboard',
    track: 'tracks',
    kanban: 'docs',
    editor: 'docs',
    fill: 'fill',
    templates: 'templates',
    audit: 'audit',
    risk: 'risk',
    capa: 'capa',
    cert: 'cert',
    share: 'share',
  };
  const activeNav = screenToNav[screen];

  // 실데이터 카운트(하드코딩 제거)
  const [counts, setCounts] = React.useState({});
  React.useEffect(() => {
    fetch('/api/tracks').then((r) => r.json()).then((d) => {
      setCounts((c) => ({ ...c, tracks: (d.tracks || []).length }));
    }).catch(() => {});
    fetch('/api/catalog').then((r) => r.json()).then((d) => {
      if (d.ok) setCounts((c) => ({ ...c, docs: d.counts.total, templates: d.counts.total }));
    }).catch(() => {});
  }, []);

  return (
    <aside className="sidebar">
      <div className="sidebar__brand" onClick={() => go('dashboard')} style={{ cursor: 'pointer', justifyContent: 'flex-start' }} title="홈(대시보드)">
        <img src="logo_white_fit.svg" alt="RAlly" style={{ height: 30, width: 'auto', maxWidth: '85%', objectFit: 'contain' }} />
      </div>

      {NAV_GROUPS.map((group) => (
        <div className="nav-section" key={group.label}>
          <div className="nav-label">{group.label}</div>
          {group.items.map((item) => {
            const isActive = activeNav === item.key;
            const targetScreen = NAV_TO_SCREEN[item.key];
            return (
              <div
                key={item.key}
                className={'nav-item' + (isActive ? ' nav-item--active' : '')}
                onClick={() => targetScreen && go(targetScreen)}
                title={item.title || null}
                style={!targetScreen ? { opacity: 0.6 } : null}
              >
                <Icon name={item.icon} size={16} />
                <span>{item.label}</span>
                {(counts[item.key] != null || item.count != null) && (
                  <span className="nav-item__count">{counts[item.key] != null ? counts[item.key] : item.count}</span>
                )}
                {item.dot && <span style={{ marginLeft: 'auto', width: 6, height: 6, borderRadius: 999, background: 'var(--coral)' }} />}
              </div>
            );
          })}
        </div>
      ))}

      <div className="nav-section">
        <div className="nav-label">Mode</div>
        <div
          className={'nav-item' + (window.RAlly.isDemo() ? ' nav-item--active' : '')}
          onClick={() => window.RAlly.setDemo(!window.RAlly.isDemo())}
          title="데모 모드: 켜면 예시(더미) 데이터로 화면을 채워 보여줍니다. 끄면 실제 서비스 데이터만 표시."
        >
          <Icon name="sparkles" size={16} />
          <span>데모 모드</span>
          <span style={{ marginLeft: 'auto', fontSize: 11, fontWeight: 700,
            color: window.RAlly.isDemo() ? 'var(--coral)' : 'rgba(240,239,232,0.4)' }}>
            {window.RAlly.isDemo() ? 'ON' : 'OFF'}
          </span>
        </div>
      </div>

      <div className="sidebar__footer">
        <div className="sidebar__user">
          <Avatar initials={u.initials} variant="coral" size="lg" />
          <div style={{ minWidth: 0, flex: 1 }}>
            <div className="sidebar__user-name">{u.name}</div>
            <div className="sidebar__user-role">{u.roleLabel} · {u.org}</div>
          </div>
          {logout && (
            <span title="로그아웃" onClick={logout}
              style={{ cursor: 'pointer', color: 'rgba(240,239,232,0.55)', fontSize: 11, fontWeight: 600, padding: 4, whiteSpace: 'nowrap' }}
              onMouseEnter={(e) => (e.currentTarget.style.color = 'var(--coral)')}
              onMouseLeave={(e) => (e.currentTarget.style.color = 'rgba(240,239,232,0.55)')}>
              로그아웃
            </span>
          )}
        </div>
      </div>
    </aside>
  );
};

const Topbar = ({ crumbs, right }) => (
  <header className="topbar">
    <div className="crumb">
      {crumbs.map((c, i) => (
        <React.Fragment key={i}>
          {i > 0 && <Icon name="chev_right" size={12} className="crumb__sep" />}
          <span className={i === crumbs.length - 1 ? 'crumb__here' : null}>{c}</span>
        </React.Fragment>
      ))}
    </div>
    <div className="topbar__right">
      <div className="search">
        <Icon name="search" size={14} />
        <input placeholder="문서·트랙·위험·CAPA 검색…" />
        <span style={{ fontSize: 11, color: 'var(--ink-3)', border: '1px solid var(--line)', padding: '1px 5px', borderRadius: 3 }}>⌘K</span>
      </div>
      <button className="icon-btn" title="알림">
        <Icon name="bell" size={18} />
        <span className="icon-btn__dot" />
      </button>
      <button className="icon-btn" title="도움말">
        <Icon name="info" size={18} />
      </button>
      {right}
    </div>
  </header>
);

window.RAlly.Sidebar = Sidebar;
window.RAlly.Topbar = Topbar;
