/**
 * Copyright 2024
 * @license Apache-2.0, see License.md for full text.
 */
import{html as t,css as e}from"../../lit/index.js";import{QuestionElement as s}from"../multiple-choice/lib/QuestionElement.js";import"../simple-icon/lib/simple-icon-button-lite.js";class MatchingQuestion extends s{static get tag(){return"matching-question"}static get styles(){return[super.styles,e`
        :host {
          display: block;
        }

        simple-icon-button-lite {
          right: 0;
          top: 0;
          display: block;
          position: absolute;
          padding: var(--ddd-spacing-2);
        }
        label {
          margin-top: var(--ddd-spacing-6);
          margin-bottom: var(--ddd-spacing-4);
          display: block;
        }

        #target-container {
          transition: all 0.3s ease-in-out;
          justify-content: center;
          overflow-y: auto;
          background-color: light-dark(
            var(--simple-colors-default-theme-grey-2),
            var(--simple-colors-default-theme-grey-10)
          );
        }

        .target {
          height: 100px;
          padding: 4px;
          font-weight: var(--ddd-font-weight-bold);
        }
        .match {
          min-height: 100px;
          padding: 4px;
        }

        .tag-option {
          margin: 4px;
        }

        #matches-container {
          transition: all 0.3s ease-in-out;
          justify-content: center;
          overflow-y: auto;
          background-color: light-dark(
            var(--simple-colors-default-theme-grey-2),
            var(--simple-colors-default-theme-grey-10)
          );
        }

        #possible-container {
          display: flex;
          justify-content: start;
          padding: var(--ddd-spacing-3);
          border: var(--ddd-border-xs);
          flex-wrap: wrap;
          justify-content: center;
          gap: var(--ddd-spacing-4);
          min-height: var(--ddd-spacing-12);
        }

        :host([show-answer]) .tag-option {
          cursor: unset;
        }

        :host(:not([show-answer])) .tag-option:hover,
        :host(:not([show-answer])) .tag-option:focus {
          background-color: var(--simple-colors-default-theme-grey-3);
        }

        :host([show-answer]) .tag-option {
          cursor: unset;
        }

        :host([dragging]) .match,
        :host([dragging]) #possible-container {
          border: var(--ddd-border-md);
          border-style: dashed;
        }
        :host([drag-enter][dragging]) #possible-container.drag-enter,
        :host([drag-enter][dragging]) .drag-enter {
          border-style: dashed;
          border-color: black;
          background-color: light-dark(
            var(--simple-colors-default-theme-grey-3),
            var(--simple-colors-default-theme-grey-9)
          );
        }

        .tag-option {
          font-size: var(--ddd-font-size-s);
          height: fit-content;
          display: inline-block;
          font-family: var(--ddd-font-navigation);
          padding: var(--ddd-spacing-2) var(--ddd-spacing-3);
          border: var(--ddd-border-sm);
          border-radius: var(--ddd-radius-sm);
          background-color: var(--simple-colors-default-theme-grey-2);
          cursor: pointer;
          user-select: none;
          transition: background-color 0.3s ease;
        }
        table {
          width: 100%;
          border: var(--ddd-border-sm);
        }
        td,
        th {
          padding: var(--ddd-spacing-2);
          border: var(--ddd-border-sm);
          margin: 0;
          width: 50%;
        }
        tr {
          margin: 0;
          border: var(--ddd-border-sm);
        }
      `]}constructor(){super(),this.guessDataValue="matchAnswers",this.__activeOption={},this.dragEnter=!1,this.dragging=!1,this.matchAnswers=[],this.matchTarget=!1}processInput(t,e,s){let r=super.processInput(t,e);if(!1===r.correct){r.matchOption=!0;for(let t=s.length;t>=0;t--)!r.match&&s[t]&&!0===s[t].target&&(r.match=s[t].order)}else r.target=!0;return r}cleanAnswerData(t){this.matchAnswers=[],this.showAnswer=!1;let e=[];for(let s in t){let r={...this.answerPrototype(),...t[s]};r.order=parseInt(s),r.match=!1,r.matchOption=!1,r.target=!1,e.push({...this.cleanAnswerDataBeforeSend(r,parseInt(s),e)})}return e}cleanAnswerDataBeforeSend(t,e,s){if(!1===t.correct){t.matchOption=!0;for(let r=e;r>=0;r--)!t.match&&s[r]&&!0===s[r].target&&(t.match=s[r].order)}else t.target=!0;return t}resetAnswer(){if(this.showAnswer=!1,globalThis.dispatchEvent(new CustomEvent("simple-toast-hide",{bubbles:!0,composed:!0,cancelable:!1,detail:!1})),this.isCorrect()){this.displayedAnswers=[],this.matchAnswers=[];const t=JSON.parse(JSON.stringify(this.answers));this.answers=[...t]}setTimeout((()=>{this.requestUpdate()}),0)}isCorrect(){let t=!0;for(var e=0;e<this.matchAnswers.length;e++)this.matchAnswers[e].guess!==this.matchAnswers[e].match?(t=!1,this.matchAnswers[e].correct=!1):this.matchAnswers[e].correct=!0;for(e=0;e<this.displayedAnswers.length;e++)this.displayedAnswers[e].match&&(t=!1);return t}renderInteraction(){return t` <dialog id="selecttarget">
        <simple-icon-button-lite
          icon="close"
          @click="${()=>{this.shadowRoot.querySelector("dialog").close()}}"
          >Close</simple-icon-button-lite
        >
        <label>Match <em>${this.__activeOption.label}</em> to:</label>
        <select @change="${this.selectTargetChange}" autofocus>
          <option value="">-- Possible options --</option>
          ${this.answers.filter((t=>t.target)).map((e=>t`<option value="${e.order}">${e.label}</option>`))}
        </select>
      </dialog>
      <div class="option-container">
        <table class="top">
          <thead>
            <th>Target</th>
            <th>Match</th>
          </thead>
          <tbody>
            ${this.answers.filter((t=>t.target)).map((e=>t`
                  <tr class="matches-container">
                    ${this.matchTarget?t` <td
                          class="target"
                          id="target-${e.order}"
                          @drop="${this.handleDrop}"
                          @dragleave="${this.dragTargetLeave}"
                          @dragover="${this.dragTargetOver}"
                        >
                          ${this.matchAnswers.filter((t=>t.guess===e.order)).map((e=>t`
                                ${this.renderOption(e,"target")}
                              `))}
                        </td>`:t`<td class="target">${e.label}</td>`}
                    <td
                      class="match"
                      id="match-${e.order}"
                      @drop="${this.handleDrop}"
                      @dragleave="${this.dragTargetLeave}"
                      @dragover="${this.dragTargetOver}"
                    >
                      ${this.matchAnswers.filter((t=>t.guess===e.order)).map((e=>t`
                            ${this.renderOption(e,"match")}
                          `))}
                    </td>
                  </tr>
                `))}
          </tbody>
        </table>
        <div
          id="possible-container"
          class="possible"
          @drop="${this.handleDrop}"
          @dragover="${this.dragTargetOver}"
          @dragleave="${this.dragTargetLeave}"
        >
          ${this.displayedAnswers.filter((t=>!!this.matchTarget||t.matchOption)).map((e=>t`
                ${this.renderOption(e,"possible")}
              `))}
        </div>
      </div>`}renderOption(e,s){return t`<button
      ?disabled="${this.disabled||this.showAnswer}"
      class="tag-option ${"possible"!=s&&this.showAnswer?e.correct?"correct":"incorrect":""}"
      draggable="${this.showAnswer?"false":"true"}"
      @dragstart="${this.handleDrag}"
      @dragend="${this.handleDragEnd}"
      data-label="${e.label}"
      @click="${()=>this.handleTagClick(e)}"
    >
      ${e.label}
    </button>`}handleDrag(t){const e=t.target.textContent.trim();t.dataTransfer.setData("text/plain",e),this.dragging=!0}handleDragEnd(t){const e=t.target.textContent.trim();t.dataTransfer.setData("text/plain",e),this.dragging=!1,this.dragEnter=!1}dragTargetOver(t){t.preventDefault(),t.target.classList.add("drag-enter"),this.dragEnter=!0}dragTargetLeave(t){t.preventDefault(),t.target.classList.remove("drag-enter")}handleDrop(t){t.preventDefault(),this.dragging=!1,this.dragEnter=!1;let e=Array.from(this.shadowRoot.querySelectorAll(".drag-enter"));for(var s in e)e[s].classList.remove("drag-enter");const r=t.dataTransfer.getData("text/plain");let a,i,o=this.answers.find((t=>t.label===r)),n=t.target;if("BUTTON"===n.tagName&&(n=n.parentNode),n&&n.getAttribute&&n.getAttribute("id")){switch(n.getAttribute("id").split("-")[0]){case"possible":o.guess=null,i=this.displayedAnswers.findIndex((t=>t.label===r)),i>-1&&this.displayedAnswers.splice(i,1),i=this.matchAnswers.findIndex((t=>t.label===r)),i>-1&&this.matchAnswers.splice(i,1),this.displayedAnswers.push(JSON.parse(JSON.stringify(o)));break;case"match":a=n.getAttribute("id").split("-")[1],o.guess=parseInt(a),i=this.displayedAnswers.findIndex((t=>t.label===r)),i>-1&&this.displayedAnswers.splice(i,1),i=this.matchAnswers.findIndex((t=>t.label===r)),i>-1&&this.matchAnswers.splice(i,1),this.matchAnswers.push(JSON.parse(JSON.stringify(o)))}this.requestUpdate(),setTimeout((()=>{this.focusActive(o)}),0)}}renderDirections(){return t`<p>
      Select all that apply. When you are done, press
      <strong>${this.t.checkAnswer}</strong>. You will get feedback indicating
      correctness of your answer and how to proceed.
    </p>`}focusActive(t){this.shadowRoot.querySelector(`button[data-label="${t.label}"]`).focus()}handleTagClick(t){let e=0;this.__activeOption={...t};let s=Array.from(this.shadowRoot.querySelectorAll("dialog option"));for(var r in s)parseInt(s[r].value)===t.guess&&(e=r);this.shadowRoot.querySelector("dialog select").selectedIndex=e,this.shadowRoot.querySelector("dialog").showModal()}selectTargetChange(t){let e=parseInt(t.target.value);this.__activeOption.guess=e;let s=this.matchAnswers.findIndex((t=>t.order===this.__activeOption.order));s>-1&&this.matchAnswers.splice(s,1),s=this.displayedAnswers.findIndex((t=>t.order===this.__activeOption.order)),s>-1&&this.displayedAnswers.splice(s,1),""===t.target.value?(this.__activeOption.guess=null,this.displayedAnswers.push(JSON.parse(JSON.stringify(this.__activeOption)))):this.matchAnswers.push(JSON.parse(JSON.stringify(this.__activeOption))),this.shadowRoot.querySelector("dialog select").selectedIndex=0,this.shadowRoot.querySelector("dialog").close(),this.requestUpdate(),setTimeout((()=>{this.focusActive(this.__activeOption),this.__activeOption={guess:null}}),0)}static get properties(){return{...super.properties,dragging:{type:Boolean,reflect:!0},dragEnter:{type:Boolean,reflect:!0,attribute:"drag-enter"},matchTarget:{type:Boolean,reflect:!0,attribute:"match-target"},matchAnswers:{type:Array},__activeOption:{type:Object}}}static get haxProperties(){return new URL(`./lib/${this.tag}.haxProperties.json`,import.meta.url).href}}globalThis.customElements.define(MatchingQuestion.tag,MatchingQuestion);export{MatchingQuestion};