var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { Component, Host, h, Element, Prop, Watch, Event } from '@stencil/core';
import { RequiredFieldRule } from '../../helpers/validator/rules/required-field-rule';
import { createEnterKeyHandlerToTriggerClick } from '../../utils/accessibility';
import { sanitizeVegaComponent } from '../../utils/component';
import { arrayToClassString, getHexFromShorthand, hexToRGB } from '../../utils/ui';
import { FormFieldControllerSlimmer } from '../../helpers/slimmers/form-field-controller-slimmer';
import { InjectVegaGlobalSlimmer, InjectVegaSlimmer, methodPlaceholder, } from 'vega-slimmer/core';
import { FORM_ELEMENT_VALUE_CHANGE } from '../../helpers/change-manager/subject/static-subject/static-subject-title';
import { createEventEmitSlimmer, } from '../../helpers/event-manager/slimmers/event-emit-slimmer';
import ChangeManager from '../../helpers/change-manager/change-manager';
import { VegaChange } from '../../helpers/event-manager/event-id/vega-event-id';
import { VegaComponentUsageRuntimeMetricsSlimmer } from '../../helpers/slimmers/component-usage-runtime-metrics';
import { VegaColorPickerRuntimeMetricsPayloadDefinition } from '../../constants/runtime-metrics-payload-definition/vega-color-picker/runtime-metrics-payload-definition';
/**
 * @vegaVersion 1.13.0
 */
