// tests/mobile-admin/offline-queue.spec.ts
import { test, expect } from "@playwright/test";

test.use({ viewport: { width: 390, height: 844 } }); // iPhone 13

test.beforeEach(async ({ page }) => {
  // Sign in as a test admin (requires the seed admin from db/seed.ts).
  await page.goto("/login");
  await page.fill('input[name="email"]', "test-admin@example.com");
  await page.fill('input[name="password"]', "test-password");
  await page.click('button[type="submit"]');
  await page.waitForURL(/\/admin/);
});

test("marking an order ready offline queues and syncs on reconnect", async ({ page, context }) => {
  // Find a "placed" order from the v2 list
  await page.goto("/admin/v2/orders");
  const placedOrderLink = page.locator('a:has(span:has-text("Placed"))').first();
  await placedOrderLink.click();
  await page.waitForURL(/\/admin\/v2\/orders\/[a-f0-9-]+/);

  // Go offline
  await context.setOffline(true);

  // Click "Mark Ready"
  const markReady = page.locator('button:has-text("Mark Ready")');
  await expect(markReady).toBeVisible();
  await markReady.click();

  // Optimistic UI: the page should still update (or the button should disable)
  // and the StickyActionBar should show "Pending sync"
  await expect(page.locator('text="Pending sync"')).toBeVisible({ timeout: 5000 });

  // Reconnect
  await context.setOffline(false);

  // Wait up to 10s for sync
  await expect(page.locator('text="Pending sync"')).toBeHidden({ timeout: 10000 });
});
