import { scheduleTerminalFits } from '@/components/agent-workspace/terminal-fit';
import { describe, expect, test, vi } from 'vitest';

const flush = async () => {
  await Promise.resolve();
  await Promise.resolve();
};

describe('scheduleTerminalFits', () => {
  test('waits for the first animation frame before font-triggered fits', async () => {
    const fit = vi.fn();
    const sendResize = vi.fn();
    let rafCb: (() => void) | undefined;

    scheduleTerminalFits({
      fit,
      sendResize,
      fontsReady: Promise.resolve(),
      loadNerdFont: () => Promise.resolve(),
      raf: (cb) => {
        rafCb = cb;
      },
      isAborted: () => false,
    });
    await flush();

    expect(fit).not.toHaveBeenCalled();
    expect(sendResize).not.toHaveBeenCalled();

    rafCb?.();
    await flush();

    expect(fit).toHaveBeenCalledTimes(3);
    expect(sendResize).toHaveBeenCalledTimes(3);
  });

  test('fits in rAF and again after fonts.ready and nerd-font load', async () => {
    const fit = vi.fn();
    const sendResize = vi.fn();
    let rafCb: (() => void) | undefined;

    scheduleTerminalFits({
      fit,
      sendResize,
      fontsReady: Promise.resolve(),
      loadNerdFont: () => Promise.resolve(),
      raf: (cb) => {
        rafCb = cb;
      },
      isAborted: () => false,
    });
    rafCb?.();
    await flush();

    expect(fit).toHaveBeenCalledTimes(3);
    expect(sendResize).toHaveBeenCalledTimes(3);
  });

  test('does nothing once aborted', async () => {
    const fit = vi.fn();

    scheduleTerminalFits({
      fit,
      sendResize: vi.fn(),
      fontsReady: Promise.resolve(),
      loadNerdFont: () => Promise.resolve(),
      raf: (cb) => cb(),
      isAborted: () => true,
    });
    await flush();

    expect(fit).not.toHaveBeenCalled();
  });
});
