import { CellValue } from "../components/CellValue";
import { Fragment } from "preact";
import { Html } from "../components/Html";
import { RowTip } from "../components/RowTip";
import { text } from "../lib/config";
import { format } from "../lib/format";
import { Slot } from "../lib/slots";

const norm = (cell) =>
  cell
    ? String(cell.raw || cell.html)
        .trim()
        .toLowerCase()
    : "";

/**
 * Spec rows for the visible products: label on top, one value per column.
 * A row is marked when the visible values differ; values that differ from
 * the base product are bold.
 */
export function CardRows({
  rows,
  starts = {},
  visible,
  base,
  emptyText,
  highlight,
}) {
  return (
    <div className="pcfw-cards__rows">
      {rows.map((row) => {
        const cells = visible.map((p) => row.cells[p.id]);
        const values = cells.map(norm);
        const baseValue = base ? norm(row.cells[base.id]) : null;
        const differs = new Set(values).size > 1;

        const group = starts[row.key];

        return (
          <Fragment key={row.key}>
            {group && (
              <div className="pcfw-cards__group">
                <Html html={group.label} />
                <span className="pcfw-table__group-count">
                  {format(
                    group.count === 1
                      ? text("specsOne", "%d spec")
                      : text("specsMany", "%d specs"),
                    group.count,
                  )}
                </span>
              </div>
            )}
            <div
              className={`pcfw-cards__row${highlight && differs ? " is-different" : ""}`}
            >
              <div className="pcfw-cards__label">
                <Html html={row.label} />
                {row.tooltip && <RowTip tip={row.tooltip} label={row.label} />}
              </div>
              <div className="pcfw-cards__values">
                {cells.map((cell, i) => {
                  const strong =
                    differs && baseValue !== null && values[i] !== baseValue;

                  return (
                    <div
                      key={visible[i].id}
                      className={`pcfw-cards__value${strong ? " is-strong" : ""}`}
                    >
                      <CellValue
                        cell={cell}
                        emptyText={emptyText}
                        rowKey={row.key}
                      />
                      <Slot
                        name="cellExtras"
                        row={row}
                        productId={visible[i].id}
                      />
                    </div>
                  );
                })}
              </div>
            </div>
          </Fragment>
        );
      })}
    </div>
  );
}
