// @vitest-environment jsdom
import '../../test/dom-setup';
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SpaceChatTabBar } from './SpaceChatTabBar';

const TABS = [
  { id: 'chat', labelKey: 'tabs.chat' },
  { id: 'overview', labelKey: 'tabs.overview' },
  { id: 'files', labelKey: 'tabs.files' },
];

function renderBar(overrides: Partial<Parameters<typeof SpaceChatTabBar>[0]> = {}) {
  const onSelect = vi.fn();
  const utils = render(
    <SpaceChatTabBar
      tabs={TABS}
      activeTab="chat"
      onSelect={onSelect}
      ariaLabel="チャットタブ"
      renderLabel={(tb) => tb.labelKey}
      appearClass={() => ''}
      actions={<button data-testid="space-chat-delete">del</button>}
      {...overrides}
    />
  );
  return { onSelect, ...utils };
}

describe('SpaceChatTabBar', () => {
  it('タブと actions を描画し、actions はスクロールする tablist の外にある', () => {
    renderBar();
    const tablist = screen.getByRole('tablist');
    const del = screen.getByTestId('space-chat-delete');
    // actions がタブのスクロールコンテナ（tablist）の子孫だと、タブが溢れたとき
    // 一緒にスクロールして画面外に流れる。兄弟であることを構造で保証する。
    expect(tablist.contains(del)).toBe(false);
    expect(screen.getByTestId('space-chat-actions').contains(del)).toBe(true);
    expect(tablist.className).toContain('overflow-x-auto');
  });

  it('ArrowRight で次のタブを選択しフォーカスを移す（末尾で wrap）', async () => {
    const user = userEvent.setup();
    const { onSelect } = renderBar();
    screen.getByRole('tab', { name: 'tabs.chat' }).focus();
    await user.keyboard('{ArrowRight}');
    expect(onSelect).toHaveBeenCalledWith('overview');
  });

  it('End で末尾タブ、Home で先頭タブを選択する', async () => {
    const user = userEvent.setup();
    const { onSelect } = renderBar();
    screen.getByRole('tab', { name: 'tabs.chat' }).focus();
    await user.keyboard('{End}');
    expect(onSelect).toHaveBeenCalledWith('files');
    await user.keyboard('{Home}');
    expect(onSelect).toHaveBeenCalledWith('chat');
  });

  it('aria-selected が activeTab にだけ付く', () => {
    renderBar({ activeTab: 'overview' });
    expect(screen.getByRole('tab', { name: 'tabs.overview' })).toHaveAttribute('aria-selected', 'true');
    expect(screen.getByRole('tab', { name: 'tabs.chat' })).toHaveAttribute('aria-selected', 'false');
  });

  it('actions なしのときアクションゾーンを描画しない', () => {
    renderBar({ actions: undefined });
    expect(screen.queryByTestId('space-chat-actions')).toBeNull();
  });
});
