"use client";

import { useTranslations } from "next-intl";

type Step = {
  id: string;
  instruction: string;
  appliesTo: string[];
};

function sectionLabel(appliesTo: string[], prepLabel: string): string {
  return appliesTo.length === 0 ? prepLabel : appliesTo.join(" + ");
}

export function BatchCookSteps({ steps }: { steps: Step[] }) {
  const t = useTranslations("recipe");
  const prepLabel = t("batchCookPrep");

  const groups: Array<{ label: string; steps: Step[] }> = [];
  for (const step of steps) {
    const label = sectionLabel(step.appliesTo, prepLabel);
    const last = groups[groups.length - 1];
    if (last && last.label === label) last.steps.push(step);
    else groups.push({ label, steps: [step] });
  }

  let stepNumber = 0;

  return (
    <div className="space-y-8">
      {groups.map((group, gi) => (
        <div key={gi} className="space-y-4">
          <h3 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
            {group.label}
          </h3>
          <ol className="space-y-6">
            {group.steps.map((step) => {
              stepNumber += 1;
              return (
                <li key={step.id} className="flex gap-4">
                  <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-bold">
                    {stepNumber}
                  </div>
                  <p className="flex-1 leading-relaxed pt-1">{step.instruction}</p>
                </li>
              );
            })}
          </ol>
        </div>
      ))}
    </div>
  );
}
