import type { RecipeSummaryView } from "@batch-cooking/shared";
import { useTranslation } from "react-i18next";
import { AllergenBadges } from "./badges/AllergenBadges";
import { DietBadges } from "./badges/DietBadges";
import "./recipes.scss";

/**
 * Left-aligned catalog table — photo / name / allergens-intolerances /
 * associated regime, one row per recipe. Replaces the earlier card grid
 * (`RecipeCard`, removed): clicking a row selects it (`onSelect`) rather
 * than navigating to a separate page — the detail renders alongside, in
 * `RecipeDetailPanel` (see `RecipesPage`'s master-detail layout).
 */
export function RecipeTable({
  recipes,
  selectedId,
  onSelect,
}: {
  recipes: RecipeSummaryView[];
  selectedId: number | null;
  onSelect: (id: number) => void;
}) {
  const { t } = useTranslation();

  return (
    <div className="recipe-table-wrap">
      <table className="recipe-table">
        <thead>
          <tr>
            <th />
            <th>{t("recipes.table.name")}</th>
            <th>{t("recipes.table.allergens")}</th>
            <th>{t("recipes.table.diets")}</th>
          </tr>
        </thead>
        <tbody>
          {recipes.map((recipe) => (
            <tr
              key={recipe.id}
              className={recipe.id === selectedId ? "selected" : undefined}
              onClick={() => onSelect(recipe.id)}
              onKeyDown={(e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  onSelect(recipe.id);
                }
              }}
              tabIndex={0}
              aria-current={recipe.id === selectedId ? "true" : undefined}
            >
              <td>
                <span className="recipe-table__photo" aria-hidden="true">
                  {recipe.picture ? <img src={recipe.picture} alt="" /> : "🍽️"}
                </span>
              </td>
              <td className="recipe-table__name">
                {recipe.name}
                {recipe.isFavorite && (
                  <span className="recipe-table__fav-mark" aria-hidden="true">
                    ★
                  </span>
                )}
              </td>
              <td>
                {recipe.allergens.length > 0 ? (
                  <AllergenBadges allergens={recipe.allergens} />
                ) : (
                  <span className="recipe-table__muted">—</span>
                )}
              </td>
              <td>
                {recipe.diets.length > 0 ? (
                  <DietBadges diets={recipe.diets} />
                ) : (
                  <span className="recipe-table__muted">—</span>
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
