export function createSliderControl({
  label = "",
  value = 0,
  min = 0,
  max = 100,
  step = 1,
  className = "",
  showValue = false,
  formatValue = (val) => String(val),
  onChange
}) {
  const row = document.createElement("div");
  row.className = ["slider-row", className].filter(Boolean).join(" ");

  const lbl = document.createElement("label");
  lbl.textContent = label;
  lbl.className = "slider-label";

  const input = document.createElement("input");
  input.type = "range";
  input.className = "slider-input";
  input.min = min;
  input.max = max;
  input.step = step;
  input.value = value;

  const valueEl = document.createElement("div");
  valueEl.className = "slider-value";

  const fillText = document.createElement("span");
  fillText.className = "slider-fill-text";
  fillText.setAttribute("aria-hidden", "true");

  const fillLabel = document.createElement("span");
  fillLabel.textContent = label;
  fillLabel.className = "slider-label";

  const fillValue = document.createElement("span");
  fillValue.className = "slider-value";
  fillText.appendChild(fillLabel);
  fillText.appendChild(fillValue);

  const updateFill = () => {
    const range = Number(input.max) - Number(input.min);
    const percent = range
      ? Math.max(0, Math.min(100, ((Number(input.value) - Number(input.min)) / range) * 100))
      : 0;
    row.style.setProperty("--slider-percent", `${percent}%`);
    input.style.setProperty("--slider-percent", `${percent}%`);
    if (showValue) {
      const formattedValue = formatValue(Number(input.value));
      valueEl.textContent = formattedValue;
      fillValue.textContent = formattedValue;
    }
  };

  input.addEventListener("input", () => {
    updateFill();
    const v = Number(input.value);
    onChange?.(v);
  });

  updateFill();

  row.appendChild(lbl);
  row.appendChild(input);
  if (showValue) {
    row.appendChild(valueEl);
    row.appendChild(fillText);
  }
  row.setValue = (nextValue) => {
    input.value = nextValue;
    updateFill();
  };
  row.getValue = () => Number(input.value);
  return row;
}
