import type { CookingTaskIngredientView, CookingTaskView } from "@batch-cooking/shared";

/**
 * Minimal shape of `react-i18next`'s `t` — just what this module needs.
 * Passed in rather than importing `useTranslation` here so these helpers
 * stay pure functions the page (and a unit test) can call without mounting
 * i18next, the same "logic extracted from the .tsx" split as
 * `shopping-list.ts`'s `groupShoppingListItems`.
 */
export type TranslateFn = (key: string, options?: Record<string, unknown>) => string;

/**
 * Formats a task quantity for display — French conventions, at most 2
 * decimals so a scaled/pooled float never shows a trailing-digit artifact
 * (`"149.99999999999997"`). Same rule as `shopping-list.ts`'s
 * `formatShoppingListQuantity`.
 */
export function formatCookingQuantity(quantity: number): string {
  return quantity.toLocaleString("fr-FR", { maximumFractionDigits: 2 });
}

/**
 * One ingredient line as a human string — `"3 oignon"`, `"200 g farine"`,
 * or just `"sel"` when the source clause carried no measurable amount
 * (`quantity`/`unit` both `null`, see {@link CookingTaskIngredientView}).
 * Labels are resolved through the same `catalog.*` i18n keys as everywhere
 * else.
 */
export function formatIngredientLine(line: CookingTaskIngredientView, t: TranslateFn): string {
  const name = t(`catalog.ingredients.${line.ingredient.key}`);
  if (line.quantity === null) return name;
  const amount = formatCookingQuantity(line.quantity);
  const unit = line.unit === null ? "" : `${t(`catalog.units.${line.unit.key}`)} `;
  return `${amount} ${unit}${name}`.trim();
}

/**
 * The headline shown on a task card:
 * - `merged-prep` — `"Émincer : 3 oignon, 200 g carotte"` (technique label +
 *   its pooled ingredient lines), built from the
 *   `cookingSession.task.mergedPrepLabel` template.
 * - `step` — the original recipe step text, verbatim.
 */
export function taskHeadline(task: CookingTaskView, t: TranslateFn): string {
  if (task.kind === "step") return task.description ?? "";
  const technique = task.technique
    ? t(`catalog.techSteps.${task.technique.key}`)
    : t("cookingSession.phase.mise-en-place");
  const items = task.ingredients.map((line) => formatIngredientLine(line, t)).join(", ");
  return t("cookingSession.task.mergedPrepLabel", { technique, items });
}

/** Comma-joined names of the recipes a task belongs to — one for a `step`, several for a pooled `merged-prep`. */
export function taskRecipeNames(task: CookingTaskView): string {
  return task.sourceRecipes.map((recipe) => recipe.name).join(", ");
}
