// ─── 탭 작업공간 바 ──────────────────────────────
// 가로 스크롤 탭칩 목록 + [+] 새 탭.
// - 비활성 탭 단탭 → onSwitch(tabId)
// - 활성 탭 단탭   → 인라인 이름 편집(자동 focus). Enter/blur 저장, Esc 취소.
// - × 버튼         → onClose(tabId) 소프트 클로즈. 활성(닫히지 않은) 탭이 1개뿐이면 미표시(C-2).
// - [+]            → onCreate
// 탭바 스크롤 vs 지도 팬 충돌 방지: 루트 touchstart/touchmove stopPropagation (M-5).
//
// 로컬 스타일 상수 (디자인 토큰 준수, appStyles.js 에 추가하지 않음 — 버킷 충돌 방지)
const tabBarStyles = {
  root: {
    display: 'flex', alignItems: 'center', gap: 6,
    overflowX: 'auto', padding: '6px 10px',
    background: '#F6F4EE', borderBottom: '1px solid #E4E2DA',
    flexShrink: 0, scrollbarWidth: 'none', WebkitOverflowScrolling: 'touch',
  },
  rootDisabled: { opacity: 0.5, pointerEvents: 'none' },
  chip: {
    display: 'flex', alignItems: 'center', gap: 4,
    padding: '6px 12px', borderRadius: 10,
    background: '#FFFFFF', border: '1px solid #E4E2DA',
    color: '#1A1814', fontSize: 13, whiteSpace: 'nowrap',
    cursor: 'pointer', flexShrink: 0, userSelect: 'none',
    fontFamily: 'inherit',
  },
  chipActive: {
    background: 'rgba(47,125,79,0.10)', border: '1px solid #2F7D4F',
    color: '#2F7D4F', fontWeight: 700,
  },
  chipEditing: { padding: '4px 6px' },
  chipLabel: { whiteSpace: 'nowrap' },
  chipInput: {
    border: '1px solid #2F7D4F', background: '#FFFFFF',
    borderRadius: 8, padding: '2px 8px', fontSize: 13,
    fontFamily: 'inherit', color: '#1A1814', outline: 'none',
    minWidth: 64, width: 110, boxSizing: 'border-box',
  },
  chipClose: {
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    width: 18, height: 18, padding: 0,
    background: 'transparent', border: 'none', borderRadius: 6,
    color: '#8E8B82', cursor: 'pointer', flexShrink: 0,
  },
  addBtn: {
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    width: 32, height: 32, flexShrink: 0,
    borderRadius: 10, background: '#FFFFFF',
    border: '1px dashed #E4E2DA', color: '#2F7D4F', cursor: 'pointer',
  },
};

function TabBar({
  tabs,
  activeTabId,
  onSwitch,
  onRename,
  onCreate,
  onClose,
  disabled,
}) {
  const [editingId, setEditingId] = useState(null);
  const [editValue, setEditValue] = useState('');
  const inputRef = useRef(null);

  useEffect(() => {
    if (editingId && inputRef.current) {
      inputRef.current.focus();
      inputRef.current.select();
    }
  }, [editingId]);

  // lucide 아이콘 렌더 (탭 추가/삭제 시 새 아이콘 생성)
  useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  });

  const startEdit = (tab) => {
    setEditingId(tab.tab_id);
    setEditValue(tab.name || '');
  };

  const commitEdit = (tab) => {
    if (editingId !== tab.tab_id) return;
    const next = editValue.trim() || tab.name || '새 작업';
    if (next !== tab.name) onRename(tab.tab_id, next);
    setEditingId(null);
  };

  const cancelEdit = () => setEditingId(null);

  const handleChipClick = (tab) => {
    if (disabled) return;
    if (tab.tab_id === activeTabId) {
      startEdit(tab);
    } else {
      onSwitch(tab.tab_id);
    }
  };

  // 활성(닫히지 않은) 탭이 2개 이상일 때만 × 노출 (C-2: 마지막 탭은 닫을 수 없음)
  const canClose = tabs.length > 1;

  const stop = (e) => { e.stopPropagation(); };

  return (
    <div
      style={{ ...tabBarStyles.root, ...(disabled ? tabBarStyles.rootDisabled : {}) }}
      onTouchStart={stop}
      onTouchMove={stop}
    >
      {tabs.map(tab => {
        const active = tab.tab_id === activeTabId;
        const editing = editingId === tab.tab_id;

        if (editing) {
          return (
            <div key={tab.tab_id} style={{ ...tabBarStyles.chip, ...tabBarStyles.chipActive, ...tabBarStyles.chipEditing }}>
              <input
                ref={inputRef}
                value={editValue}
                onChange={(e) => setEditValue(e.target.value)}
                onBlur={() => commitEdit(tab)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') { e.preventDefault(); commitEdit(tab); }
                  if (e.key === 'Escape') { e.preventDefault(); cancelEdit(); }
                }}
                style={tabBarStyles.chipInput}
                maxLength={20}
              />
            </div>
          );
        }

        return (
          <div
            key={tab.tab_id}
            style={{ ...tabBarStyles.chip, ...(active ? tabBarStyles.chipActive : {}) }}
            onClick={() => handleChipClick(tab)}
            role="button"
          >
            <span style={tabBarStyles.chipLabel}>{tab.name || '새 작업'}</span>
            {active && canClose && (
              <button
                style={tabBarStyles.chipClose}
                onClick={(e) => { e.stopPropagation(); onClose(tab.tab_id); }}
                aria-label="작업공간 닫기"
              >
                <i data-lucide="x" style={{ width: 13, height: 13 }}></i>
              </button>
            )}
          </div>
        );
      })}

      <button
        style={tabBarStyles.addBtn}
        onClick={() => { if (!disabled) onCreate(); }}
        aria-label="새 작업공간"
      >
        <i data-lucide="plus" style={{ width: 16, height: 16 }}></i>
      </button>
    </div>
  );
}

window.TabBar = TabBar;
