import {
  __decorateClass,
  __privateAdd,
  __privateGet,
  __privateMethod,
  __privateSet
} from "../../chunks/chunk.QU3DSPNU.js";
var _form, _formObserver, _GdsFormSummary_instances, getFormControls_fn, getErrorControls_fn, renderArrowIcon_fn;
import { msg, str } from "@lit/localize";
import { nothing } from "lit";
import { property, queryAsync } from "lit/decorators.js";
import { until } from "lit/directives/until.js";
import { when } from "lit/directives/when.js";
import { GdsElement } from "../../gds-element.js";
import { gdsCustomElement, html } from "../../scoping.js";
import { tokens } from "../../tokens.style.js";
import { GdsButton } from "../button/button.component.js";
import { GdsCard } from "../card/card.component.js";
import { GdsDiv } from "../div/div.component.js";
import { GdsFlex } from "../flex/flex.component.js";
import { IconArrowUp } from "../icon/icons/arrow-up.component.js";
import SummaryStyles from "./summary.styles.js";
let GdsFormSummary = class extends GdsElement {
  constructor() {
    super(...arguments);
    __privateAdd(this, _GdsFormSummary_instances);
    this.hideErrors = false;
    this.reactive = false;
    __privateAdd(this, _form);
    __privateAdd(this, _formObserver);
  }
  /**
   * The current number of errors displayed in the summary.
   *
   * This is a convenience property that can be used to display the number of errors in the summary.
   */
  get errorCount() {
    return __privateMethod(this, _GdsFormSummary_instances, getErrorControls_fn).call(this).length;
  }
  /**
   * Focuses the first focusable element in the summary.
   */
  focus(options) {
    this._elRoot.then((el) => {
      const firstFocusable = el.querySelector(
        '[gds-element="gds-button"]'
      );
      if (firstFocusable) {
        firstFocusable.focus(options);
      }
    });
  }
  connectedCallback() {
    super.connectedCallback();
    __privateSet(this, _form, this.closest("form") || void 0);
    if (__privateGet(this, _form) && this.reactive) {
      __privateSet(this, _formObserver, new MutationObserver(() => {
        this.refresh();
      }));
      __privateGet(this, _formObserver).observe(__privateGet(this, _form), {
        attributes: true,
        subtree: true
      });
    }
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    __privateGet(this, _formObserver)?.disconnect();
  }
  /**
   * Refresh the component to reflext the current state of the form.
   */
  refresh() {
    this.requestUpdate();
  }
  render() {
    const formControls = __privateMethod(this, _GdsFormSummary_instances, getFormControls_fn).call(this);
    const errorControls = __privateMethod(this, _GdsFormSummary_instances, getErrorControls_fn).call(this);
    return when(
      errorControls.length > 0,
      () => html`<gds-card
          id="root"
          role="navigation"
          variant="negative"
          padding="l"
          background="negative-01"
          color="negative-01"
          overflow="hidden"
          aria-describedby="description"
          aria-label=${msg(`Form error summary`)}
        >
          <gds-flex gap="0" flex-direction="column">
            <gds-text font="heading-xs" font-weight="book" id="description">
              ${msg(
        str`There are ${errorControls.length} errors to correct before you can continue:`
      )}
            </gds-text>
            <ul>
              ${formControls.map(
        (el, idx) => html`<li ?inert=${!(el.ariaInvalid === "true" || el.invalid)}>
                    <gds-card
                      display="flex"
                      padding="s"
                      flex-direction="row"
                      align-items="center"
                      justify-content="space-between"
                      gap="xs"
                      level="3"
                      color="negative-01"
                      background="transparent; hover: negative-01/.1"
                      style="cursor: pointer"
                      border-width="0"
                      border-radius="xs"
                      margin="0 -xs"
                      @click=${(e) => {
          e.preventDefault();
          el.focus();
        }}
                    >
                      <div id=${`error-label-${idx}`}>
                        <gds-div font-weight="book"
                          >${el.dataset.label || el.label || el.ariaLabel}</gds-div
                        >
                        ${when(
          !this.hideErrors,
          () => html`<gds-div font="body-regular-s">
                              ${el.dataset.errormessage || el.errorMessage || el.ariaErrorMessage}
                            </gds-div>`
        )}
                      </div>
                      <gds-button
                        size="small"
                        variant="negative"
                        label=${`Move focus to ${el.label} field`}
                      >
                        ${until(__privateMethod(this, _GdsFormSummary_instances, renderArrowIcon_fn).call(this, el), nothing)}
                      </gds-button>
                    </gds-card>
                  </li>`
      )}
            </ul>
          </gds-flex>
        </gds-card>`
    );
  }
};
_form = new WeakMap();
_formObserver = new WeakMap();
_GdsFormSummary_instances = new WeakSet();
getFormControls_fn = function() {
  return Array.from(__privateGet(this, _form)?.elements || []).filter(
    // Individual checkboxes can be used as form controls, but they don't support error messages,
    // so we filter them out here. Checkboxes needs to be wrapped in a group to work with form summary.
    (el) => el.gdsElementName !== "gds-checkbox"
  );
};
getErrorControls_fn = function() {
  return __privateMethod(this, _GdsFormSummary_instances, getFormControls_fn).call(this).filter(
    (el) => el.ariaInvalid === "true" || el.invalid
  );
};
renderArrowIcon_fn = async function(el) {
  const selfTop = (await this._elRoot).getBoundingClientRect().top;
  const elTop = el.getBoundingClientRect().top;
  const isAbove = elTop < selfTop;
  return isAbove ? html`<gds-icon-arrow-up></gds-icon-arrow-up>` : html`<gds-icon-arrow-up
          style="transform: rotate(180deg)"
        ></gds-icon-arrow-up>`;
};
GdsFormSummary.styles = [tokens, SummaryStyles];
__decorateClass([
  property({ type: Boolean })
], GdsFormSummary.prototype, "hideErrors", 2);
__decorateClass([
  property({ type: Boolean })
], GdsFormSummary.prototype, "reactive", 2);
__decorateClass([
  queryAsync("#root")
], GdsFormSummary.prototype, "_elRoot", 2);
GdsFormSummary = __decorateClass([
  gdsCustomElement("gds-form-summary", {
    dependsOn: [GdsCard, GdsFlex, GdsDiv, GdsButton, IconArrowUp]
  })
], GdsFormSummary);
export {
  GdsFormSummary
};
