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 { h } from '@stencil/core';
import { MapToComponentField, VegaSlimmer } from 'vega-slimmer/core';
import { DomNodeSubjectObserverFactory } from '../../../../../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-observer-factory';
import { VegaChange, VegaClick, VegaFocus, VegaPopoverShow, } from '../../../../../../../helpers/event-manager/event-id/vega-event-id';
import { createEnterKeyHandlerToTriggerClick } from '../../../../../../../utils/accessibility';
import { RTE_TABLE_BORDER_STYLES } from '../../../constants/styles.constants';
import { VegaInternalIconManager } from '../../../../../../../helpers/icon/internal-icon-manager';
export class VegaRichTextTablePropertiesBaseFormFieldRenderer extends VegaSlimmer {
  constructor() {
    super(...arguments);
    this.dimensionFieldValidationRule = [
      {
        canEvaluate: (input) => {
          return !!input;
        },
        shouldShowError: () => {
          return true;
        },
        evaluate: (input) => {
          const dimensionRegex = /^[0-9]*\.?[0-9]+(px|em|rem|%)?$/;
          return {
            isValid: dimensionRegex.test(input),
            message: '',
          };
        },
      },
    ];
    /**
     * Emit a change event on each form field value change.
     *
     * @param {HTMLElement} el - The form field element.
     */
    this.handleFormChange = (el) => {
      DomNodeSubjectObserverFactory.addUniqueObserverToNode(el, VegaChange, async (input) => {
        if (this.formRef) {
          const validateResult = await this.formRef.valid();
          if (validateResult.isValid) {
            if (this.renderer.isFormTouched()) {
              const formData = (await this.formRef.getValue());
              const fieldName = el.dataset.vegaForm;
              this.emitFormDataChange(fieldName, formData);
            }
          }
          this.updateBorderDisplayColor(input.host);
          this.updateBackgroundDisplayColor(input.host);
        }
      });
      if (el && el.tagName === 'VEGA-INPUT') {
        DomNodeSubjectObserverFactory.addUniqueObserverToNode(el, VegaFocus, this.markFormTouched);
      }
    };
    /**
     * Emit a change event on each form field value change.
     *
     * @param {string} fieldName - The name of the changed field.
     * @param {RTETablePropertiesType} formData - The current form data.
     */
    this.emitFormDataChange = (_fieldName, formData) => {
      this.vegaChange.emit(formData);
    };
    /**
     * Handle text alignment button click event.
     *
     * @param {MouseEvent} e - The click event.
     */
    this.handleAlignmentButtonClick = async (e) => {
      const button = e.currentTarget;
      const formFieldName = button.dataset.formFieldName;
      if (this.formRef) {
        await this.formRef.setValue({ [formFieldName]: button.dataset.id }, { skipInvisible: false });
      }
    };
    /**
     * Clear border color value and hide the color picker popover.
     *
     * @param {HTMLElement} btn - The clear button element.
     */
    this.clearBorderColor = (btn) => {
      DomNodeSubjectObserverFactory.addUniqueObserverToNode(btn, VegaClick, () => {
        if (this.borderColorPickerRef) {
          this.borderColorPickerRef.value = '';
          if (this.formRef) {
            void this.formRef.setValue({ borderColor: '' });
          }
        }
        if (this.colorPickerPopoverRef) {
          void this.colorPickerPopoverRef.hide();
        }
      });
    };
    /**
     * Apply border color value and hide the color picker popover.
     *
     * @param {HTMLElement} btn - The apply button element.
     */
    this.applyBorderColor = (btn) => {
      DomNodeSubjectObserverFactory.addUniqueObserverToNode(btn, VegaClick, () => {
        if (this.borderColorPickerRef && this.formRef) {
          void this.formRef.setValue({
            borderColor: this.controller.getColorKey(this.borderColorPickerRef.value),
          });
        }
        if (this.colorPickerPopoverRef) {
          void this.colorPickerPopoverRef.hide();
        }
      });
    };
    /**
     * Handle background color picker change event.
     *
     * @param {HTMLElement} el - The background color picker element.
     */
    this.handleBackgroundColorPickerChange = (el) => {
      DomNodeSubjectObserverFactory.addUniqueObserverToNode(el, VegaChange, (input) => {
        const colorValue = input.detail;
        const colorKey = this.controller.getColorKey(colorValue) || colorValue;
        if (this.formRef) {
          void this.formRef.setValue({ backgroundColor: colorKey });
        }
      });
    };
    /**
     * Clear background color value.
     *
     * @param {MouseEvent} event - The mouse event.
     */
    this.clearBackgroundColor = (event) => {
      event.stopPropagation();
      if (this.formRef) {
        void this.formRef.setValue({ backgroundColor: null });
      }
    };
    /**
     * Mark the form as touched.
     */
    this.markFormTouched = () => {
      this.renderer.markFormTouched();
    };
  }
  get formRef() {
    return this.renderer.getFormRef();
  }
  /**
   * Render style border fields.
   *
   * @returns { HTMLElement } The border fields element.
   */
  renderBorderFields() {
    return (h("vega-flex", { gap: "size-16", direction: "row", alignItems: "center" },
      h("vega-input-select", { "data-vega-form": "borderStyle", label: "Border Style", placeholder: "Select style", vegaDropdownProps: { searchable: false, matchTargetWidth: false }, source: VegaRichTextTablePropertiesBaseFormFieldRenderer.TABLE_BORDER_STYLES, ref: this.handleFormChange }),
      h("vega-input", { ref: this.handleFormChange, "data-vega-form": "borderWidth", label: "Weight", validationRules: this.dimensionFieldValidationRule }),
      this.renderBorderColorPicker()));
  }
  /**
   * Render background color picker.
   *
   * @returns {HTMLElement} The background color picker element.
   */
  renderBackgroundColorPicker() {
    return (h("div", { class: "background-color-group" },
      h("vega-font", { class: "field-label", variant: "font-field-label", color: "text-primary" }, "Background Color"),
      h("div", { class: "color-picker-container" },
        h("span", { role: "button", tabIndex: 0, "aria-label": "Clear background color", onClick: this.clearBackgroundColor, onKeyDown: createEnterKeyHandlerToTriggerClick(), class: "color-none" }),
        h("vega-divider", { direction: "vertical" }),
        h("vega-color-picker", { isInline: true, ref: this.handleBackgroundColorPickerChange, colors: this.controller.getColors() }),
        h("vega-input", { ref: this.handleFormChange, type: "hidden", "data-vega-form": "backgroundColor" }))));
  }
  /**
   * Render style dimension fields.
   *
   * @returns { HTMLElement } The dimension fields element.
   */
  renderDimensionFields(withPadding = false) {
    return (h("vega-flex", { gap: "size-16", direction: "row", alignItems: "end" },
      h("vega-input", { ref: this.handleFormChange, "data-vega-form": "width", label: "Width", validationRules: this.dimensionFieldValidationRule }),
      h("vega-input", { ref: this.handleFormChange, "data-vega-form": "height", label: "Height", validationRules: this.dimensionFieldValidationRule }),
      withPadding && (h("vega-input", { ref: this.handleFormChange, "data-vega-form": "padding", label: "Padding", validationRules: this.dimensionFieldValidationRule }))));
  }
  renderAlignmentField(alignmentList, iconPrefix, formFieldName) {
    return (h("vega-flex", { direction: "row", gap: "0", class: "text-alignment-button-group" },
      h("vega-input", { ref: this.handleFormChange, "data-vega-form": formFieldName, type: "hidden" }),
      alignmentList.map((key) => {
        return (h("button", { "data-id": key, "data-form-field-name": formFieldName, class: `text-alignment-${key}`, onClick: this.handleAlignmentButtonClick },
          h("vega-icon", { icon: VegaInternalIconManager.getIconKey(`${iconPrefix}${key}`) })));
      })));
  }
  /**
   * Render save and cancel action buttons.
   *
   * @returns {HTMLElement} The action buttons element.
   */
  renderActionButtons() {
    return (h("div", { class: "action-buttons" },
      h("vega-button-link", { ref: this.handleSave }, "Save"),
      h("vega-button-link", { ref: this.handleCancel }, "Cancel")));
  }
  /**
   * Render border color field color picker.
   *
   * @returns {HTMLElement} The border color picker element.
   */
  renderBorderColorPicker() {
    return (h("div", { class: "color-picker-group" },
      h("vega-font", { class: "field-label", variant: "font-field-label", color: "text-primary" }, "Color"),
      h("vega-popover", { ref: (el) => {
          this.colorPickerPopoverRef = el;
          DomNodeSubjectObserverFactory.addUniqueObserverToNode(el, VegaPopoverShow, async () => {
            if (this.formRef && this.borderColorPickerRef) {
              const formValue = await this.formRef.getValue();
              this.borderColorPickerRef.value = this.controller.getColorByKey(formValue['borderColor']);
            }
          });
        }, trigger: "click" },
        h("div", { slot: "popover-content", class: "color-picker-container" },
          h("vega-input", { ref: this.handleFormChange, "data-vega-form": "borderColor", type: "hidden" }),
          h("span", { role: "button", tabIndex: 0, "aria-label": "Clear border color", onKeyDown: createEnterKeyHandlerToTriggerClick(), class: "display-color-placeholder color-none" })),
        h("vega-box", { slot: "popover" },
          h("vega-color-picker", { ref: (el) => {
              this.borderColorPickerRef = el;
            }, isInline: true, colors: this.controller.getColors() }),
          h("vega-flex", { margin: { top: 'size-16' }, justifyContent: "end", gap: "size-16" },
            h("vega-button-link", { ref: this.clearBorderColor }, "Clear"),
            h("vega-button-link", { ref: this.applyBorderColor }, "Apply"))))));
  }
  /**
   * Update the color display span background color when border color changes.
   *
   * @param {HTMLElement} colorPickerRef - The border color field element.
   */
  updateBorderDisplayColor(colorPickerRef) {
    if (colorPickerRef && colorPickerRef.dataset.vegaForm === 'borderColor') {
      const selectedColorKey = colorPickerRef.value;
      const selectedColor = this.controller.getColorByKey(selectedColorKey);
      const displayColorDiv = colorPickerRef.nextElementSibling;
      displayColorDiv.style.backgroundColor = selectedColor;
      if (selectedColor) {
        displayColorDiv.classList.remove('color-none');
      }
      else {
        displayColorDiv.classList.add('color-none');
      }
      if (this.borderColorPickerRef && selectedColor !== this.borderColorPickerRef.value) {
        this.borderColorPickerRef.value = selectedColor;
      }
    }
  }
  /**
   * Update the background color display when background color changes.
   *
   * @param {HTMLElement} colorInput - The background color field element.
   */
  updateBackgroundDisplayColor(colorInput) {
    if (colorInput && colorInput.dataset.vegaForm === 'backgroundColor') {
      const colorKey = colorInput.value;
      const colorValue = this.controller.getColorByKey(colorKey);
      const colorPicker = colorInput.previousElementSibling;
      colorPicker.value = colorValue;
    }
  }
}
VegaRichTextTablePropertiesBaseFormFieldRenderer.TABLE_BORDER_STYLES = RTE_TABLE_BORDER_STYLES.map((style) => ({
  id: style,
  displayName: style.charAt(0).toUpperCase() + style.slice(1),
}));
__decorate([
  MapToComponentField()
], VegaRichTextTablePropertiesBaseFormFieldRenderer.prototype, "controller", void 0);
__decorate([
  MapToComponentField()
], VegaRichTextTablePropertiesBaseFormFieldRenderer.prototype, "defaultValue", void 0);
__decorate([
  MapToComponentField()
], VegaRichTextTablePropertiesBaseFormFieldRenderer.prototype, "renderer", void 0);
__decorate([
  MapToComponentField()
], VegaRichTextTablePropertiesBaseFormFieldRenderer.prototype, "styleMap", void 0);
__decorate([
  MapToComponentField()
], VegaRichTextTablePropertiesBaseFormFieldRenderer.prototype, "vegaChange", void 0);
__decorate([
  MapToComponentField()
], VegaRichTextTablePropertiesBaseFormFieldRenderer.prototype, "vegaCancel", void 0);
__decorate([
  MapToComponentField()
], VegaRichTextTablePropertiesBaseFormFieldRenderer.prototype, "vegaSave", void 0);
