// Sidebar.jsx — left rail, header, popmenus

function PopMenu({ items, onClose, style }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) onClose(); };
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    const tid = setTimeout(() => document.addEventListener('mousedown', onClick), 0);
    document.addEventListener('keydown', onKey);
    return () => { clearTimeout(tid); document.removeEventListener('mousedown', onClick); document.removeEventListener('keydown', onKey); };
  }, []);
  return (
    <div className="ch-popmenu" ref={ref} style={style} onClick={e => e.stopPropagation()}>
      {items.map((it, i) => it.divider
        ? <div key={i} className="div"/>
        : it.section
        ? <div key={i} className="section">{it.section}</div>
        : <button key={i} className={'item' + (it.danger ? ' danger' : '')} onClick={(e) => { e.stopPropagation(); it.onClick && it.onClick(); onClose(); }}>
            <span className="ic">{it.ic}</span><span className="lbl">{it.label}</span>{it.kbd && <kbd>{it.kbd}</kbd>}
          </button>)}
    </div>
  );
}

function ChatRail({ threads, active, onSelect, onNew, onOpenSettings, onOpenAdmin, onSearch, onThreadAction, onSignOut, onClose, user }) {
  const [menu, setMenu] = React.useState(null); // thread id whose ⋯ menu is open
  const displayName = (user && user.display_name) || (user ? user.email : 'guest');
  const subline = user
    ? ((user.is_admin ? 'admin' : 'member') + ' · ' + user.email)
    : 'not signed in';
  const initial = (displayName || '?')[0].toUpperCase();
  return (
    <aside className="ch-rail">
      <div className="ch-rail-brand">
        <img src="../../assets/zigu-logo-gold.png" alt="GBR"/>
        <span className="wm">GBR</span>
        <span className="ver">v2.4 · dev</span>
        {onClose && (
          <button className="ch-rail-close" onClick={onClose} aria-label="메뉴 닫기" data-tip="닫기">×</button>
        )}
      </div>
      <button className="ch-new" onClick={onNew} data-tip={'새 대화 · ' + window.MOD_KEY + 'N'}>+ 새 대화</button>
      <div className="ch-search" onClick={onSearch} data-tip="대화·모델·인증서 검색">
        <span>⌕</span><span>대화 검색</span><kbd>{window.MOD_KEY} K</kbd>
      </div>
      <div className="ch-rail-section">고정됨</div>
      <div className="ch-threads">
        {threads.filter(t => t.pinned).map(t => (
          <ThreadRow key={t.id} t={t} active={active === t.id} menuOpen={menu === t.id}
            onSelect={() => onSelect(t.id)} onMenu={() => setMenu(menu === t.id ? null : t.id)}
            onCloseMenu={() => setMenu(null)} onAction={(a) => onThreadAction && onThreadAction(a, t)}/>
        ))}
        <div className="ch-rail-section" style={{paddingLeft: 10, paddingTop: 14}}>최근</div>
        {threads.filter(t => !t.pinned).map(t => (
          <ThreadRow key={t.id} t={t} active={active === t.id} menuOpen={menu === t.id}
            onSelect={() => onSelect(t.id)} onMenu={() => setMenu(menu === t.id ? null : t.id)}
            onCloseMenu={() => setMenu(null)} onAction={(a) => onThreadAction && onThreadAction(a, t)}/>
        ))}
      </div>
      <div className="ch-rail-foot">
        <div className="ch-avatar" style={{cursor:'pointer'}} onClick={() => onOpenSettings && onOpenSettings('account-profile')} data-tip="계정 · 프로필">{initial}</div>
        <div onClick={() => onOpenSettings && onOpenSettings('account-profile')} style={{cursor:'pointer', minWidth:0, flex:1}}>
          <div className="who" style={{whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{displayName}</div>
          <div className="sub" style={{whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{subline}</div>
        </div>
        {onOpenAdmin && <span className="gear" data-tip="관리자 콘솔" onClick={onOpenAdmin} style={{color:'var(--accent)',fontSize:18,padding:'6px 8px'}}>◈</span>}
        <span className="gear" data-tip={'설정 · ' + window.MOD_KEY + ','} onClick={() => onOpenSettings && onOpenSettings('account-profile')} style={{fontSize:20,padding:'6px 8px'}}>⚙</span>
      </div>
    </aside>
  );
}

function ThreadRow({ t, active, menuOpen, onSelect, onMenu, onCloseMenu, onAction }) {
  return (
    <div className={'ch-thread' + (active ? ' active' : '') + (menuOpen ? ' menu-open' : '')} onClick={onSelect}>
      <div className="t">{t.title}</div>
      <div className="m">{t.model} · {t.time}{t.pinned && <span className="pin-dot" data-tip="Pinned">●</span>}</div>
      <button className="row-more" data-tip="Thread actions" onClick={(e) => { e.stopPropagation(); onMenu(); }}>⋯</button>
      {menuOpen && <PopMenu onClose={onCloseMenu} style={{ position: 'absolute', right: 8, top: 32 }} items={[
        { ic: '✎', label: '이름 변경', kbd: 'F2', onClick: () => onAction('rename') },
        { ic: t.pinned ? '◌' : '★', label: t.pinned ? '고정 해제' : '맨 위로 고정', onClick: () => onAction('pin') },
        { ic: '↗', label: '프로젝트로 이동…', onClick: () => onAction('move') },
        { ic: '⎘', label: '복제', kbd: window.MOD_KEY + 'D', onClick: () => onAction('duplicate') },
        { divider: true },
        { ic: '⤴', label: '공유…', onClick: () => onAction('share') },
        { ic: '↓', label: '내보내기…', onClick: () => onAction('export') },
        { ic: '◫', label: '대화 ID 복사', onClick: () => onAction('copy-id') },
        { divider: true },
        { ic: '▢', label: '보관', onClick: () => onAction('archive') },
        { ic: '🗑', label: '대화 삭제', onClick: () => onAction('delete'), danger: true },
      ]}/>}
    </div>
  );
}

function ChatHeader({ title, model, temp, status, onMenu, onShare, onExport, onMoreAction }) {
  const [moreOpen, setMoreOpen] = React.useState(false);
  const dotColor = status === 'streaming' ? 'var(--accent)'
                 : status === 'ready'     ? 'var(--zg-success)'
                 : status === 'error'     ? 'var(--zg-danger)'
                 : 'var(--fg-5)';
  const tempText = (typeof temp === 'number' ? temp : 0.2).toFixed(2);
  return (
    <div className="ch-header">
      <div className="ch-title">
        {onMenu && (
          <button className="ch-hamburger" onClick={onMenu} aria-label="Open menu" data-tip="Menu">≡</button>
        )}
        <span style={{display:'inline-flex',alignItems:'center',gap:8}}>
          <span style={{width:6,height:6,borderRadius:'50%',background:dotColor,display:'inline-block'}}/>
          {title}
        </span>
        <span className="tag">{model}</span>
        <span className="tag">temp {tempText}</span>
      </div>
      <div className="ch-header-actions">
        <button className="ch-icon-btn" data-tip={'대화 공유 · ' + window.MOD_KEY + window.SHIFT_KEY + 'S'} onClick={onShare}>⤴</button>
        <button className="ch-icon-btn" data-tip="대화 내보내기" onClick={onExport}>↓</button>
        <div style={{ position: 'relative' }}>
          <button className="ch-icon-btn" data-tip="더보기" onClick={() => setMoreOpen(v => !v)}>⋯</button>
          {moreOpen && <PopMenu onClose={() => setMoreOpen(false)} style={{ position: 'absolute', right: 0, top: 36 }} items={[
            { ic: '✎', label: '대화 이름 변경', kbd: 'F2', onClick: () => onMoreAction && onMoreAction('rename') },
            { ic: '★', label: '맨 위로 고정', onClick: () => onMoreAction && onMoreAction('pin') },
            { ic: '↗', label: '프로젝트로 이동…', onClick: () => onMoreAction && onMoreAction('move') },
            { ic: '⎘', label: '복제', kbd: window.MOD_KEY + 'D', onClick: () => onMoreAction && onMoreAction('duplicate') },
            { divider: true },
            { section: '검사' },
            { ic: '⚙', label: '플레이그라운드에서 열기', kbd: window.MOD_KEY + '.', onClick: () => onMoreAction && onMoreAction('playground') },
            { ic: '◫', label: '대화 ID 복사', onClick: () => onMoreAction && onMoreAction('copy-id') },
            { ic: '⛨', label: '인증서 보기', onClick: () => onMoreAction && onMoreAction('cert') },
            { divider: true },
            { ic: '▢', label: '보관', onClick: () => onMoreAction && onMoreAction('archive') },
            { ic: '🗑', label: '대화 삭제', onClick: () => onMoreAction && onMoreAction('delete'), danger: true },
          ]}/>}
        </div>
      </div>
    </div>
  );
}

window.ChatRail = ChatRail;
window.ChatHeader = ChatHeader;
window.PopMenu = PopMenu;
