import { expect, test } from '@playwright/test';

const TOLERANCE_PX = 4;
/** h-4 w-4 swatch size in Tailwind default scale */
const SWATCH_PX = 16;

function overlap(aStart: number, aEnd: number, bStart: number, bEnd: number): number {
  return Math.min(aEnd, bEnd) - Math.max(aStart, bStart);
}

test.describe('PalettePicker container-query layout', () => {
  test('narrow container (320px) — option list and preview card stack vertically', async ({ page }) => {
    await page.goto('/palette-picker?w=320');

    const container = page.getByTestId('palette-picker-container');
    const list = page.getByRole('radiogroup', { name: 'Palette options' });
    const card = page.getByTestId('palette-preview');

    await expect(container).toHaveCSS('width', '320px');
    await expect(list).toBeVisible();
    await expect(card).toBeVisible();

    const listBox = await list.boundingBox();
    const cardBox = await card.boundingBox();
    expect(listBox).not.toBeNull();
    expect(cardBox).not.toBeNull();

    // Stacked: preview sits at or below the list block (vertical flow).
    expect(cardBox!.y).toBeGreaterThanOrEqual(listBox!.y + listBox!.height - TOLERANCE_PX);

    // Overlapping x bands (same column, not side-by-side).
    const xOverlap = overlap(
      listBox!.x,
      listBox!.x + listBox!.width,
      cardBox!.x,
      cardBox!.x + cardBox!.width,
    );
    expect(xOverlap).toBeGreaterThan(0);
  });

  test('wide container (640px) — option list and preview card sit side-by-side', async ({ page }) => {
    await page.goto('/palette-picker?w=640');

    const container = page.getByTestId('palette-picker-container');
    const list = page.getByRole('radiogroup', { name: 'Palette options' });
    const card = page.getByTestId('palette-preview');

    await expect(container).toHaveCSS('width', '640px');
    await expect(list).toBeVisible();
    await expect(card).toBeVisible();

    const listBox = await list.boundingBox();
    const cardBox = await card.boundingBox();
    expect(listBox).not.toBeNull();
    expect(cardBox).not.toBeNull();

    // Side-by-side: horizontal separation exceeds one swatch width.
    expect(Math.abs(cardBox!.x - listBox!.x)).toBeGreaterThan(SWATCH_PX);

    // Overlapping y bands (same row, not stacked).
    const yOverlap = overlap(
      listBox!.y,
      listBox!.y + listBox!.height,
      cardBox!.y,
      cardBox!.y + cardBox!.height,
    );
    expect(yOverlap).toBeGreaterThan(0);
  });
});
