const isHexColor = (value) => /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(String(value || "").trim());

export function createColorControl({
  value = "#ffffff",
  previewValue = value,
  ariaLabel = "Выбрать цвет",
  valueLabel = "Значение цвета",
  onChange,
}) {
  const root = document.createElement("div");
  root.className = "env-color-field";

  const swatch = document.createElement("label");
  swatch.className = "env-color-field__swatch";

  const preview = document.createElement("span");
  preview.className = "env-color-field__preview";

  const picker = document.createElement("input");
  picker.type = "color";
  picker.setAttribute("aria-label", ariaLabel);

  const valueWrap = document.createElement("div");
  valueWrap.className = "env-color-field__value";

  const valueInput = document.createElement("input");
  valueInput.type = "text";
  valueInput.setAttribute("aria-label", valueLabel);
  valueWrap.appendChild(valueInput);

  const update = (nextValue, { emit = false } = {}) => {
    const safeValue = String(nextValue ?? "");
    const safePreview = isHexColor(safeValue)
      ? safeValue
      : (isHexColor(previewValue) ? previewValue : "#000000");

    valueInput.value = safeValue;
    picker.value = isHexColor(safeValue) ? safeValue : safePreview;
    preview.style.background = safePreview;

    if (emit && typeof onChange === "function") {
      onChange(safeValue);
    }
  };

  picker.addEventListener("input", () => update(picker.value, { emit: true }));
  valueInput.addEventListener("change", () => update(valueInput.value, { emit: true }));

  swatch.appendChild(preview);
  swatch.appendChild(picker);
  root.appendChild(swatch);
  root.appendChild(valueWrap);

  update(value);

  root.setValue = (nextValue) => update(nextValue);
  root.getValue = () => valueInput.value;

  return root;
}
