import { getConfig, text } from "../lib/config";
import { format } from "../lib/format";
import { Slot } from "../lib/slots";
import { CellValue } from "./CellValue";
import { Html } from "./Html";
import { RowTip } from "./RowTip";

/**
 * True when every product has the same value (2+ products). The Cards
 * template keeps one cell per card, so it never merges.
 */
function sameForAll(row, products) {
  if (
    products.length < 2 ||
    row.different ||
    getConfig().template === "cards"
  ) {
    return false;
  }

  const first = (row.cells[products[0].id] || {}).html ?? "";

  return products.every((p) => ((row.cells[p.id] || {}).html ?? "") === first);
}

/**
 * One spec row: the label (with a dot when products differ), then a cell
 * per product, or one merged "Same on all N" cell when they all match.
 * `pad` adds the empty cell under the "Add a product" column.
 */
export function TableRow({ row, products, emptyText, highlight, pad }) {
  const different = highlight && row.different;
  const same = sameForAll(row, products);

  return (
    <tr
      className={`pcfw-table__row pcfw-table__row--${row.key}${different ? " is-different" : ""}`}
    >
      <th scope="row" className="pcfw-table__label">
        {different && <span className="pcfw-table__dot" aria-hidden="true" />}
        <Html html={row.label} />
        {row.tooltip && <RowTip tip={row.tooltip} label={row.label} />}
        {different && (
          <span className="pcfw-screen-reader-text">
            {text("differs", "(differs)")}
          </span>
        )}
      </th>
      {same ? (
        <td
          className="pcfw-table__cell pcfw-table__same"
          colSpan={products.length}
        >
          <CellValue
            cell={row.cells[products[0].id]}
            emptyText={emptyText}
            rowKey={row.key}
          />
          <span className="pcfw-table__same-tag">
            {format(text("sameOnAll", "Same on all %d"), products.length)}
          </span>
        </td>
      ) : (
        products.map((product) => (
          <td key={product.id} className="pcfw-table__cell">
            <CellValue
              cell={row.cells[product.id]}
              emptyText={emptyText}
              rowKey={row.key}
            />
            <Slot name="cellExtras" row={row} productId={product.id} />
          </td>
        ))
      )}
      {pad && <td className="pcfw-table__pad" />}
    </tr>
  );
}
