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

/**
 * Find and select an ingredient from the ingredient search modal
 *
 * @param scope - Page or Locator to scope the search within (e.g., a specific modal)
 * @param ingredientTitle - The ingredient title to search for
 * @param searchKey - Optional search key to use (defaults to ingredientTitle)
 */
export default async function findIngredient(
  scope: Page | Locator,
  ingredientTitle: string,
  searchKey: string = ingredientTitle,
): Promise<void> {
  // Fill the search input
  await scope.getByPlaceholder("Поиск ингредиента...").fill(searchKey);

  // Find the ingredient button within the given scope
  // Note: Multiple matching ingredients may exist if searching in page scope
  // (e.g., in search results and in the recommended ingredients section)
  // Using .first() ensures we always click the first match in the search results
  await scope
    .getByRole("button", {
      name: new RegExp(
        `^(${ingredientTitle}|Новый ингредиент \"${ingredientTitle}\")$`,
      ),
      exact: true,
    })
    .click();
}
