import { unsafeCSS, LitElement, nothing, html } from "lit";
import { property, state } from "lit/decorators.js";
import { customElement } from "../../decorator.js";
import componentStyle from "./keyboard-numeric.css.js";
import "../icon-button/icon-button.js";
import "../../icons/icon-close-google.js";
import "../../icons/icon-backspace-google.js";
import "../button/button.js";
import "../../icons/icon-up-iec.js";
import "../../icons/icon-down-iec.js";
import "../../icons/icon-multiply.js";
import "../../icons/icon-divide.js";
import "../../icons/icon-equal.js";
import { ObcNumberInputFieldTextAlign, ObcNumberInputFieldSize } from "../number-input-field/number-input-field.js";
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;
};
var ObcKeyboardNumericType = /* @__PURE__ */ ((ObcKeyboardNumericType2) => {
  ObcKeyboardNumericType2["Floating"] = "floating";
  ObcKeyboardNumericType2["Flat"] = "flat";
  return ObcKeyboardNumericType2;
})(ObcKeyboardNumericType || {});
var ObcKeyboardNumericContent = /* @__PURE__ */ ((ObcKeyboardNumericContent2) => {
  ObcKeyboardNumericContent2["Numbers"] = "numbers";
  ObcKeyboardNumericContent2["Symbols"] = "symbols";
  return ObcKeyboardNumericContent2;
})(ObcKeyboardNumericContent || {});
const NUMBER_KEYS = [
  ["1", "2", "3"],
  ["4", "5", "6"],
  ["7", "8", "9"],
  ["–", "0", ","]
];
const SYMBOL_KEYS = [
  ["!", "@", "#"],
  ["$", "%", "&"],
  ["(", ")", "/"],
  ["–", "0", ","]
];
const ALLOWED_CHARS = [
  "0",
  "1",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
  "–",
  "-",
  ",",
  ".",
  "+",
  "×",
  "÷",
  "=",
  "!",
  "@",
  "#",
  "$",
  "%",
  "&",
  "(",
  ")",
  "/"
];
const OPERATORS = ["+", "-", "–", "×", "÷", "*", "/"];
let ObcKeyboardNumeric = class extends LitElement {
  constructor() {
    super(...arguments);
    this.type = "floating";
    this.hasTitleBar = false;
    this.label = "Parameter name";
    this.value = "";
    this.hasCalculation = false;
    this.has2Symbols = false;
    this.helperText = "";
    this.hasLeadingIcon = false;
    this.unit = "";
    this.inputFieldTextAlign = ObcNumberInputFieldTextAlign.Right;
    this.validationPattern = "";
    this.content = "numbers";
  }
  /** Validates if a character can be added to the current value */
  canAddCharacter(char) {
    const potentialValue = this.value + char;
    if (this.validationPattern) {
      const regex = new RegExp(this.validationPattern);
      return regex.test(potentialValue);
    }
    if (!ALLOWED_CHARS.includes(char)) {
      return false;
    }
    const lastChar = this.value.slice(-1);
    if (char === "," || char === ".") {
      const segments = this.value.split(/[+\-–×÷*/]/);
      const currentSegment = segments[segments.length - 1] || "";
      return !currentSegment.includes(",") && !currentSegment.includes(".");
    }
    if (char === "–" || char === "-" || char === "+") {
      return this.value === "" || this.value === "0" || OPERATORS.includes(lastChar);
    }
    return true;
  }
  /** Validates that all characters in a value are allowed */
  isValidValue(value) {
    return [...value].every((char) => ALLOWED_CHARS.includes(char));
  }
  handleCloseClick() {
    this.dispatchEvent(
      new CustomEvent("close-click", { bubbles: true, composed: true })
    );
  }
  handleKeyPress(key) {
    if (this.canAddCharacter(key)) {
      if ((key === "–" || key === "-" || key === "+") && (this.value === "" || this.value === "0")) {
        this.value = key;
      } else {
        this.value += key;
      }
      this.dispatchValueChange();
    }
  }
  handleCalculationKey(key) {
    if (key === "=") {
      this.evaluateExpression();
    } else {
      this.value += key;
      this.dispatchValueChange();
    }
  }
  evaluateExpression() {
    if (!this.value) return;
    try {
      const expression = this.value.replace(/×/g, "*").replace(/÷/g, "/").replace(/–/g, "-").replace(/,/g, ".");
      if (!/^[\d+\-*/().]+$/.test(expression)) {
        return;
      }
      const result = new Function(`return (${expression})`)();
      if (typeof result === "number" && isFinite(result)) {
        const rounded = Math.round(result * 1e6) / 1e6;
        this.value = String(rounded).replace(".", ",");
        this.dispatchValueChange();
      }
    } catch {
    }
  }
  handleBackspace() {
    if (this.value.length > 0) {
      this.value = this.value.slice(0, -1);
      this.dispatchValueChange();
    }
  }
  handleClear() {
    this.value = "";
    this.dispatchValueChange();
  }
  handleToggleContent() {
    this.content = this.content === "numbers" ? "symbols" : "numbers";
  }
  handleDone() {
    this.evaluateExpression();
    this.dispatchEvent(
      new CustomEvent("done-click", {
        detail: { value: this.value },
        bubbles: true,
        composed: true
      })
    );
  }
  dispatchValueChange() {
    this.dispatchEvent(
      new CustomEvent("value-change", {
        detail: { value: this.value },
        bubbles: true,
        composed: true
      })
    );
  }
  handleInputChange(e) {
    const input = e.target;
    const newValue = input.value;
    if (this.validationPattern && newValue) {
      const regex = new RegExp(this.validationPattern);
      if (!regex.test(newValue)) {
        input.value = this.value;
        return;
      }
    }
    if (newValue && !this.isValidValue(newValue)) {
      input.value = this.value;
      return;
    }
    this.value = newValue;
    this.dispatchValueChange();
  }
  handleInputKeydown(e) {
    if (e.key === "Enter") {
      e.preventDefault();
      this.handleDone();
    } else if (e.key === "Escape") {
      e.preventDefault();
      this.handleCloseClick();
    }
  }
  renderCalculationRow() {
    if (!this.hasCalculation) return nothing;
    return html`
      <div class="calculation-container">
        <obc-icon-button
          class="calculation-button"
          @click=${() => this.handleCalculationKey("+")}
        >
          <obi-up-iec></obi-up-iec>
        </obc-icon-button>
        <obc-icon-button
          class="calculation-button"
          @click=${() => this.handleCalculationKey("-")}
        >
          <obi-down-iec></obi-down-iec>
        </obc-icon-button>
        <obc-icon-button
          class="calculation-button"
          @click=${() => this.handleCalculationKey("×")}
        >
          <obi-multiply></obi-multiply>
        </obc-icon-button>
        <obc-icon-button
          class="calculation-button"
          @click=${() => this.handleCalculationKey("÷")}
        >
          <obi-divide></obi-divide>
        </obc-icon-button>
        <obc-icon-button
          class="calculation-button"
          @click=${() => this.handleCalculationKey("=")}
        >
          <obi-equal></obi-equal>
        </obc-icon-button>
      </div>
    `;
  }
  renderKeyboard() {
    const keys = this.content === "numbers" ? NUMBER_KEYS : SYMBOL_KEYS;
    return html`
      <div class="keys-container">
        ${keys.map(
      (row) => html`
            <div class="row">
              ${row.map(
        (key) => html`
                  <obc-button
                    class="key-button"
                    variant="normal"
                    @click=${() => this.handleKeyPress(key)}
                  >
                    ${key}
                  </obc-button>
                `
      )}
            </div>
          `
    )}
      </div>
    `;
  }
  renderInputField() {
    return html`
      <obc-number-input-field
        class="input-field"
        .value=${this.value}
        .unit=${this.unit}
        .textAlign=${this.inputFieldTextAlign}
        .size=${ObcNumberInputFieldSize.Large}
        .helperText=${this.helperText}
        ?hasLeadingIcon=${this.hasLeadingIcon}
        placeholder="00.0"
        @input=${this.handleInputChange}
        @keydown=${this.handleInputKeydown}
      >
        <slot name="leading-icon" slot="leading-icon"></slot>
      </obc-number-input-field>
    `;
  }
  render() {
    const showTitleBar = this.hasTitleBar && this.type === "floating";
    return html`
      <div class="wrapper type-${this.type}">
        ${showTitleBar ? html`
              <div class="top-bar">
                <div class="parameter-name">${this.label}</div>
                <obc-icon-button variant="flat" @click=${this.handleCloseClick}>
                  <obi-close-google></obi-close-google>
                </obc-icon-button>
              </div>
            ` : nothing}

        <div class="container-content">
          ${this.renderInputField()}

          <div class="key-container">
            ${this.renderCalculationRow()}

            <div class="input-container">
              ${this.renderKeyboard()}

              <div class="action-container">
                <div class="function-buttons-container">
                  <obc-button
                    class="action-button"
                    @click=${this.handleBackspace}
                    showLeadingIcon
                  >
                    <obi-backspace-google
                      slot="leading-icon"
                    ></obi-backspace-google
                    >DEL
                  </obc-button>
                  <obc-button
                    class="action-button clear"
                    @click=${this.handleClear}
                  >
                    CLEAR
                  </obc-button>
                  ${this.has2Symbols ? html`
                        <obc-button
                          class="action-button symbols"
                          variant="normal"
                          @click=${this.handleToggleContent}
                        >
                          ${this.content === "numbers" ? "#+=" : "123"}
                        </obc-button>
                      ` : nothing}
                </div>
                <obc-button
                  class="action-button done"
                  variant="raised"
                  @click=${this.handleDone}
                >
                  DONE
                </obc-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    `;
  }
};
ObcKeyboardNumeric.styles = unsafeCSS(componentStyle);
__decorateClass([
  property({ type: String })
], ObcKeyboardNumeric.prototype, "type", 2);
__decorateClass([
  property({ type: Boolean })
], ObcKeyboardNumeric.prototype, "hasTitleBar", 2);
__decorateClass([
  property({ type: String })
], ObcKeyboardNumeric.prototype, "label", 2);
__decorateClass([
  property({ type: String })
], ObcKeyboardNumeric.prototype, "value", 2);
__decorateClass([
  property({ type: Boolean })
], ObcKeyboardNumeric.prototype, "hasCalculation", 2);
__decorateClass([
  property({ type: Boolean })
], ObcKeyboardNumeric.prototype, "has2Symbols", 2);
__decorateClass([
  property({ type: String })
], ObcKeyboardNumeric.prototype, "helperText", 2);
__decorateClass([
  property({ type: Boolean })
], ObcKeyboardNumeric.prototype, "hasLeadingIcon", 2);
__decorateClass([
  property({ type: String })
], ObcKeyboardNumeric.prototype, "unit", 2);
__decorateClass([
  property({ type: String })
], ObcKeyboardNumeric.prototype, "inputFieldTextAlign", 2);
__decorateClass([
  property({ type: String })
], ObcKeyboardNumeric.prototype, "validationPattern", 2);
__decorateClass([
  state()
], ObcKeyboardNumeric.prototype, "content", 2);
ObcKeyboardNumeric = __decorateClass([
  customElement("obc-keyboard-numeric")
], ObcKeyboardNumeric);
export {
  ObcKeyboardNumeric,
  ObcKeyboardNumericContent,
  ObcKeyboardNumericType
};
//# sourceMappingURL=keyboard-numeric.js.map
