import FieldStyles from "../styles/FieldStyles.wrn"

import ComponentBaseStyles from "../styles/ComponentBaseStyles.wrn"

component RangeSlider {
  outputs {
    input(payload: ({ value: number; name: string; sourceEvent: Event }) | ({ sourceEvent?: Event; value: string | number | boolean | null | object; [key: string]: string | number | boolean | null | object } | string | number | boolean | null | object[]))
    change(payload: ({ value: number; name: string; sourceEvent: Event }) | ({ sourceEvent?: Event; value: string | number | boolean | null | object; [key: string]: string | number | boolean | null | object } | string | number | boolean | null | object[]))
    focus(payload: { sourceEvent?: Event; [key: string]: string | number | boolean | null | object })
    blur(payload: { sourceEvent?: Event; [key: string]: string | number | boolean | null | object })
  }

  props {
    size: string = "default"
    color: string = "primary"
    id: string = ""
    name: string = ""
    label: string = "Range"
    hiddenLabel: boolean = false
    placeholder: string = ""
    variant: string = "normal"
    icon: string = ""
    iconPosition: string = "start"
    value: number = 50
    min: number = 0
    max: number = 100
    step: number = 1
    showValue: boolean = true
    showBounds: boolean = true
    showSteps: boolean = false
    marks: unknown[] = []
    helperText: string = ""
    cornerHint: string = ""
    error: string = ""
    inline: boolean = false
    readonly: boolean = false
    disabled: boolean = false
    required: boolean = false
    class: string = ""
  }
  state currentValue = value
  functions {
    shared function percent() { if (Number(max) === Number(min)) { return 0 } return (Number(currentValue) - Number(min)) / (Number(max) - Number(min)) * 100 }
    client function setValue(nextValue, sourceEvent, commit, detail, root, slider, input, outputElement, progressValue) { if (readonly || disabled) { return } currentValue = Number(nextValue); root = sourceEvent.currentTarget.closest(".wire-next--range-slider"); if (root) { slider = root.querySelector("[role=slider]"); input = root.querySelector("input[name='" + name + "']"); outputElement = root.querySelector("output"); progressValue = (currentValue - Number(min)) / (Number(max) - Number(min)) * 100; if (slider) { slider.setAttribute("aria-valuenow", String(currentValue)); slider.style.setProperty("--wire-range-progress", progressValue + "%") } if (input) { input.value = String(currentValue) } if (outputElement) { outputElement.textContent = String(currentValue) } } detail = { value: currentValue, min: min, max: max, step: step, name: name, sourceEvent: sourceEvent }; output.input(detail); if (commit) { output.change(detail) } }
    client function valueFromPointer(sourceEvent, rect, ratio) { rect = sourceEvent.currentTarget.getBoundingClientRect(); ratio = Math.max(0, Math.min(1, (sourceEvent.clientX - rect.left) / rect.width)); return Number(min) + ratio * (Number(max) - Number(min)) }
    client function beginSlide(sourceEvent, rect, ratio, rawValue) { if (readonly || disabled) { return } sourceEvent.currentTarget.setPointerCapture(sourceEvent.pointerId); rect = sourceEvent.currentTarget.getBoundingClientRect(); ratio = Math.max(0, Math.min(1, (sourceEvent.clientX - rect.left) / rect.width)); rawValue = Number(min) + ratio * (Number(max) - Number(min)); currentValue = Number(min) + Math.round((rawValue - Number(min)) / Number(step)) * Number(step); output.input({ value: currentValue, name: name, sourceEvent: sourceEvent }) }
    client function moveSlide(sourceEvent, rect, ratio, rawValue) { if (!sourceEvent.currentTarget.hasPointerCapture(sourceEvent.pointerId)) { return } rect = sourceEvent.currentTarget.getBoundingClientRect(); ratio = Math.max(0, Math.min(1, (sourceEvent.clientX - rect.left) / rect.width)); rawValue = Number(min) + ratio * (Number(max) - Number(min)); currentValue = Number(min) + Math.round((rawValue - Number(min)) / Number(step)) * Number(step); output.input({ value: currentValue, name: name, sourceEvent: sourceEvent }) }
    client function endSlide(sourceEvent, rect, ratio, rawValue) { rect = sourceEvent.currentTarget.getBoundingClientRect(); ratio = Math.max(0, Math.min(1, (sourceEvent.clientX - rect.left) / rect.width)); rawValue = Number(min) + ratio * (Number(max) - Number(min)); currentValue = Number(min) + Math.round((rawValue - Number(min)) / Number(step)) * Number(step); if (sourceEvent.currentTarget.hasPointerCapture(sourceEvent.pointerId)) { sourceEvent.currentTarget.releasePointerCapture(sourceEvent.pointerId) } output.change({ value: currentValue, name: name, sourceEvent: sourceEvent }) }
    client function selectMark(sourceEvent, root, slider, input, outputElement, nextValue, progressValue, detail) { if (readonly || disabled) { return } root = sourceEvent.currentTarget.closest(".wire-next--range-slider"); slider = root.querySelector(".wire-next__custom-slider"); input = root.querySelector(".wire-next__range-value"); outputElement = root.querySelector("output"); nextValue = Number(sourceEvent.currentTarget.dataset.value); currentValue = nextValue; progressValue = (nextValue - Number(min)) / (Number(max) - Number(min)) * 100; slider.setAttribute("aria-valuenow", String(nextValue)); slider.style.setProperty("--wire-range-progress", progressValue + "%"); input.setAttribute("value", String(nextValue)); outputElement.replaceChildren(String(nextValue)); detail = { value: nextValue, min: min, max: max, step: step, name: name, sourceEvent: sourceEvent }; output.input(detail); output.change(detail) }
    client function handleKey(sourceEvent) { if (sourceEvent.key === "ArrowRight") { sourceEvent.preventDefault(); currentValue = Math.min(Number(max), Number(currentValue) + Number(step)); output.input({ value: currentValue, name: name, sourceEvent: sourceEvent }); output.change({ value: currentValue, name: name, sourceEvent: sourceEvent }) } if (sourceEvent.key === "ArrowLeft") { sourceEvent.preventDefault(); currentValue = Math.max(Number(min), Number(currentValue) - Number(step)); output.input({ value: currentValue, name: name, sourceEvent: sourceEvent }); output.change({ value: currentValue, name: name, sourceEvent: sourceEvent }) } if (sourceEvent.key === "Home") { sourceEvent.preventDefault(); currentValue = Number(min); output.change({ value: currentValue, name: name, sourceEvent: sourceEvent }) } if (sourceEvent.key === "End") { sourceEvent.preventDefault(); currentValue = Number(max); output.change({ value: currentValue, name: name, sourceEvent: sourceEvent }) } }
    client function emitFocus(nameEvent, sourceEvent) { output[nameEvent]({ value: currentValue, name: name, sourceEvent: sourceEvent }) }
    client function decreaseValue(sourceEvent) { currentValue = Math.max(Number(min), Number(currentValue) - Number(step)); output.input({ value: currentValue, name: name, sourceEvent: sourceEvent }); output.change({ value: currentValue, name: name, sourceEvent: sourceEvent }) }
    client function increaseValue(sourceEvent) { currentValue = Math.min(Number(max), Number(currentValue) + Number(step)); output.input({ value: currentValue, name: name, sourceEvent: sourceEvent }); output.change({ value: currentValue, name: name, sourceEvent: sourceEvent }) }
  }
  view {
    <div {...attrs} class="wire-component wire-component--color-{color} wire-component--size-{size} wire-next--field wire-next--range-slider {class}" data-variant="{variant}" data-inline="{inline}" data-invalid="{error ? 'true' : 'false'}">
      <div class="wire-next__field-heading"><label class="{hiddenLabel ? 'wire-next__sr-only' : ''}" for="{id || name}">{label}</label>{#if cornerHint}<span class="wire-next__field-hint">{cornerHint}</span>{/if}</div>
      <div class="wire-next__range-control" data-variant="{variant}" data-icon-position="{iconPosition}" data-show-steps="{showSteps}">
        {#if icon}<span class="{icon}" aria-hidden="true"></span>{/if}
        <button type="button" class="wire-next__range-stepper" aria-label="Decrease {label}" disabled="{disabled || readonly}" @click="decreaseValue(event)">−</button>
        <div class="wire-next__range-track">
          <input id="{id || name}" class="wire-next__sr-only wire-next__range-value" type="number" name="{name}" value="{currentValue}" min="{min}" max="{max}" step="{step}" required="{required}" readonly />
          <div class="wire-next__custom-slider" role="slider" tabindex="{disabled ? '-1' : '0'}" aria-label="{hiddenLabel ? label : ''}" aria-valuemin="{min}" aria-valuemax="{max}" aria-valuenow="{currentValue}" aria-disabled="{disabled}" aria-readonly="{readonly}" aria-invalid="{error ? 'true' : 'false'}" style="--wire-range-progress: {percent()}%" @pointerdown="beginSlide(event)" @pointermove="moveSlide(event)" @pointerup="endSlide(event)" @pointercancel="endSlide(event)" @keydown="handleKey(event)" @focus="emitFocus('focus', event)" @blur="emitFocus('blur', event)">
            <span class="wire-next__slider-fill"></span><span class="wire-next__slider-thumb"></span>
            {#if marks.length}<span class="wire-next__slider-marks">{#each marks as mark}<button type="button" data-value="{mark.value}" style="left: {(Number(mark.value) - Number(min)) / (Number(max) - Number(min)) * 100}%" aria-label="{mark.label}" @click="selectMark(event)"></button>{/each}</span>{/if}
          </div>
          {#if showBounds}<div class="wire-next__range-bounds"><span>{min}</span><span>Step {step}</span><span>{max}</span></div>{/if}
        </div>
        {#if showValue}<output for="{id || name}">{currentValue}</output>{/if}
        <button type="button" class="wire-next__range-stepper" aria-label="Increase {label}" disabled="{disabled || readonly}" @click="increaseValue(event)">+</button>
      </div>
      {#if helperText}<small class="wire-next__field-help">{helperText}</small>{/if}<small class="wire-next__field-error" data-error="{name}">{error}</small>
    </div>
    <FieldStyles hidden />
    <ComponentBaseStyles hidden />
  }

  style {
    .wire-next__range-track {
      display: grid;
      flex: 1;
      min-width: 0;
      gap: 0.35rem;
    }

    .wire-next__range-control input {
      width: 100%;
      min-width: 0;
      margin: 0;
      flex: 1;
      accent-color: var(--wire-field-color);
    }

    .wire-next__custom-slider {
      position: relative;
      width: 100%;
      height: 1.5rem;
      cursor: pointer;
      touch-action: none;
    }

    .wire-next__custom-slider::before,
    .wire-next__slider-fill {
      position: absolute;
      top: 50%;
      height: 0.4rem;
      border-radius: 999px;
      transform: translateY(-50%);
      content: "";
    }

    .wire-next__custom-slider::before {
      right: 0;
      left: 0;
      background: var(--wire-color-surface-2);
      box-shadow: inset 0 0 0 1px var(--wire-color-border);
    }

    .wire-next__slider-fill {
      z-index: 1;
      left: 0;
      width: var(--wire-range-progress);
      background: var(--wire-field-color);
    }

    .wire-next__slider-thumb {
      position: absolute;
      z-index: 3;
      top: 50%;
      left: var(--wire-range-progress);
      width: 1.25rem;
      height: 1.25rem;
      border: 3px solid var(--wire-field-color);
      border-radius: 50%;
      background: var(--wire-color-surface);
      box-shadow: var(--wire-shadow-1);
      transform: translate(-50%, -50%);
    }

    .wire-next__custom-slider:focus-visible {
      outline: 3px solid color-mix(in srgb, var(--wire-field-color) 28%, transparent);
      outline-offset: 3px;
    }

    .wire-next__slider-marks button {
      position: absolute;
      z-index: 2;
      top: 50%;
      width: 0.55rem;
      height: 0.55rem;
      padding: 0;
      border: 2px solid var(--wire-color-surface);
      border-radius: 50%;
      background: var(--wire-color-muted);
      transform: translate(-50%, -50%);
    }

    .wire-next__range-control[data-show-steps="true"] input {
      background-image: repeating-linear-gradient(
        90deg,
        transparent 0,
        transparent calc(10% - 1px),
        var(--wire-color-border) calc(10% - 1px),
        var(--wire-color-border) 10%
      );
    }

    .wire-next__range-bounds {
      display: grid;
      grid-template-columns: 1fr auto 1fr;
      color: var(--wire-color-muted);
      font-size: 0.78em;
      font-variant-numeric: tabular-nums;
    }

    .wire-next__range-bounds span:nth-child(2) {
      text-align: center;
    }

    .wire-next__range-bounds span:last-child {
      text-align: right;
    }

    .wire-next__range-control output {
      min-width: 3ch;
      font-variant-numeric: tabular-nums;
    }

    .wire-next__range-stepper {
      display: inline-grid;
      width: 2.35rem;
      height: 2.35rem;
      flex: 0 0 auto;
      place-items: center;
      border: 1px solid var(--wire-color-border);
      border-radius: 50%;
      background: var(--wire-color-surface);
      color: var(--wire-color-text);
      font: inherit;
      font-size: 1.2rem;
      cursor: pointer;
    }

    .wire-next__range-stepper:hover:not(:disabled) {
      border-color: var(--wire-field-color);
      color: var(--wire-field-color);
    }

    .wire-next__range-stepper:disabled {
      cursor: not-allowed;
      opacity: 0.45;
    }
  }
}
