<template>
  <div class="project-container">
    <div class="top-zone mb30">
        <div class="search-zone" style="background-color: #dfe5f3;">
          <div style="position: relative;">
            <input type="text" class="form-control sm" style="border: 0;" placeholder="제목을 입력해주세요" v-model="keyword">
            <button class="btn-ico sm ico-after ico-sch" @click="searchProjects(keyword)"></button>
          </div>
        </div>
        <div class="layout center justify-end gap10">
          <select name="" id="" class="form-select sm" style="border: 0; width: 200px;">
            <option value="">최근 수정순</option>
          </select>
          <button class="btn sm" style="background-color: #f4d01e;border: #f4d01e;"><img src="../../../resources/img/content/ico_folder.svg" alt="" style="vertical-align: middle;">폴더</button>
        </div>
    </div>
    <div class="bottom-zone">
      <!-- 새 카드 -->
      <div class="card new-card" @click="goToModelingCreate()">
        <div class="new-symbol">
          <img src="../../../resources/img/content/ico_digital_asset.svg" alt="">
        </div>
        <div class="new-text">새로운<br>디지털 자산 만들기</div>
        <div class="new-icon"></div>
      </div>

      <!-- v-for 카드 반복 -->
      <div class="card" v-for="(project, index) in projects" :key="index">
        <div class="thumbnail" @click="goToModelingUpdate(project)">
          <img :src="project.img" alt="" />
        </div>
        <div class="card-footer">
          <div class="w_100 layout center space-between">
            <p class="title" @click="goToModelingUpdate(project)">{{ project.name }}</p>
            <div class="layout center">
              <button @click="toggleFavorite(index)">
                <img
                  :src="project.isFavorite
                    ? require('../../../resources/img/content/ico_favorites.svg')
                    : require('../../../resources/img/content/ico_unFavorites.svg')"
                />
              </button>
              <button @click="toggleMenu(index)">
                  <img src="../../../resources/img/component/common/ico_bread_dot.svg"
                      alt=""
                      style="transform: rotate(90deg); width: 20px; height: 20px;" />
              </button>
            </div>
          </div>
          <p class="date">{{ project.date }}</p>
        </div>
          <!-- 드롭다운 메뉴 표시 -->
        <div v-if="openMenuIndex === index" class="dropdown-menu"   :class="dropdownDirection">
            <button><img src="../../../resources/img/content/ico_subShare.svg" alt=""> 공유</button>
            <button><img src="../../../resources/img/content/ico_subCopy.svg" alt="" @click="duplicateProject(project.projectId)"> 복사</button>
            <button><img src="../../../resources/img/content/ico_trashcan.svg" alt="" @click="deleteProject(project.projectGroupId)"> 삭제</button>
            <button><img src="../../../resources/img/content/ico_version.svg" alt=""> 버전기록</button>
            <!-- @click="changeProjectName -->
            <button><img src="" alt="" > 이름 변경</button> 
        </div>
      </div>
    </div>
    <div class="old-projects">
      <!-- 팝업 창 -->
      <div v-if="showPopup" class="popup-overlay" @click.self="showPopup = false">
        <div class="popup">
          <button class="close-btn" @click="showPopup = false">X</button>
          <!-- 여기에 내용 넣기 -->
          <h3>작업내역</h3>
          <img src="../../../resources/img/content/ico_digital_asset.svg" alt="작업 이미지" />
          <div class="versions">
            <p>버전 목록</p>
            <ul>
              <li>5월 3일 오후 2:50</li>
              <li>5월 3일 오후 1:14</li>
              <li>5월 1일 오전 11:50</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { deleteProjectProc, findAllProjectsProc, duplicateProjectProc } from '../../../resources/api/asset';

