<template>
  <div class="mypage-container">
    <!-- 프로필 섹션 -->
    <div class="profile-section">
      <div class="profile-card">
        <div class="profile-header">
          <div class="profile-avatar">
            {{ getMemberTypeName(userInfo.memberType) === "인플루언서" ? '❤️' : '💜' }}
          </div>
          <div class="profile-info">
            <h2>{{ userInfo.companyName || userInfo.nickName || userInfo.name }}</h2>
            <span class="member-type-badge">{{ getMemberTypeName(userInfo.memberType) }}</span>
          </div>
          <button 
            class="edit-btn" 
            @click="toggleEditMode"
            :class="{ active: isEditMode }"
          >
            {{ isEditMode ? '취소' : '수정' }}
          </button>
        </div>

        <!-- 정보 표시/수정 폼 -->
        <div class="profile-content">
          <div v-if="!isEditMode" class="info-display">
            <div class="info-row">
              <label>이름</label>
              <span>{{ myInfo.name }}</span>
            </div>
            <div class="info-row" v-if="userInfo.memberType === 'INFLUENCER'">
              <label>닉네임</label>
              <span>{{ myInfo.nickName }}</span>
            </div>
            <div class="info-row">
              <label>이메일</label>
              <span>{{ myInfo.email }}</span>
            </div>
            <div class="info-row" v-if="userInfo.memberType !== 'INFLUENCER'">
              <label>회사명</label>
              <span>{{ userInfo.companyName }}</span>
            </div>
            <div class="info-row">
              <label>전화번호</label>
              <span>{{ myInfo.phone || '미등록' }}</span>
            </div>
            <div class="info-row" v-if="userInfo.memberType === 'INFLUENCER'">
              <label>SNS</label>
              <span>{{ myInfo.sns_type || '미등록' }} {{ myInfo.sns_link || '미등록' }}</span>
            </div>
          </div>

          <div v-else class="info-edit">
            <div class="info-row">
              <label>이름</label>
              <span>{{ myInfo.name }}</span>
            </div>
            <div class="info-row" v-if="userInfo.memberType === 'INFLUENCER'">
              <label>닉네임</label>
              <input 
                type="text" 
                v-model="editForm.nickName"
                placeholder="닉네임을 입력하세요"
                class="edit-input w--20"
              />
            </div>
            <div class="info-row">
              <label>비밀번호 변경</label>
              <input 
                type="password" 
                v-model="editForm.newPassword"
                placeholder="비밀번호를 입력하세요."
                class="edit-input"
              />
            </div>
            
            <div class="info-row" v-if="editForm.newPassword">
              <label>비밀번호 확인</label>
              <input 
                type="password" 
                v-model="editForm.confirmPassword"
                placeholder="비밀번호를 한 번 더 입력하세요."
                class="edit-input"
              />
            </div>
            <div class="info-row email-row" v-if="userInfo.memberType !== 'INFLUENCER'">
              <label>이메일</label>
              <div class="email-container">
                <input 
                  type="text" 
                  v-model="editForm.emailLocal"
                  placeholder="이메일"
                  class="edit-input email-local"
                />
                <span>@</span>
                <input 
                  type="text" 
                  v-model="editForm.emailDomain"
                  placeholder="이메일"
                  class="edit-input email-local"
                />
              </div>
            </div>
            <div class="info-row" v-if="userInfo.memberType !== 'INFLUENCER'">
              <label>회사명</label>
              <input 
                type="text" 
                v-model="editForm.companyName"
                placeholder="회사명을 입력하세요"
                class="edit-input"
              />
            </div>
            <div class="info-row phone-row">
              <label>전화번호</label>
              <div class="phone-container">
                <input 
                  type="tel" 
                  v-model="editForm.phone1"
                  placeholder="010"
                  class="edit-input phone-part"
                  maxlength="3"
                />
                <span>-</span>
                <input 
                  type="tel" 
                  v-model="editForm.phone2"
                  placeholder="1234"
                  class="edit-input phone-part"
                  maxlength="4"
                />
                <span>-</span>
                <input 
                  type="tel" 
                  v-model="editForm.phone3"
                  placeholder="5678"
                  class="edit-input phone-part"
                  maxlength="4"
                />
              </div>
            </div>
            <div class="info-row sns--row" v-if="userInfo.memberType === 'INFLUENCER'">
              <label>SNS</label>
              <select v-model="editForm.snsType" class="edit-input">
                <option value="">선택하세요</option>
                <option value="youtube">유튜브</option>
                <option value="instagram">인스타그램</option>
                <option value="naver">네이버 블로그</option>
                <option value="tiktok">틱톡</option>
                <option value="twitter">트위터</option>
              </select>
              <div class="edit-input-container">
                <input 
                  type="text" 
                  v-model="editForm.snsLink"
                  :placeholder="getSnsPlaceholder(editForm.snsType)"
                  class="edit-input"
                />
              </div>
            </div>
            
            
            <div class="edit-actions">
              <button 
                class="btn-save" 
                @click="fnUpdate"
              >
                저장
              </button>
              <button 
                class="btn-cancel" 
                @click="cancelEdit"
              >
                취소
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 추가 정보 섹션 -->
    <div class="additional-info">
      <div class="info-card">
        <h3>계정 정보</h3>
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">계정 타입</span>
            <span class="info-value">{{ getMemberTypeName(userInfo.memberType) }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">계정 ID</span>
            <span class="info-value">{{ userInfo.id }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">가입일</span>
            <span class="info-value">{{ formatDate(myInfo.regDate) || '정보 없음' }}</span>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import "@vuepic/vue-datepicker/dist/main.css";
  /************************************************************************
|    레이아웃
************************************************************************/
  definePageMeta({
    layout: "default",
  });
  /************************************************************************
|   PROPS
 ************************************************************************/
  const props = defineProps({
    propsData: {
      type: Object,
      default: () => {},
    },
  });
  /************************************************************************
|    스토어
 ************************************************************************/
  const useDtStore = useDetailStore();
  const useAtStore = useAuthStore();
  /************************************************************************
|    전역
 ************************************************************************/
  const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
  const router = useRouter();

  const myInfo = ref({});
  
  // 사용자 정보
  const userInfo = ref({
    id: useAtStore.auth.id,
    name: useAtStore.auth.name,
    email: useAtStore.auth.email,
    companyName: useAtStore.auth.companyName,
    companyNumber: useAtStore.auth.companyNumber,
    phone: useAtStore.auth.phone,
    memberType: useAtStore.auth.memberType,
    regDate: null
  });

  // 편집 모드
  const isEditMode = ref(false);
  const editForm = ref({
    name: '',
    nickName: '',
    emailLocal: '',
    emailDomain: null,
    companyName: '',
    phone1: '',
    phone2: '',
    phone3: '',
    snsType: '',
    snsLink: '',
    newPassword: '',
    confirmPassword: ''
  });

  /* eslint-disable */
  /* prettier-ignore */

  /************************************************************************
|    함수(METHODS)
************************************************************************/

  // 회원 타입 이름 반환
  const getMemberTypeName = (type) => {
    switch(type) {
      case 'INFLUENCER': return '인플루언서';
      case 'VENDOR': return '벤더사';
      case 'BRAND': return '브랜드사';
      default: return '사용자';
    }
  };

  // 편집 모드 토글
  const toggleEditMode = () => {
    if (isEditMode.value) {
      // 편집 취소
      isEditMode.value = false;
    } else {
      // 편집 시작 - 현재 값으로 폼 초기화
      const currentEmail = myInfo.value.email || userInfo.value.email || '';
      const [emailLocal, emailDomain] = currentEmail.includes('@') ? currentEmail.split('@') : [currentEmail, ''];
      
      const currentPhone = myInfo.value.phone || userInfo.value.phone || '';
      const phoneParts = currentPhone.split('-');
      
      editForm.value = {
        name: myInfo.value.name || userInfo.value.name,
        nickName: myInfo.value.nickName || '',
        emailLocal: emailLocal,
        emailDomain: emailDomain || null,
        companyName: userInfo.value.companyName || '',
        phone1: phoneParts[0] || '',
        phone2: phoneParts[1] || '',
        phone3: phoneParts[2] || '',
        snsType: myInfo.value.sns_type || '',
        snsLink: myInfo.value.sns_link || '',
        newPassword: '',
        confirmPassword: ''
      };
      isEditMode.value = true;
    }
  };

  // 편집 취소
  const cancelEdit = () => {
    isEditMode.value = false;
  };


  // 프로필 저장
  const fnUpdate = async () => {
    // 패스워드 유효성 검사
    if (editForm.value.newPassword && editForm.value.newPassword !== editForm.value.confirmPassword) {
      $toast.error('패스워드가 일치하지 않습니다.');
      return;
    }

    if (editForm.value.newPassword && editForm.value.newPassword.length < 6) {
      $toast.error('패스워드는 최소 6자 이상이어야 합니다.');
      return;
    }

    let req = {
      MEMBER_TYPE: useAtStore.auth.memberType,
      MEMBER_SEQ: useAtStore.auth.seq,
      EMAIL: `${editForm.value.emailLocal}@${editForm.value.emailDomain || ''}`,
      COMPANY_NAME: editForm.value.companyName,
      SNS_TYPE: editForm.value.snsType,
      SNS_LINK_ID: editForm.value.snsLink
    }
    
    // 패스워드가 입력된 경우에만 추가
    if (editForm.value.newPassword.trim()) {
      req.PASSWORD = editForm.value.newPassword;
    }
    
    // 전화번호 조합
    const combinedPhone = `${editForm.value.phone1}-${editForm.value.phone2}-${editForm.value.phone3}`;
    
    // 인플루언서인 경우 닉네임 추가
    if (userInfo.value.memberType === 'INFLUENCER') {
      req.PHONE = combinedPhone;
      req.NICK_NAME = editForm.value.nickName;
    }

    // 인플루언서/벤더&브랜드사 테이블 내 연락처 컬럼명이 상이해 별도로 처리
    if (userInfo.value.memberType !== 'INFLUENCER') {
      req.HP = combinedPhone;
    }

    useAxios().post('/mypage/update', req).then(async (res) => {
      // 로컬 데이터 업데이트
      myInfo.value.email = `${editForm.value.emailLocal}@${editForm.value.emailDomain || ''}`;
      myInfo.value.phone = combinedPhone;
      myInfo.value.sns_type = editForm.value.snsType;
      myInfo.value.sns_link = editForm.value.snsLink;
      
      if (userInfo.value.memberType === 'INFLUENCER') {
        myInfo.value.nickName = editForm.value.nickName;
      }

      // 스토어도 업데이트
      useAtStore.auth.email = `${editForm.value.emailLocal}@${editForm.value.emailDomain || ''}`;
      useAtStore.auth.phone = combinedPhone;
      if (userInfo.value.memberType !== 'INFLUENCER') {
        useAtStore.auth.companyName = editForm.value.companyName;
      }

      $toast.success('프로필이 성공적으로 수정되었습니다.');
      isEditMode.value = false;
      
      // 페이지 새로고침 (F5)
      location.reload();
    })
  };

  const formatDate = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}.${month}.${day}`;
  };

  // SNS 입력 placeholder 반환
  const getSnsPlaceholder = (snsType) => {
    const placeholders = {
      'youtube': '채널 ID 또는 전체 URL',
      'instagram': '사용자명 또는 전체 URL',
      'naver': '블로그 ID 또는 전체 URL',
      'tiktok': '사용자명 또는 전체 URL',
      'facebook': '페이지명 또는 전체 URL',
      'twitter': '사용자명 또는 전체 URL',
      'blog': '블로그 주소',
      'kakao': '사용자명 또는 전체 URL'
    };
    return placeholders[snsType] || 'SNS 링크 또는 ID를 입력하세요';
  };

  // 사용자 상세 정보 로드
  const fnDetail = () => {
    let req = {
      MEMBER_TYPE: useAtStore.auth.memberType, 
      MEMBER_SEQ: useAtStore.auth.seq
    }

    useAxios()
      .post(`/mypage/detail`, req)
      .then((res) => {
        myInfo.value.id = res.data.ID;
        myInfo.value.name = res.data.NAME;
        myInfo.value.nickName = res.data.NICK_NAME;
        myInfo.value.phone = res.data.PHONE || res.data.HP;
        myInfo.value.sns_type = res.data.SNS_TYPE;
        myInfo.value.sns_link = res.data.SNS_LINK_ID;
        myInfo.value.email = res.data.EMAIL;
        myInfo.value.regDate = res.data.REGDATE || res.data.REG_DATE;
    })
  };

  /************************************************************************
  |    라이프사이클
  ************************************************************************/

  onMounted(() => {
    fnDetail();
  });
</script>

<style scoped>
.mypage-container {
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-header h1 {
  font-size: 2.5rem;
  color: #1a237e;
  margin-bottom: 8px;
}

.page-header p {
  color: #666;
  font-size: 1.1rem;
}

.profile-section {
  margin-bottom: 32px;
}

.profile-card {
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.profile-header {
  display: flex;
  align-items: center;
  padding: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.profile-avatar {
  font-size: 3rem;
  margin-right: 24px;
  background: rgba(255, 255, 255, 0.2);
  width: 96px;
  height: 96px;
  overflow: hidden;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.profile-info {
  flex: 1;
}

.profile-info h2 {
  margin-bottom: 15px;
  font-size: 1.8rem;
}

.member-type-badge {
  background: rgba(255, 255, 255, 0.2);
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.9rem;
}

.edit-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 2px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 12px 24px;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.edit-btn:hover, .edit-btn.active {
  background: white;
  color: #667eea;
}

.profile-content {
  padding: 32px;
}

/* 정보 표시 스타일 */
.info-display .info-row {
  display: flex;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-display .info-row:last-child {
  border-bottom: none;
}

.info-display label {
  width: 150px;
  font-weight: 600;
  color: #333;
}

.info-display span {
  flex: 1;
  color: #666;
}

/* 편집 폼 스타일 */
.info-edit .info-row {
  display: flex;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  align-items: center;
}

.info-edit .info-row.sns--row > .edit-input{
  width: 20%;
  flex: none;
  margin-right: 20px;
}

.info-edit .info-row.sns--row .edit-input-container{
  width: 100%;
}

.info-edit .info-row.sns--row .edit-input-container .edit-input{
  width: 100%;
}

.info-edit .info-row:last-child {
  border-bottom: none;
}

.info-edit label {
  width: 150px;
  font-weight: 600;
  color: #333;
  flex-shrink: 0;
}

.edit-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
  background: white;
}

.edit-input.w--20{
  width: 20%;
}

.edit-input:focus {
  outline: none;
  border-color: #667eea;
}

.edit-input:disabled {
  background: #f8f9fa;
  color: #6c757d;
  cursor: not-allowed;
}

.edit-help {
  display: block;
  margin-top: 4px;
  font-size: 0.8rem;
  color: #666;
  font-style: italic;
}

.edit-actions {
  display: flex;
  gap: 12px;
  margin-top: 32px;
  justify-content: flex-end;
}

.btn-save {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-save:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.btn-save:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-cancel {
  background: #f5f5f5;
  color: #666;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-cancel:hover {
  background: #e0e0e0;
}

/* 추가 정보 섹션 */
.additional-info {
  margin-top: 32px;
}

.info-card {
  background: white;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.info-card h3 {
  margin: 0 0 24px 0;
  color: #1a237e;
  font-size: 1.3rem;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 24px;
}

.info-item {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 12px;
}

.info-label {
  display: block;
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 15px;
}

.info-value {
  font-weight: 600;
  color: #333;
  font-size: 1rem;
}

/* 이메일 입력 스타일 */
.email-container {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.email-local {
  width: 20%;
}

.email-domain {
}

/* 전화번호 입력 스타일 */
.phone-container {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 20%;
}

.phone-part {
  flex: 1;
  text-align: center;
}


</style>