export function sanitizeDecimalInput(rawValue) {
  if (!rawValue) return "";
  const cleaned = rawValue.replace(/[^\d,.]/g, "");
  let separatorIdx = -1;
  let result = "";
  for (let i = 0; i < cleaned.length; i++) {
    if (cleaned[i] === "," || cleaned[i] === ".") {
      if (separatorIdx === -1) {
        separatorIdx = result.length;
        result += cleaned[i];
      }
    } else {
      result += cleaned[i];
    }
  }
  return result;
}

export function parseGermanDecimal(value) {
  if (value === "" || value == null) return null;
  const trimmed = String(value).trim();
  if (!trimmed) return null;
  const normalized = trimmed.replace(",", ".");
  if (!/^\d+(\.\d+)?$/.test(normalized)) return null;
  return Number(normalized);
}

export function formatGermanDecimal(value, { fractionDigits } = {}) {
  if (value == null) return "";
  const str = fractionDigits != null ? Number(value).toFixed(fractionDigits) : String(value);
  return str.replace(".", ",");
}