export class VegaColorPicker {
  constructor() {
    this.globalSlimmers = {};
    this.formFieldController = new FormFieldControllerSlimmer({
      propertyRules: [
        {
          propertyName: 'required',
          ruleFactory: (isRequired) => (isRequired ? new RequiredFieldRule() : null),
        },
      ],
      validationRulesName: 'validationRules',
      defaultValue: '',
      attributeGetter: (propertyName) => this[propertyName],
      inputContainerGetter: () => this.colorPickerContainerRef,
      touchableAreaGetter: () => [this.colorPickerTouchableAreaRef],
    });
    this.changeEventEmitter = createEventEmitSlimmer(VegaColorPicker, VegaChange);
    this.vegaComponentUsageRuntimeMetricsSlimmer = new VegaComponentUsageRuntimeMetricsSlimmer(VegaColorPickerRuntimeMetricsPayloadDefinition);
    /**
     * Specifies the initial or preset color value of the color picker.
     *    It is represented as a hexadecimal string.
     *
     * @vegaVersion 1.13.0
     */
    /* eslint-disable-next-line @stencil/strict-mutable */
    this.value = '';
    /**
     * Displays a supplementary prompt message that assists users
     *    in understanding the expected value for the color picker.
     *
     * @vegaVersion 1.13.0
     */
    this.hint = '';
    /**
     * Specifies whether the color picker element is disabled.
     *
     * @vegaVersion 1.13.0
     */
    this.disabled = false;
    /**
     * Specifies whether a color must be selected for
     *    the color picker to pass form validation.
     *
     * @vegaVersion 1.13.0
     */
    this.required = false;
    /**
     * Specifies the label or title for the color picker.
     *
     * It provides descriptive text that helps identify
     *    the purpose or content expected in the color picker.
     *
     * @vegaVersion 1.13.0
     */
    this.label = '';
    /**
     * Specifies the validation status of the color picker component.
     *
     * @vegaVersion 1.13.0
     */
    /* eslint-disable-next-line @stencil/strict-mutable */
    this.isValid = null;
    /**
     * Determines whether automatic validation should be implemented
     *  for the color picker when a color is selected.
     *
     * @vegaVersion 1.13.0
     */
    this.autoValidation = true;
    /**
     * Specifies custom validation rules for the color picker.
     *
     * @vegaVersion 1.13.0
     */
    this.validationRules = [];
    /**
     * Defines custom color options for the color picker.
     *
     * It should be an array of hexadecimal strings representing different colors.
     *
     * @vegaVersion 1.13.0
     */
    this.colors = [
      '#73E6DC',
      '#806BFF',
      '#FFDC83',
      '#FF9571',
      '#00BBFF',
      '#FF82C9',
      '#259F9F',
      '#563D82',
    ];
    /**
     * Specifies whether the color picker is inline with container styles, including a border, background color, and padding.
     *
     * @vegaVersion 2.30.0
     */
    this.isInline = false;
    /**
     * Specifies the maximum number of color swatches displayed per row.
     *
     * When the number of `colors` exceeds `columns`, the remaining swatches
     *    wrap to additional rows. For example, `columns={5}` with 10 colors
     *    renders 2 rows of 5 swatches.
     *
     * Defaults to `8` to preserve the original single-row layout for the
     *    default 8-color palette.
     *
     * @vegaVersion 2.82.0
     */
    this.columns = 8;
    this.renderColorPickerContainer = () => {
      const columns = this.getValidColumns();
      return (h("div", { class: arrayToClassString([!this.isInline ? 'color-picker-inline' : null]), ref: (e) => (this.colorPickerContainerRef = e) },
        h("vega-flex", { direction: "row", gap: "size-8", alignItems: "center", style: { maxWidth: `${columns * 34 - 8}px` } }, this.colors.map((color) => {
          const selected = this.value === color;
          return (h("div", { id: color, class: { 'color-picker-inline-items': true, 'selected': selected }, ref: (e) => (this.colorPickerTouchableAreaRef = e), style: {
              backgroundColor: color,
            }, onClick: this.updateValueProp, role: 'button', tabIndex: 0, "aria-label": "color", onKeyDown: createEnterKeyHandlerToTriggerClick() }, selected ? (h("vega-icon", { icon: "checkmark", size: "size-16", class: {
              'v-text-black': this.isDarkColorCheckmark(this.value),
              'v-text-white': !this.isDarkColorCheckmark(this.value),
            } })) : null));
        }))));
    };
    this.renderHintMessage = () => {
      return h("vega-text", null, this.hint);
    };
    this.updateValueProp = async (e) => {
      if (!this.disabled) {
        this.value = String(e.currentTarget.getAttribute('id'));
      }
    };
  }
  watchValue() {
    this.resetValueIfInvalid();
    this.changeEventEmitter.emit(this.value);
    ChangeManager.notify(FORM_ELEMENT_VALUE_CHANGE, {
      host: this.host,
      detail: this.value,
    });
  }
  watchValidationRules() {
    methodPlaceholder();
  }
  connectedCallback() {
    this.resetValueIfInvalid();
  }
  render() {
    return sanitizeVegaComponent(h(Host, { class: {
        disabled: this.disabled,
      } },
      this.renderLabelDom(),
      this.renderColorPickerContainer(),
      this.hint && this.renderHintMessage()), this.host);
  }
  renderLabelDom() {
    return (h("vega-field-label", { "is-field-required": this.required, disabled: this.disabled, label: this.label }));
  }
  getValidColumns() {
    const flooredColumns = Math.floor(this.columns);
    return Number.isFinite(flooredColumns) && flooredColumns > 0 ? flooredColumns : 1;
  }
  // W3C Recommendations for color contrast rules, please check the following link for more details:
  // https://stackoverflow.com/questions/3942878/how-to-decide-font-color-in-white-or-black-depending-on-background-color
  isDarkColorCheckmark(bgColor, lightColor = '#fcfcfc', darkColor = '#203645') {
    const L = this.getLuminance(bgColor);
    const L1 = this.getLuminance(lightColor);
    const L2 = this.getLuminance(darkColor);
    return L > Math.sqrt((L1 + 0.05) * (L2 + 0.05)) - 0.05;
  }
  getLuminance(hexColor) {
    const r = hexToRGB(hexColor).r; // hexToR
    const g = hexToRGB(hexColor).g; // hexToG
    const b = hexToRGB(hexColor).b; // hexToB
    const colors = [r / 255, g / 255, b / 255];
    const c = colors.map((col) => col <= 0.03928 ? col / 12.92 : ((col + 0.055) / 1.055) ** 2.4);
    return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
  }
  resetValueIfInvalid() {
    const colorExistInList = this.colors.some((color) => {
      return getHexFromShorthand(color).toUpperCase() == getHexFromShorthand(this.value).toUpperCase();
    });
    if (!colorExistInList) {
      this.value = '';
    }
  }
  static get is() { return "vega-color-picker"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["./vega-color-picker.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["vega-color-picker.css"]
  }; }
  static get properties() { return {
    "value": {
      "type": "string",
      "mutable": true,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "name": "vegaVersion",
            "text": "1.13.0"
          }],
        "text": "Specifies the initial or preset color value of the color picker.\n   It is represented as a hexadecimal string."
      },
      "attribute": "value",
      "reflect": true,
      "defaultValue": "''"
    },
    "hint": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "name": "vegaVersion",
            "text": "1.13.0"
          }],
        "text": "Displays a supplementary prompt message that assists users\n   in understanding the expected value for the color picker."
      },
      "attribute": "hint",
      "reflect": false,
      "defaultValue": "''"
    },
    "disabled": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "name": "vegaVersion",
            "text": "1.13.0"
          }],
        "text": "Specifies whether the color picker element is disabled."
      },
      "attribute": "disabled",
      "reflect": true,
      "defaultValue": "false"
    },
    "required": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "name": "vegaVersion",
            "text": "1.13.0"
          }],
        "text": "Specifies whether a color must be selected for\n   the color picker to pass form validation."
      },
      "attribute": "required",
      "reflect": true,
      "defaultValue": "false"
    },
    "label": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "name": "vegaVersion",
            "text": "1.13.0"
          }],
        "text": "Specifies the label or title for the color picker.\n\nIt provides descriptive text that helps identify\n   the purpose or content expected in the color picker."
      },
      "attribute": "label",
      "reflect": false,
      "defaultValue": "''"
    },
    "isValid": {
      "type": "boolean",
      "mutable": true,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "name": "vegaVersion",
            "text": "1.13.0"
          }],
        "text": "Specifies the validation status of the color picker component."
      },
      "attribute": "is-valid",
      "reflect": true,
      "defaultValue": "null"
    },
    "autoValidation": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "name": "vegaVersion",
            "text": "1.13.0"
          }],
        "text": "Determines whether automatic validation should be implemented\n for the color picker when a color is selected."
      },
      "attribute": "auto-validation",
      "reflect": true,
      "defaultValue": "true"
    },
    "validationRules": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "FormFieldValidationRule<unknown>[]",
        "resolved": "FormFieldValidationRule<unknown>[]",
        "references": {
          "FormFieldValidationRule": {
            "location": "import",
            "path": "../../helpers/validator/rules/form-field-validation-rule"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "name": "vegaVersion",
            "text": "1.13.0"
          }],
        "text": "Specifies custom validation rules for the color picker."
      },
      "defaultValue": "[]"
    },
    "colors": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "string[]",
        "resolved": "string[]",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "name": "vegaVersion",
            "text": "1.13.0"
          }],
        "text": "Defines custom color options for the color picker.\n\nIt should be an array of hexadecimal strings representing different colors."
      },
      "defaultValue": "[\n\t\t'#73E6DC',\n\t\t'#806BFF',\n\t\t'#FFDC83',\n\t\t'#FF9571',\n\t\t'#00BBFF',\n\t\t'#FF82C9',\n\t\t'#259F9F',\n\t\t'#563D82',\n\t]"
    },
    "isInline": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "name": "vegaVersion",
            "text": "2.30.0"
          }],
        "text": "Specifies whether the color picker is inline with container styles, including a border, background color, and padding."
      },
      "attribute": "is-inline",
      "reflect": false,
      "defaultValue": "false"
    },
    "columns": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "name": "vegaVersion",
            "text": "2.82.0"
          }],
        "text": "Specifies the maximum number of color swatches displayed per row.\n\nWhen the number of `colors` exceeds `columns`, the remaining swatches\n   wrap to additional rows. For example, `columns={5}` with 10 colors\n   renders 2 rows of 5 swatches.\n\nDefaults to `8` to preserve the original single-row layout for the\n   default 8-color palette."
      },
      "attribute": "columns",
      "reflect": false,
      "defaultValue": "8"
    }
  }; }
  static get events() { return [{
      "method": "vegaChange",
      "name": "vegaChange",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [{
            "name": "vegaVersion",
            "text": "1.13.0"
          }],
        "text": "An event emitter notifying changes in the value of the color picker,\n   whether triggered programmatically or through user interaction."
      },
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      }
    }, {
      "method": "change",
      "name": "change",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [{
            "name": "eventSemantics",
            "text": "namespace:native"
          }, {
            "name": "vegaVersion",
            "text": "2.0.0"
          }],
        "text": "An event emitter notifying changes in the value of the color picker,\n   whether triggered programmatically or through user interaction."
      },
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      }
    }]; }
  static get elementRef() { return "host"; }
  static get watchers() { return [{
      "propName": "value",
      "methodName": "watchValue"
    }, {
      "propName": "validationRules",
      "methodName": "watchValidationRules"
    }]; }
}
__decorate([
  InjectVegaGlobalSlimmer()
], VegaColorPicker.prototype, "globalSlimmers", void 0);
__decorate([
  InjectVegaSlimmer()
], VegaColorPicker.prototype, "formFieldController", void 0);
__decorate([
  InjectVegaSlimmer()
], VegaColorPicker.prototype, "changeEventEmitter", void 0);
__decorate([
  InjectVegaSlimmer()
], VegaColorPicker.prototype, "vegaComponentUsageRuntimeMetricsSlimmer", void 0);