export default {
    data() {
        return {
            projects: [
                // { name: '프로젝트A', date: '2025.05.12', img: require('../../../resources/img/content/sample1.png'),isFavorite: false },
                // { name: '프로젝트B', date: '2025.05.12', img: require('../../../resources/img/content/sample1.png'),isFavorite: true },
                // { name: '프로젝트C', date: '2025.05.12', img: require('../../../resources/img/content/sample1.png'),isFavorite: false },
                // { name: '프로젝트D', date: '2025.05.12', img: require('../../../resources/img/content/sample1.png'),isFavorite: true },
                // { name: '프로젝트E', date: '2025.05.12', img: require('../../../resources/img/content/sample1.png'),isFavorite: false },
            ],
            members: [],
            openMenuIndex: null,
            dropdownDirection: 'right', // 또는 'left'
            // showPopup: false,
            keyword: '', // 검색 키워드

        };
    },
    methods: {
        toggleFavorite(index) {
            this.projects[index].isFavorite = !this.projects[index].isFavorite;
        },
        toggleMenu(index) {
          if (this.openMenuIndex === index) {
            this.openMenuIndex = null;
            return;
          }

          this.$nextTick(() => {
            const card = this.$el.querySelectorAll('.card')[index + 1]; // 0번은 "새 카드"니까 +1
            if (!card) return;

            const rect = card.getBoundingClientRect();
            const windowWidth = window.innerWidth;

            // 카드가 오른쪽 200px 이내에 있으면 왼쪽으로 드롭다운
            this.dropdownDirection = (windowWidth - rect.right < 200) ? 'left' : 'right';
            this.openMenuIndex = index;
          });
        },
        loadMainProjects() {
          findAllProjectsProc({
            memberId: this.getMemId,
            isMain: 'Y' // 대표 프로젝트만 화면 목록에 뜨게 함.
          })
            .then(response => {
              const projectList = response.data.result.projects;

              this.projects = projectList.map(project => ({
                id: project.projectId,
                groupId: project.projectGroupId,
                isMain: project.isMain,
                name: project.projectName,
                date: project.createdAt,
                img: require('../../../resources/img/content/sample1.png'), // 백엔드 - 썸네일 기능 추가 후 수정
                isFavorite: false // 백엔드 - 즐겨찾기 기능 추가 후 수정
              }));
            })
            .catch(error => {console.error('자산 목록 조회 실패: ', error);})
        },
        searchProjects(keyword) {
          findAllProjectsProc({
            memberId: this.getMemId,
            projectName: keyword,
            isMain: 'Y' // 대표 프로젝트만 화면 목록에 뜨게 함.
          })
            .then(response => {
              const projectList = response.data.result.projects;

              this.projects = projectList.map(project => ({
                id: project.projectId,
                groupId: project.projectGroupId,
                isMain: project.isMain,
                name: project.projectName,
                date: project.createdAt,
                img: require('../../../resources/img/content/sample1.png'), // 백엔드 - 썸네일 기능 추가 후 수정
                isFavorite: false // 백엔드 - 즐겨찾기 기능 추가 후 수정
              }));
            })
            .catch(error => {console.error('프로젝트 검색 실패: ', error);})
        },
        loadOldProjects() {
          findAllProjectsProc({
            memberId: this.getMemId,
            projectGroupId: '', // 그룹 아이디 넣어야함
            isMain: 'N' // 이전 프로젝트만 목록에 뜨게 함.
          })
            .then(response => {
              const projectList = response.data.result.projects;

              this.projects = projectList.map(project => ({
                name: project.projectName,
                date: project.createdAt,
                img: require('../../../resources/img/content/sample1.png'), // 백엔드 - 썸네일 기능 추가 후 수정
                isFavorite: false // 백엔드 - 즐겨찾기 기능 추가 후 수정
              }));
            })
            .catch(error => {console.error('자산 목록 조회 실패: ', error);})
        },
        goToModelingCreate() {
          this.$router.push('/modeling.page');
        },
        goToModelingUpdate(project) {
          this.$router.push({ name: 'Modeling', query: {projectId: project.id}});
        },
        duplicateProject(projectId) {
          const data = {
            memberId : this.getMemId
          };

          duplicateProjectProc(projectId, data)
            .then((response) => {
              console.log('복제 성공');
              this.loadMainProjects();
              this.openMenuIndex = null;
            })
            .catch((error) => {
              console.error('복제 실패: ', error);
            })
        },
        // showPopupFunc(){
        //   console.log("팝업창 열기");
        //   this.showPopup = true;
        // },
        deleteProject(projectGroupId) {
          const data = {
            memberId : this.getMemId
          };
          deleteProjectProc(projectGroupId, data)
            .then((response) => {
              console.log('삭제 성공');
              this.loadMainProjects();
              this.openMenuIndex = null;
            })
            .catch((error) => {
              console.error('삭제 실패: ', error);
            })
        }
        
    },
    watch: {},
    computed: {
    ...mapGetters([
      'getMemId',
      'getMemNm',
      'getMemLoginId'
    ])
    },
    components: {},
    created() {},
    mounted() {
      console.log("로그인한 사용자:", this.getMemId);
      this.loadMainProjects();
    },
    beforeUnmount() {},
};

</script>

<!-- <style scoped>
.popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.popup {
  position: relative;
  background: white;
  padding: 24px;
  border-radius: 8px;
  width: 400px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
}
</style> -->