import { text } from "../lib/config";
import { plainText } from "../lib/plain";
import { Html } from "./Html";
import { CheckIcon, DashIcon } from "./icons";
import { slot } from "../lib/slots";

/** "yes" / "no" for cells that say just Yes or No (English or translated). */
function answer(cell) {
  const value = plainText(String(cell.raw ?? cell.html))
    .trim()
    .toLowerCase();

  if (value === "yes" || value === text("yes", "Yes").toLowerCase()) {
    return "yes";
  }

  if (value === "no" || value === text("no", "No").toLowerCase()) {
    return "no";
  }

  return "";
}

/**
 * One cell's content: the PHP-escaped HTML, or the empty placeholder.
 * Yes / No values get a check or a dash in front; the stock row gets a
 * status icon when Stock display (Pro) asks for one.
 */
export function CellValue({ cell, emptyText, rowKey }) {
  if (!cell || cell.html.trim() === "") {
    return <span className="pcfw-table__empty">{emptyText}</span>;
  }

  const Stock = rowKey === "stock" && slot("stock");

  if (Stock) {
    return <Stock status={cell.raw} html={cell.html} />;
  }

  const kind = answer(cell);

  if (!kind) {
    return <Html html={cell.html} />;
  }

  return (
    <span className={`pcfw-table__answer is-${kind}`}>
      <span className="pcfw-table__answer-icon">
        {kind === "yes" ? <CheckIcon /> : <DashIcon />}
      </span>
      <Html html={cell.html} />
    </span>
  );
}
