import type { ProductDetailProductBase } from "@/lib/product-detail/types";

type ProductAttributes = ProductDetailProductBase["attributes"];

type ProductDetailAttributesSectionProps = {
  attributes?: ProductAttributes | null;
};

const ATTRIBUTE_LABELS: Record<keyof NonNullable<ProductAttributes>, string> = {
  petSize: "Pet size",
  ageRange: "Age range",
  specialDiet: "Special diet",
  material: "Material",
  flavor: "Flavor",
};

function formatAttributeValue(
  value: string | string[] | undefined,
): string | null {
  if (value == null) return null;
  if (Array.isArray(value)) {
    const filtered = value.filter((v) => v != null && String(v).trim() !== "");
    return filtered.length === 0 ? null : filtered.join(", ");
  }
  const s = String(value).trim();
  return s === "" ? null : s;
}

/**
 * Attributes/specs section for PDP tabs.
 * Uses <table> with <caption> and <th scope="row"> per SEO rule.
 * Renders inside a parent <section> provided by ProductDetailTabsSection.
 */
export function ProductDetailAttributesSection({
  attributes,
}: ProductDetailAttributesSectionProps) {
  if (!attributes) {
    return (
      <p className="text-sm text-[var(--muted)]">
        No product details available.
      </p>
    );
  }

  const entries: Array<{
    key: keyof NonNullable<ProductAttributes>;
    label: string;
    value: string;
  }> = [];
  for (const key of Object.keys(ATTRIBUTE_LABELS) as Array<
    keyof NonNullable<ProductAttributes>
  >) {
    const value = formatAttributeValue(attributes[key]);
    if (value != null) {
      entries.push({ key, label: ATTRIBUTE_LABELS[key], value });
    }
  }

  if (entries.length === 0) {
    return (
      <p className="text-sm text-[var(--muted)]">
        No product details available.
      </p>
    );
  }

  return (
    <table className="w-full max-w-xl text-sm">
      <caption className="sr-only">Product specifications</caption>
      <tbody>
        {entries.map(({ key, label, value }) => (
          <tr
            key={key}
            className="border-b border-[var(--separator)] last:border-b-0"
          >
            <th
              scope="row"
              className="w-1/3 py-3 pr-4 text-left font-medium text-[var(--muted)]"
            >
              {label}
            </th>
            <td className="py-3 text-[var(--foreground)]">{value}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}
