<template>
  <div id="Chapter1_1" class="content-wrap">
    <div style="margin: 30px 0px 50px; width: 20%">
      <router-link to="/MyPlan.page">
        <div class="logo mb25">
          <img src="../../../../resources/img/logo2.png" alt="" />
        </div>
      </router-link>
    </div>
    <div
      class="title-box mb25 flex align-center mt40"
      style="justify-content: space-between"
    >
      <div>
        <span class="title mr40">1. Hello WORLD</span>
        <span class="subtitle">my name is dd</span>
      </div>
      <button class="completeBtn" @click="complete">학습 종료</button>
    </div>
    <div class="flex justify-between align-center">
      <div class="pre-btn" @click="previousProblem()">
        <img src="../../../../resources/img/left.png" alt="" />
      </div>
      <div class="content title-box">
        <div style="display: flex; justify-content: space-between">
          <p class="title mt25 title-bg">step3 - 놀면서 배우는 영어</p>
          <button id="returnButton" @click="returnPage" style="margin: 4rem">
            <img src="../../../../resources/img/btn_return_50x50.png" alt="" />
            <p>되돌리기</p>
          </button>
        </div>
        <div class="flex align-center mb30">
          <p class="subtitle2 mr20">
            앗! 퍼즐이 망가졌어! 퍼즐을 맞춰 문장을 완성해보자!
          </p>
        </div>

        <div class="text-ct">
          <div class="dropGroup flex align-center justify-center mt30">
            <div style="position: relative">
              <img src="../../../../resources/img/img28_s.png" alt="" />
              <button
                class="dropzone"
                :data-answer="answerArr[0]"
                style="left: 30px; top: 167px"
              >
                <img src="../../../../resources/img/img29_s_01.png" alt="" />
                <p style="font-size: 35px">?</p>
              </button>
              <button
                class="dropzone"
                :data-answer="answerArr[1]"
                style="right: 409px; top: 133px"
              >
                <img src="../../../../resources/img/img30_s_01.png" alt="" />
                <p style="font-size: 35px">?</p>
              </button>
              <button
                class="dropzone"
                :data-answer="answerArr[2]"
                style="right: 46px; top: 128px"
              >
                <img src="../../../../resources/img/img31_s_01.png" alt="" />
                <p style="font-size: 35px">?</p>
              </button>
            </div>
          </div>
          <div class="dragGroup flex justify-center" style="gap: 20px">
            <article style="right: 0; top: 36%">
              <button
                class="draggable"
                :data-text="answerArr[0]"
                draggable="true"
              >
                <img src="../../../../resources/img/img29_s.png" alt="" />
                <p style="font-size: 35px">{{ answerArr[0] }}</p>
              </button>
            </article>
            <article style="left: 0; top: 36%">
              <button
                class="draggable"
                :data-text="answerArr[1]"
                draggable="true"
              >
                <img src="../../../../resources/img/img30_s.png" alt="" />
                <p style="font-size: 35px">{{ answerArr[1] }}</p>
              </button>
            </article>
            <article style="left: 50%; top: 10%">
              <button
                class="draggable"
                :data-text="answerArr[2]"
                draggable="true"
              >
                <img src="../../../../resources/img/img31_s.png" alt="" />
                <p style="font-size: 35px">{{ answerArr[2] }}</p>
              </button>
            </article>
          </div>
        </div>
      </div>
      <div class="next-btn" @click="nextProblem()">
        <img src="../../../../resources/img/right.png" alt="" />
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      draggedElement: null, // 현재 드래그 중인 요소
      prblm_id: [],
      problemData: [],
      answerArr: [],

      // prblmArr: [],
    };
  },
  methods: {
    complete() {
      const { unit_id, book_id } = this.$route.query;
      this.$router.push({
        name: "Dashboard",
        query: { value: 11, unit_id, book_id },
      });
    },
    goToPage(page) {
      this.$router.push({ name: page });
    },
    returnPage() {
      window.location.reload();
    },
    handleDragStart(event) {
      this.draggedElement = event.target; // 드래그한 요소 저장
      event.dataTransfer.setData("text/plain", event.target.dataset.text);
      event.target.style.cursor = "grabbing"; // 드래그 중 커서 변경
    },
    handleDragEnd(event) {
      event.target.style.cursor = "grab"; // 드래그 종료 후 커서 변경
    },
    handleDragOver(event) {
      event.preventDefault(); // 드롭 허용
    },
    handleDrop(event) {
      event.preventDefault();
      const dropZone = event.target.closest("button.dropzone");
      const draggedText = this.draggedElement
        ? this.draggedElement.dataset.text
        : "";

      if (dropZone) {
        const expectedText = dropZone.dataset.answer;
        if (draggedText === expectedText) {
          // 드래그된 텍스트가 정답인 경우
          const rect = dropZone.getBoundingClientRect();
          // 버튼의 이미지 및 텍스트를 드롭존에 맞게 설정
          dropZone.querySelector("p").textContent = draggedText;
          dropZone.querySelector("img").style.display = "none"; // 기존 이미지 숨기기

          // 드래그된 버튼의 이미지와 텍스트를 드롭존에 복사
          const draggedImage = this.draggedElement
            .querySelector("img")
            .cloneNode();
          const draggedTextElement = this.draggedElement
            .querySelector("p")
            .cloneNode();

          // 드롭존에 이미지 및 텍스트를 추가
          dropZone.appendChild(draggedImage);
          dropZone.appendChild(draggedTextElement);

          // 드래그한 요소 숨기기
          this.draggedElement.style.display = "none";
        } else {
          // 정답이 아닌 경우
          alert("오답입니다! 다시 시도해보세요."); // 오답 경고 메시지
        }
      }

      this.draggedElement = null; // 드래그 상태 초기화
    },
    storeProblemId() {
      this.prblm_id = this.$store.getters.currentLearningId;
      console.log("prblm_id", this.prblm_id);
      this.problemData = this.prblm_id;
      // this.fetchProblemData();
    },
    nextProblem() {
      if (
        this.currentProblemIndex <
        this.$store.state.currentLearningIds.length - 1
      ) {
        this.$store.dispatch("goToNextProblem");
        this.handleProblemDetail(this.currentLearningId);
        this.goToPage(this.problemType);
      } else {
        // 마지막 문제면 이동
        this.goToPage("Chapter4");
      }
    },
    previousProblem() {
      if (this.currentProblemIndex > 0) {
        this.$store.dispatch("goToPreviousProblem");
        this.handleProblemDetail(this.currentLearningId);
        this.goToPage(this.problemType);
      }
    },

    handleProblemDetail(item) {
      if (item.prblm_type_id === "prblm_type_001") {
        this.problemType = "Chapter3";
      } else if (item.prblm_type_id === "prblm_type_002") {
        this.problemType = "Chapter3_1";
      } else if (item.prblm_type_id === "prblm_type_003") {
        this.problemType = "Chapter3_2";
      } else if (item.prblm_type_id === "prblm_type_004") {
        this.problemType = "Chapter3_3";
      } else if (item.prblm_type_id === "prblm_type_005") {
        this.problemType = "Chapter3_3_1";
      } else if (item.prblm_type_id === "prblm_type_006") {
        this.problemType = "Chapter3_4";
      } else if (item.prblm_type_id === "prblm_type_007") {
        this.problemType = "Chapter3_5";
      } else if (item.prblm_type_id === "prblm_type_008") {
        this.problemType = "Chapter3_6";
      } else if (item.prblm_type_id === "prblm_type_009") {
        this.problemType = "Chapter3_7";
      } else if (item.prblm_type_id === "prblm_type_010") {
        this.problemType = "Chapter3_8";
      } else if (item.prblm_type_id === "prblm_type_011") {
        this.problemType = "Chapter3_9";
      } else if (item.prblm_type_id === "prblm_type_012") {
        this.problemType = "Chapter3_10";
      } else if (item.prblm_type_id === "prblm_type_013") {
        this.problemType = "Chapter3_11";
      } else if (item.prblm_type_id === "prblm_type_014") {
        this.problemType = "Chapter3_12";
      } else if (item.prblm_type_id === "prblm_type_015") {
        this.problemType = "Chapter3_13";
      } else if (item.prblm_type_id === "prblm_type_016") {
        this.problemType = "Chapter3_14";
      } else if (item.prblm_type_id === "prblm_type_017") {
        this.problemType = "Chapter3_15";
      } else if (item.prblm_type_id === "prblm_type_018") {
        this.problemType = "Chapter2_8";
      } else if (item.prblm_type_id === "prblm_type_019") {
        this.problemType = "Chapter2_7";
      } else if (item.prblm_type_id === "prblm_type_020") {
        this.problemType = "Chapter2_5";
      } else if (item.prblm_type_id === "prblm_type_021") {
        this.problemType = "Chapter2_6";
      } else if (item.prblm_type_id === "prblm_type_022") {
        this.problemType = "Chapter2_10";
      } else if (item.prblm_type_id === "prblm_type_023") {
        this.problemType = "Chapter2_11";
      } else if (item.prblm_type_id === "prblm_type_024") {
        this.problemType = "Chapter2_13";
      }
    },

    fetchProblemData() {
      axios({
        url: "/problem/problemInfo.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: {
          prblmId: this.prblm_id.prblm_id,
        },
      })
        .then((response) => {
          this.problemData = response.data;
          console.log("problemData", this.problemData);
          this.sortingProblem();
        })
        .catch((error) => {
          this.state = "noProblem";
          console.error("Error fetching problemData:", error);
        });
    },

    sortingProblem() {
      let prblmExpln = this.problemData.problem.prblmExpln;
      let prblmArr = prblmExpln.split("/");
      this.answerArr = prblmArr;

      // for (let i = prblmArr.length - 1; i > 0; i--) {
      //   const j = Math.floor(Math.random() * (i + 1));
      //   [prblmArr[i], prblmArr[j]] = [prblmArr[j], prblmArr[i]];
      // }

      // this.prblmArr = prblmArr;
      // console.log(prblmArr);
    },
  },
  computed: {
    currentLearningId() {
      return this.$store.getters.currentLearningId;
    },
    currentLabel() {
      return this.$store.getters.currentLabel;
    },
    currentProblemIndex() {
      return this.$store.getters.currentProblemIndex;
    },
    isPreviousButtonDisabled() {
      return this.currentProblemIndex === 0;
    },
  },
  created() {
    console.log("Current Learning ID:", this.currentLearningId);
    this.prblm_id = this.currentLearningId;
    console.log("Current Label:", this.currentLabel);
    console.log("Current Problem Index:", this.currentProblemIndex);

    // Fetch or process the current problem based on `currentLearningId`
  },
  mounted() {
    this.fetchProblemData();
    // this.storeProblemId();
    // this.storeLearningId();
    this.$route.query;
    // 드래그 가능한 요소에 드래그 시작 및 종료 이벤트 추가
    document.querySelectorAll(".draggable").forEach((button) => {
      button.addEventListener("dragstart", this.handleDragStart);
      button.addEventListener("dragend", this.handleDragEnd);
    });

    // 드롭 가능한 영역에 드래그 오버 및 드롭 이벤트 추가
    document.querySelectorAll(".dropzone").forEach((zone) => {
      zone.addEventListener("dragover", this.handleDragOver);
      zone.addEventListener("drop", this.handleDrop);
    });
  },
};
</script>

<style scoped>
.draggable {
  cursor: grab;
}

.draggable:active {
  cursor: grabbing;
}

.dropzone img {
  display: block;
  /* 이미지가 항상 보이도록 설정 */
}

.completeBtn {
  margin-right: 100px;
  background-color: #ffba08;
  padding: 10px 30px;
  border-radius: 10px;
  font-size: 28px;
  font-family: "ONEMobilePOPOTF";
}
</style>
