/*
 * Copyright (c) 2010, 2026 BSI Business Systems Integration AG
 *
 * This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License 2.0
 * which is available at https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 */
import {Action, aria, Device, InitModelOf, ModeModel, tooltips} from '../index';

export class Mode<TRef = any> extends Action implements ModeModel<TRef> {
  declare model: ModeModel<TRef>;

  ref: TRef;

  constructor() {
    super();

    this.selected = false;
    this.ref = null;
    this.preventInitialFocus = false;
  }

  protected override _init(model: InitModelOf<this>) {
    model.owner = model.parent;
    super._init(model);
  }

  protected override _render() {
    super._render();
    this.$container.addClass('button mode')
      .data('mode', this);
  }

  protected override _renderProperties() {
    super._renderProperties();
    this._renderSelected();
  }

  protected override _renderSelected() {
    this.$container.setSelected(this.selected);
    aria.checked(this.$container, this.selected);
  }

  protected override _renderTabbable() {
    // should not lose tab index if disabled
    this.$container.setTabbable(this.tabbable && !Device.get().supportsOnlyTouch());
  }

  override doAction(): boolean {
    if (!this.prepareDoAction()) {
      return false;
    }

    if (!this.selected) {
      this.setSelected(true);
      this.focus();
    }

    return true;
  }

  override toggle() {
    if (!this.selected) {
      this.setSelected(true);
    }
  }

  protected override _renderIconId() {
    super._renderIconId();

    this._updateLabelAndIconStyle();
    // Invalidate layout because mode may now be longer or shorter
    this.invalidateLayoutTree();
  }

  protected override _renderText() {
    super._renderText();
    if (this.$text) {
      tooltips.installForEllipsis(this.$text, {
        parent: this
      });
    }
    this._updateLabelAndIconStyle();
    // Invalidate layout because mode may now be longer or shorter
    this.invalidateLayoutTree();
  }

  protected _updateLabelAndIconStyle() {
    let hasText = !!this.text;
    this.get$Icon().toggleClass('with-label', hasText);
  }

  protected override _renderActionStyle() {
    aria.role(this.$container, 'radio');
  }
}
