import { usePinned } from "../hooks/usePinned";
import { getConfig, text } from "../lib/config";
import { groupStarts, LAYOUT_ROWS, specRows } from "../lib/rows";
import { AddSlot } from "./AddSlot";
import { GroupHeading } from "./GroupHeading";
import { ProductHead } from "./ProductHead";
import { TableFoot } from "./TableFoot";
import { TableRow } from "./TableRow";

/**
 * The comparison table: a header row of products (the base product first),
 * then one row per spec, optionally only the rows that differ and a
 * repeated price/cart footer. On the shopper's own list (`fromList`) the
 * header offers Pin / Remove and an "Add a product" column while there's
 * room. Labels and the header stay visible while scrolling (CSS sticky).
 */
export function CompareTable({
  data,
  layout = "auto",
  onlyDiff = false,
  corner = null,
  fromList = false,
}) {
  const settings = getConfig().table;
  const { pinned, products, pin } = usePinned(data, fromList);
  const keys = data.rows.map((row) => row.key);
  const show = Object.fromEntries(
    LAYOUT_ROWS.map((key) => [key, keys.includes(key)]),
  );
  const rows = specRows(data, onlyDiff);
  const starts = groupStarts(data, rows);
  const sticky = settings.sticky_header !== false;
  const left = fromList
    ? Math.max(
        0,
        (Number(getConfig().limit) || 4) - (data.list_count ?? products.length),
      )
    : 0;
  const classes = [
    "pcfw-table",
    `is-layout-${layout}`,
    settings.sticky_labels !== false && "has-sticky-labels",
    sticky && "has-sticky-header",
  ].filter(Boolean);

  return (
    <div className={`pcfw-table__scroll${sticky ? " is-sticky" : ""}`}>
      <table className={classes.join(" ")}>
        <caption className="pcfw-screen-reader-text">
          {text("caption", "Product comparison")}
        </caption>
        <thead>
          <tr>
            <td className="pcfw-table__corner">{corner}</td>
            {products.map((product) => (
              <ProductHead
                key={product.id}
                product={product}
                show={show}
                pinned={product.id === pinned}
                pinnedLabel={data.pinned_label}
                actions={fromList}
                onPin={pin}
              />
            ))}
            {left > 0 && <AddSlot left={left} />}
          </tr>
        </thead>
        <tbody>
          {rows.map((row) => [
            starts[row.key] && (
              <GroupHeading
                key={`group-${row.key}`}
                group={starts[row.key]}
                colSpan={products.length + 1 + (left > 0 ? 1 : 0)}
              />
            ),
            <TableRow
              key={row.key}
              row={row}
              products={products}
              emptyText={settings.empty_cell_text ?? "—"}
              highlight={!onlyDiff && settings.highlight_differences !== false}
              pad={left > 0}
            />,
          ])}
          {onlyDiff && !rows.length && (
            <tr>
              <td
                className="pcfw-table__none"
                colSpan={products.length + 1 + (left > 0 ? 1 : 0)}
              >
                {text(
                  "noDifferences",
                  "These products don't differ in any row.",
                )}
              </td>
            </tr>
          )}
        </tbody>
        {settings.repeat_price_cart_bottom && (
          <TableFoot data={data} products={products} pad={left > 0} />
        )}
      </table>
    </div>
  );
}
