// src/lib/conditional-rule-match.ts
function rowValueForRule(row, rule, columns) {
  const col = columns?.find((c) => c.key === rule.fieldKey);
  const dataKey = col?.sortKey ?? rule.fieldKey;
  return String(row[dataKey] ?? "");
}
function ruleHasActiveValues(rule, columns) {
  if (rule.values.length === 0) return false;
  const col = columns?.find((c) => c.key === rule.fieldKey);
  if (col?.filter?.type === "text")
    return (rule.values[0] ?? "").trim().length > 0;
  return true;
}
function conditionalTextMatches(cellVal, needle, op, textMask) {
  const v = cellVal.trim();
  const n = needle.trim();
  if (!n) return op === "not_contains";
  if (textMask === "phone" || textMask === "zip") {
    const nd = n.replace(/\D/g, "");
    const hay = v.replace(/\D/g, "");
    if (!nd) return op === "not_contains";
    const hit2 = hay.includes(nd);
    return op === "contains" ? hit2 : !hit2;
  }
  const hit = v.toLowerCase().includes(n.toLowerCase());
  return op === "contains" ? hit : !hit;
}
function conditionalRuleMatchesRow(row, rule, columns) {
  if (!ruleHasActiveValues(rule, columns)) return false;
  const v = rowValueForRule(row, rule, columns).trim();
  const col = columns?.find((c) => c.key === rule.fieldKey);
  const textMask = col?.filter?.type === "text" ? col.filter.textMask : void 0;
  switch (rule.operator) {
    case "is":
      return rule.values.includes(v);
    case "is_not":
      return !rule.values.includes(v);
    case "contains":
      return rule.values.some(
        (val) => conditionalTextMatches(v, val, "contains", textMask)
      );
    case "not_contains":
      return !rule.values.some(
        (val) => conditionalTextMatches(v, val, "contains", textMask)
      );
    default:
      return false;
  }
}
function getConditionalRowBackground(row, rules, columns) {
  if (!rules?.length) return void 0;
  for (const rule of rules) {
    if (conditionalRuleMatchesRow(row, rule, columns)) return rule.bgColor;
  }
  return void 0;
}
function getConditionalCellBackground(row, colKey, rules, columns) {
  if (!rules?.length) return void 0;
  const rule = rules.find((r) => r.fieldKey === colKey);
  if (!rule || !conditionalRuleMatchesRow(row, rule, columns)) return void 0;
  return rule.bgColor;
}
export {
  conditionalRuleMatchesRow,
  getConditionalCellBackground,
  getConditionalRowBackground
};
//# sourceMappingURL=conditional-rule-match.js.map