import { Page } from "@playwright/test";
import goToJournal from "./goToJournal.ts";

/**
 * Add a recipe to a meal plan through the journal wizard UI
 * Navigates like a real user would - goes to journal and clicks the search icon
 *
 * @param page - Playwright page object
 * @param recipeTitle - Title of the recipe to add
 * @param mealTypeName - Meal type name as displayed in UI (e.g., "Обед", "Завтрак", "Ужин")
 */
export default async function addRecipeToMealPlan(
  page: Page,
  recipeTitle: string,
  mealTypeName: string,
): Promise<void> {
  // Navigate to journal page
  await goToJournal(page);

  // Find the meal type region and click "Add meal" button
  // Uses .first() to get today/future date (past dates show "Log meal" instead)
  const addButton = page
    .getByRole("region", { name: mealTypeName })
    .getByRole("button", { name: /Добавить блюдо/i })
    .first();

  await addButton.scrollIntoViewIfNeeded();
  await addButton.click();

  // Wait for wizard dialog to load and select recipe
  const dialog = page.getByRole("dialog");
  await dialog.waitFor({ state: "visible" });
  await dialog.getByRole("button", { name: recipeTitle }).click();

  // Wait for servings screen and confirm
  await page
    .getByRole("button", { name: "Добавить в план" })
    .waitFor({ state: "visible" });
  await page.getByRole("button", { name: "Добавить в план" }).click();

  // Wait for dialog to close
  await page.getByRole("dialog").waitFor({ state: "hidden" });
}
