import { Page, expect } from "@playwright/test";

/**
 * Navigate to the leftovers section (Есть дома)
 *
 * Note: This uses position-based navigation instead of accessible name because
 * immediately after certain operations (like dismissing alerts), the navigation
 * buttons may not be reliably clickable by name. Position-based navigation with
 * force click and animation delay ensures consistent behavior.
 */
export default async function goToLeftovers(page: Page): Promise<void> {
  // Click the leftovers navigation button (3rd button in the nav)
  // The buttons are: Рецепты, Журнал, Есть дома, Покупки, Профиль
  const navigation = page.getByRole("navigation");
  const navButtons = navigation.getByRole("button");
  const leftoverButton = navButtons.nth(2); // 0-indexed, so 2 is the 3rd button (Есть дома)

  // Dismiss any alerts that might be blocking the navigation
  const alert = page.getByRole("alert");
  const alertVisible = await alert.isVisible().catch(() => false);
  if (alertVisible) {
    const closeButton = alert.getByRole("button", { name: "Close" });
    await closeButton.click().catch(() => {});
    await page.waitForTimeout(300);
  }

  // Wait for button to be visible and clickable
  await leftoverButton.waitFor({ state: "visible", timeout: 10000 });
  await page.waitForTimeout(300); // Allow animations to settle
  await leftoverButton.click({ force: true });

  // Wait for navigation to leftovers page
  await page.waitForURL("**/leftovers**", { timeout: 10000 });

  // Optionally verify the page heading is visible
  try {
    await expect(page.getByText("Есть дома")).toBeVisible({ timeout: 5000 });
  } catch (error) {
    // If the heading isn't visible, that's ok - we successfully navigated to the leftovers page
    console.log("Leftovers heading not visible, but navigation successful");
  }
}
