import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { dialog } from '@ablogcms/dialog';
import AdminNewCard from './admin-new-card';

vi.mock('@ablogcms/dialog', () => ({
  dialog: {
    confirm: vi.fn(),
    alert: vi.fn(),
  },
}));

// Button コンポーネント化後も acms-admin-btn 系クラスと onClick の挙動が変わっていないことを固定する
describe('AdminNewCard', () => {
  it('キャンセルボタンは acms-admin-btn acms-admin-btn-text を持ち、クリックで onCancel を呼ぶ', () => {
    const onCancel = vi.fn();
    render(<AdminNewCard laneId="LANE1" onAdd={vi.fn()} onCancel={onCancel} />);

    const cancelButton = screen.getByRole('button', { name: 'admin_menu.cancel' });
    expect(cancelButton).toHaveClass('acms-admin-btn', 'acms-admin-btn-text');

    fireEvent.click(cancelButton);
    expect(onCancel).toHaveBeenCalledTimes(1);
  });

  it('追加ボタンは acms-admin-btn acms-admin-btn-success を持つ', () => {
    render(<AdminNewCard laneId="LANE1" onAdd={vi.fn()} onCancel={vi.fn()} />);

    const addButton = screen.getByRole('button', { name: 'admin_menu.add' });
    expect(addButton).toHaveClass('acms-admin-btn', 'acms-admin-btn-success');
  });

  it('title のみ入力（url 未入力）で追加ボタンを押すと onAdd を呼ばずアラートを出す', async () => {
    const onAdd = vi.fn();
    render(<AdminNewCard laneId="LANE1" onAdd={onAdd} onCancel={vi.fn()} />);

    fireEvent.change(screen.getByLabelText('admin_menu.add_title'), { target: { value: 'タイトル' } });
    fireEvent.click(screen.getByRole('button', { name: 'admin_menu.add' }));

    expect(onAdd).not.toHaveBeenCalled();
    await waitFor(() => expect(dialog.alert).toHaveBeenCalledWith('admin_menu.card_add_alert'));
  });

  it('title/url を入力してから追加ボタンを押すと onAdd に入力内容を渡す', () => {
    const onAdd = vi.fn();
    render(<AdminNewCard laneId="LANE1" onAdd={onAdd} onCancel={vi.fn()} />);

    fireEvent.change(screen.getByLabelText('admin_menu.add_title'), { target: { value: 'タイトル' } });
    fireEvent.change(screen.getByLabelText('admin_menu.url'), { target: { value: 'https://example.com' } });
    fireEvent.click(screen.getByRole('button', { name: 'admin_menu.add' }));

    expect(onAdd).toHaveBeenCalledTimes(1);
    expect(onAdd).toHaveBeenCalledWith(expect.objectContaining({ title: 'タイトル', url: 'https://example.com' }));
  });
});
