<template>

<div class="connect-container">
    <!-- 왼쪽: 한자 (HanziWriter) -->
    <div class="connect-column left" :style="getColumnStyle">
      <div
        class="connect-item hanzi"
        v-for="(hanzi, i) in characters"
        :key="'h' + i"
        :class="{ selected: selectedHanziIndex === i, correct: matchedHanziIndex === i }"
        @click="selectHanzi(i)"
      >
        <div :id="`${id}-connect-hanzi${i}`" class="connect-hanzi-box" />

      </div>
    </div>

    <!-- 오른쪽: 의미 -->
    <div class="connect-column right" :style="getColumnStyle">
      <div
        class="connect-item meaning"
        v-for="(meaning, i) in meaningList"
        :key="'m' + i"
        :class="{ selected: selectedMeaningIndex === i, correct: matchedMeaningIndex === i }"
        @click="selectMeaning(i)"
      >
        {{ meaning }}
      </div>
    </div>
  </div>

</template>
  
<script>
import HanziWriter from 'hanzi-writer'

  export default {
    props: {
      id: {
			type: String,
			required: true
		   },
      characters: {
        type: Array,
        required: true
      },
      meaningList: {
        type: Array,
        required: true
      },
      correctPairs: {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        // hanziList: ['爱', '火', '水'],
        // meaningList: ['사랑', '불', '물'],
        // correctPairs: {
        //   0: 0,
        //   1: 1,
        //   2: 2,
        // },
        selectedHanziIndex: null,
        selectedMeaningIndex: null,
        matchedHanziIndex: null,
        matchedMeaningIndex: null,
        writers: [],
        matchedPairs: [],
      };
    },
    computed: {
      getColumnStyle() {
        const total = this.meaningList.length;
        let gap = '10px';
        console.log(total);
        if (total <= 3) gap = '60px';
        else if (total <= 5) gap = '45px';
        return { gap };
      }
    },
    mounted() {
      this.characters.forEach((char, i) => {
        const writer = HanziWriter.create(`${this.id}-connect-hanzi${i}`, char, {
          width: 80,
          height: 80,
          padding: 5,
          showOutline: true,
          showCharacter: true,
          radicalColor: '#168F16', // green
          strokeColor: '#aa0099', // 녹색 스트로크
          delayBetweenStrokes: 100,
        })
        this.writers[i] = writer
      })
    },
    methods: {
      selectHanzi(index) {
        this.selectedHanziIndex = index
        this.checkMatch()
      },
      selectMeaning(index) {
        this.selectedMeaningIndex = index
        this.checkMatch()
      },
      
      checkMatch() {
        if (
          this.selectedHanziIndex !== null &&
          this.selectedMeaningIndex !== null
        ) {
          const h = this.selectedHanziIndex;
          const m = this.selectedMeaningIndex;
          

          if (this.correctPairs[h] === m) {
            // this.matchedIndex = h;
            this.matchedHanziIndex = h;
            this.matchedMeaningIndex = m;
            this.writers[h].animateCharacter();
            const hanziEl = document.querySelectorAll('.connect-item.hanzi')[h];
            const meaningEl = document.querySelectorAll('.connect-item.meaning')[m];
            
            hanziEl.classList.add('correct');
            meaningEl.classList.add('correct');
            
            setTimeout(() => {
              this.resetSelections();
              
            }, 2000);
          } else {
            // 틀렸을 때 애니메이션 효과를 위한 플래그
            const wrongHanzi = h;
            const wrongMeaning = m;

            this.$nextTick(() => {
              const hanziEl = document.querySelectorAll('.connect-item.hanzi')[wrongHanzi];
              const meaningEl = document.querySelectorAll('.connect-item.meaning')[wrongMeaning];

              hanziEl?.classList.add('wrong');
              meaningEl?.classList.add('wrong');

              setTimeout(() => {
                hanziEl?.classList.remove('wrong');
                meaningEl?.classList.remove('wrong');
              }, 500);
            });

            this.resetSelections();
          }
        }
      },

      resetSelections() {
        this.selectedHanziIndex = null;
        this.selectedMeaningIndex = null;
        this.matchedIndex = null;
      }

    }
  };
</script>
  
<style>
.connect-container {
  display: flex;
  justify-content: space-between;
  padding: 40px;
  background: #f8f8f8;
  min-height: 300px;
}

.connect-column {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.connect-item {
  width: 80px;
  height: 80px;
  font-size: 2em;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 12px;
}

.connect-hanzi-box {
  width: 80px;
  height: 80px;
}

.selected {
  border: 2px solid #3498db;
  background-color: #e0f0fc;
}

.correct {
  animation: glowScale 0.8s ease-in-out 2;
  border: 2px solid #f1c40f;
  background-color: #fff8cc;
}
.connect-line {
  position: absolute;
  background-color: #2ecc71; /* 녹색 선 */
  width: 2px;
  height: 100px; /* 선의 길이 */
  transition: all 0.3s ease-in-out;
  z-index: -1;
  opacity: 0; /* 초기엔 숨김 */
}
.wrong {
  animation: shake 0.4s ease-in-out;
  border: 2px solid #e74c3c;
  background-color: #fdd;
}

@keyframes glowScale {
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 rgba(255, 255, 0, 0.5);
  }
  50% {
    transform: scale(1.15);
    box-shadow: 0 0 20px rgba(255, 255, 0, 0.8);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 0 0 rgba(255, 255, 0, 0.5);
  }
}

@keyframes shake {
  0% { transform: translateX(0); }
  20% { transform: translateX(-6px); }
  40% { transform: translateX(6px); }
  60% { transform: translateX(-4px); }
  80% { transform: translateX(4px); }
  100% { transform: translateX(0); }
}
</style>