/**
 * Critical UX fix — delete confirmation is now a branded bottom-sheet, not
 * the native window.confirm(). Long-press on an own upload → Löschen
 * → ConfirmSheet opens. Cancel keeps the post; Confirm removes it.
 *
 * The window.confirm path was jarring on mobile and broke the consistent
 * bottom-sheet design language; the ConfirmSheet uses the same shell as
 * ContextSheet and traps focus while open.
 */
import { test, expect } from '../../fixtures/test';
import { uploadRaw } from '../../helpers/upload-client';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';

const SAMPLE_JPG = join(process.cwd(), 'fixtures', 'media', 'sample.jpg');

async function seedUpload(token: string): Promise<{ id: string }> {
  const res = await uploadRaw(token, readFileSync(SAMPLE_JPG), {
    filename: 'cs.jpg',
    contentType: 'image/jpeg',
    caption: 'Confirm-sheet fixture',
  });
  if (res.status !== 201) throw new Error(`Upload seed failed (${res.status})`);
  return (await res.json()) as { id: string };
}

test.describe('Feed — ConfirmSheet replaces window.confirm for deletion', () => {
  test('Cancel keeps the post; Confirm removes it', async ({ page, guest, signIn }) => {
    const g = await guest('CSDelete');
    await seedUpload(g.jwt);
    await signIn(page, g);
    await page.goto('/feed');

    const card = page.locator('article').filter({ hasText: g.displayName }).first();
    await expect(card).toBeVisible({ timeout: 10_000 });

    // Open the desktop kebab (long-press is exercised in 09-mobile; we want
    // both code paths covered without depending on touch).
    await card.getByRole('button', { name: 'Mehr Aktionen' }).click();

    // Context sheet appears. The Löschen action is wired to set pendingDeleteId,
    // which opens the ConfirmSheet (data-testid="confirm-sheet").
    await page.getByRole('button', { name: /löschen/i }).click();

    const confirmSheet = page.getByTestId('confirm-sheet');
    await expect(confirmSheet).toBeVisible();
    await expect(confirmSheet).toContainText(/beitrag löschen/i);

    // Cancel — sheet closes, post stays.
    await page.getByTestId('confirm-sheet-cancel').click();
    await expect(confirmSheet).not.toBeVisible();
    await expect(card).toBeVisible();

    // Reopen, confirm — post is removed from the DOM.
    await card.getByRole('button', { name: 'Mehr Aktionen' }).click();
    await page.getByRole('button', { name: /löschen/i }).click();
    await expect(page.getByTestId('confirm-sheet')).toBeVisible();
    await page.getByTestId('confirm-sheet-confirm').click();
    await expect(page.getByTestId('confirm-sheet')).not.toBeVisible();
    await expect(card).not.toBeVisible({ timeout: 5_000 });
  });
});
