import { html, nothing } from 'lit';
import { query, state, property, eventOptions } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { live } from 'lit/directives/live.js';
import { boolean } from '../../internal/boolean.mjs';
import { defaultValue } from '../../internal/default-value.mjs';
import { FlowRdfFormControl } from '../../internal/flow-ui-rdf-element.mjs';
import { FormControlController } from '../../internal/form.mjs';
import { clamp } from '../../internal/math.mjs';
import { HasSlotController } from '../../internal/slot.mjs';
import { isNumber } from '../../internal/type-checks.mjs';
import { watch } from '../../internal/watch.mjs';
import { LocalizeController } from '../../utilities/localize.mjs';
import styles from './range.styles.mjs';

var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};
class FlowUiRange extends FlowRdfFormControl {
  constructor() {
    super(...arguments);
    this.formControlController = new FormControlController(this);
    this.hasSlotController = new HasSlotController(this, "help-text", "label", "prefix", "suffix");
    this.localize = new LocalizeController(this);
    this.hasFocus = false;
    this.title = "";
    this.name = "";
    this.value = 0;
    this.size = "medium";
    this.label = "";
    this.helpText = "";
    this.disabled = false;
    this.min = 0;
    this.max = 100;
    this.step = 1;
    this.format = "0";
    this.form = "";
    this.defaultValue = 0;
    this.inline = false;
    this.divider = false;
    this.noInput = false;
  }
  /** Gets the validity state object */
  get validity() {
    return this.input.validity;
  }
  /** Gets the validation message */
  get validationMessage() {
    return this.input.validationMessage;
  }
  connectedCallback() {
    super.connectedCallback();
    this.disabled = boolean(this.disabled, true);
    this.inline = boolean(this.inline, true);
    this.divider = boolean(this.divider, true);
    this.noInput = boolean(this.noInput, true);
    this.resizeObserver = new ResizeObserver(() => this.syncRange());
    if (this.value < this.min) {
      this.value = this.min;
    }
    if (this.value > this.max) {
      this.value = this.max;
    }
    this.updateComplete.then(() => {
      this.syncRange();
      this.resizeObserver.observe(this.input);
    });
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this.resizeObserver.unobserve(this.input);
  }
  handleRangeChange(event) {
    event.stopPropagation();
    this.emit("flow-ui-change");
  }
  handleRangeInput(event) {
    event.stopPropagation();
    this.value = parseFloat(this.input.value);
    this.syncRange();
    this.emit("flow-ui-input");
  }
  /*
    Handler for flow-ui-input & flow-ui-change events from number input.
    Event is propagated out of control.
  */
  handleNumberChange() {
    const value = parseFloat(this.numberInput.value);
    if (isNumber(value)) {
      this.value = parseFloat(this.numberInput.value);
      this.syncRange();
    }
  }
  handleBlur(event) {
    event.stopPropagation();
    this.hasFocus = false;
    this.emit("flow-ui-blur");
  }
  handleFocus(event) {
    event.stopPropagation();
    this.hasFocus = true;
    this.emit("flow-ui-focus");
  }
  handleThumbDragStart() {
  }
  handleThumbDragEnd() {
  }
  syncProgress(percent) {
    this.input.style.setProperty("--percent", `${percent * 100}%`);
  }
  handleValueChange() {
    this.formControlController.updateValidity();
    this.value = clamp(this.value, this.min, this.max);
    this.syncRange();
  }
  handleDisabledChange() {
    this.formControlController.setValidity(this.disabled);
  }
  /** @internal */
  syncRange() {
    const percent = Math.max(0, (this.value - this.min) / (this.max - this.min));
    this.syncProgress(percent);
  }
  handleRangeInvalid(event) {
    this.formControlController.setValidity(false);
    this.formControlController.emitInvalidEvent(event);
  }
  /** Sets focus on the range. */
  focus(options) {
    this.input.focus(options);
  }
  /** Removes focus from the range. */
  blur() {
    this.input.blur();
  }
  /** Increments the value of the range by the value of the step attribute. */
  stepUp() {
    this.input.stepUp();
    if (this.value !== Number(this.input.value)) {
      this.value = Number(this.input.value);
    }
  }
  /** Decrements the value of the range by the value of the step attribute. */
  stepDown() {
    this.input.stepDown();
    if (this.value !== Number(this.input.value)) {
      this.value = Number(this.input.value);
    }
  }
  /** Checks for validity but does not show a validation message. Returns `true` when valid and `false` when invalid. */
  checkValidity() {
    return this.input.checkValidity();
  }
  /** Gets the associated form, if one exists. */
  getForm() {
    return this.formControlController.getForm();
  }
  /** Checks for validity and shows the browser's validation message if the control is invalid. */
  reportValidity() {
    return this.input.reportValidity();
  }
  /** Sets a custom validation message. Pass an empty string to restore validity. */
  setCustomValidity(message) {
    this.input.setCustomValidity(message);
    this.formControlController.updateValidity();
  }
  render() {
    const hasLabelSlot = this.hasSlotController.test("label");
    const hasHelpTextSlot = this.hasSlotController.test("help-text");
    const hasLabel = this.label ? true : !!hasLabelSlot;
    const hasHelpText = this.helpText ? true : !!hasHelpTextSlot;
    return html`
      <div
        part="form-control"
        class=${classMap({
      "form-control": true,
      "form-control--small": this.size === "small",
      "form-control--medium": this.size === "medium",
      "form-control--large": this.size === "large",
      "form-control--inline": this.inline,
      "form-control--disabled": this.disabled,
      "form-control--focused": this.hasFocus,
      "form-control--has-label": hasLabel,
      "form-control--has-help-text": hasHelpText,
      "form-control--has-divider": this.divider,
      "range--has-input": !this.noInput,
      "range--has-prefix": this.hasSlotController.test("prefix"),
      "range--has-suffix": this.hasSlotController.test("suffix")
    })}
      >
        <label
          part="form-control-label"
          class="form-control__label"
          for="input"
          aria-hidden=${hasLabel ? "false" : "true"}
        >
          <slot name="label">${this.label}</slot>
        </label>

        <slot
          name="help-text"
          part="form-control-help-text"
          id="help-text"
          class="form-control__help-text"
          aria-hidden=${hasHelpText ? "false" : "true"}
        >
          ${this.helpText}
        </slot>

        <div part="form-control-input" class="form-control__input">
          <div
            part="base"
            class=${classMap({
      range: true,
      "range--disabled": this.disabled,
      "range--focused": this.hasFocus,
      "range--rtl": this.localize.dir() === "rtl"
    })}
            @mousedown=${this.handleThumbDragStart}
            @mouseup=${this.handleThumbDragEnd}
            @touchstart=${this.handleThumbDragStart}
            @touchend=${this.handleThumbDragEnd}
          >
            <slot name="prefix" part="prefix" class="range__prefix"></slot>
            <input
              part="input"
              id="input"
              class="range__control"
              title=${this.label}
              type="range"
              name=${ifDefined(this.name)}
              ?disabled=${this.disabled}
              min=${ifDefined(this.min)}
              max=${ifDefined(this.max)}
              step=${ifDefined(this.step)}
              .value=${live(this.value.toString())}
              aria-describedby="help-text"
              @change=${this.handleRangeChange}
              @focus=${this.handleFocus}
              @input=${this.handleRangeInput}
              @invalid=${this.handleRangeInvalid}
              @blur=${this.handleBlur}
            />
            <slot name="suffix" part="suffix" class="range__suffix"></slot>

            <flow-ui-input
              class=${classMap({
      "number-input": true,
      "no-input": this.noInput
    })}
              type="number"
              inline
              filled
              exportparts="form-control:number-input"
              no-step-buttons
              size=${this.size}
              format=${this.format}
              min=${ifDefined(this.min)}
              max=${ifDefined(this.max)}
              step=${ifDefined(this.step)}
              ?disabled=${this.disabled}
              .value=${this.value.toString()}
              @flow-ui-change=${this.handleNumberChange}
              @flow-ui-focus=${this.handleFocus}
              @flow-ui-blur=${this.handleBlur}
            ></flow-ui-input>
          </div>
        </div>

        ${this.divider ? this.renderDivider() : nothing}
      </div>
    `;
  }
}
FlowUiRange.styles = styles;
__decorateClass([
  query(".range__control")
], FlowUiRange.prototype, "input", 2);
__decorateClass([
  query(".number-input")
], FlowUiRange.prototype, "numberInput", 2);
__decorateClass([
  state()
], FlowUiRange.prototype, "hasFocus", 2);
__decorateClass([
  property()
], FlowUiRange.prototype, "title", 2);
__decorateClass([
  property()
], FlowUiRange.prototype, "name", 2);
__decorateClass([
  property({ type: Number })
], FlowUiRange.prototype, "value", 2);
__decorateClass([
  property({ reflect: true })
], FlowUiRange.prototype, "size", 2);
__decorateClass([
  property()
], FlowUiRange.prototype, "label", 2);
__decorateClass([
  property({ attribute: "help-text" })
], FlowUiRange.prototype, "helpText", 2);
__decorateClass([
  property({ type: Boolean, reflect: true })
], FlowUiRange.prototype, "disabled", 2);
__decorateClass([
  property({ type: Number })
], FlowUiRange.prototype, "min", 2);
__decorateClass([
  property({ type: Number })
], FlowUiRange.prototype, "max", 2);
__decorateClass([
  property({ type: Number })
], FlowUiRange.prototype, "step", 2);
__decorateClass([
  property()
], FlowUiRange.prototype, "format", 2);
__decorateClass([
  property({ reflect: true })
], FlowUiRange.prototype, "form", 2);
__decorateClass([
  defaultValue()
], FlowUiRange.prototype, "defaultValue", 2);
__decorateClass([
  property({ type: Boolean, reflect: true })
], FlowUiRange.prototype, "inline", 2);
__decorateClass([
  property({ type: Boolean, reflect: true })
], FlowUiRange.prototype, "divider", 2);
__decorateClass([
  property({ type: Boolean, reflect: true, attribute: "no-input" })
], FlowUiRange.prototype, "noInput", 2);
__decorateClass([
  eventOptions({ passive: true })
], FlowUiRange.prototype, "handleThumbDragStart", 1);
__decorateClass([
  watch("value", { waitUntilFirstUpdate: true })
], FlowUiRange.prototype, "handleValueChange", 1);
__decorateClass([
  watch("disabled", { waitUntilFirstUpdate: true })
], FlowUiRange.prototype, "handleDisabledChange", 1);

export { FlowUiRange as default };
