<template>
  <div class="login-wrap">
    <div class="login--gate" v-show="loginVisible == 'Y'">
      <div class="gate-container">
        <div
          class="gate-card influencer-gate"
          :class="gate1 ? 'actv' : ''"
          @mouseover="handleInfluenceMove"
          @click.stop="location('influence')"
          @mouseleave="gate1 = false"
        >
          <div class="gate-icon">
            <div class="icon-circle influencer-bg">
              ❤️
            </div>
          </div>
          <div class="gate-content">
            <h3>인플루언서</h3>
            <p>크리에이터와 함께하세요</p>
          </div>
        </div>

        <div
         @click.stop="location('vendor')"
          class="gate-card vendor-gate"
          :class="gate2 ? 'actv' : ''"
          @mouseover="handleVendorMove"
          @mouseleave="gate2 = false"
        >
          <div class="gate-icon">
            <div class="icon-circle vendor-bg">
              🛍️
            </div>
          </div>
          <div class="gate-content" >
            <h3>벤더사</h3>
            <p>상품을 판매해보세요</p>
          </div>
        </div>

        <div
         @click.stop="location('brand')"
          class="gate-card brand-gate"
          :class="gate3 ? 'actv' : ''"
          @mouseover="handleBrandMove"
          @mouseleave="gate3 = false"
        >
          <div class="gate-icon">
            <div class="icon-circle brand-bg">
              💎
            </div>
          </div>
          <div class="gate-content">
            <h3>브랜드사</h3>
            <p>브랜드를 성장시켜보세요</p>
          </div>
        </div>
      </div>
    </div>

    <div class="login--cock" v-show="loginVisible == 'N'">
      <!-- header -->
      <div class="login--header">
        <div class="login--header--l">
          <div class="logo">
            SHOPDELI
          </div>
        </div>
        <div class="login--header--r"></div>
      </div>
      <!-- login -->
      <div class="login-box">
        <div class="login-l">
          <div class="login-l-center">
            <span class="logo">
              <!-- prettier-ignore  -->
              SHOPDELI
            </span>
            <!-- <p>We Make Scalable Mobility Life</p> -->
          </div>
        </div>
        <div class="login-r">
          <div class="tit-login">
            <strong>{{ route.query.type == 'brand' ? '브랜드사' : route.query.type == 'vendor' ? '벤더사' : '' }} 로그인</strong>
          </div>
          <div class="login-input-wrap">
            <div
              class="txt-field-box"
              :class="!loginForm.validCheck.input.userId ? 'error' : ''"
            >
              <v-text-field
                v-model="loginForm.userId"
                placeholder="아이디를 입력해주세요"
                class="custom-input"
                @keyup.enter="
                  loginAction(loginForm.userId, loginForm.passwd, loginForm.loginType)
                "
                @input="setInputField('main_userId')"
              ></v-text-field>
              <i class="ico"></i>
            </div>
            <div
              class="txt-field-box"
              :class="!loginForm.validCheck.input.passwd ? 'error' : ''"
            >
              <v-text-field
                v-model="loginForm.passwd"
                :type="visible ? 'text' : 'password'"
                placeholder="비밀번호를 입력해주세요"
                class="custom-input"
                id="password"
                @keyup.enter="
                  loginAction(loginForm.userId, loginForm.passwd, loginForm.loginType)
                "
                @input="setInputField('main_passwd')"
              ></v-text-field>
              <i
                class="ico-eye"
                @click.stop="toggleVisibility"
                :class="visible ? 'eye-on' : 'eye-off'"
              ></i>
              <i class="ico"></i>
            </div>
            <!-- <p class="error-txt" v-if="!loginForm.validCheck.inputErrorCheck">
              {{ loginForm.validCheck.passwd }}
            </p> -->
          </div>

          <div class="login-btn-wrap">
            <v-btn
              v-if="loginForm.loginType == 'influence'"
              class="custom-btn btn-blue"
              @keyup.enter="loginAction(loginForm.userId, loginForm.passwd, 'influence')"
              @click="loginAction(loginForm.userId, loginForm.passwd, 'influence')"
              >로그인</v-btn
            >
            <v-btn
              v-else-if="loginForm.loginType == 'vendor'"
              class="custom-btn btn-blue"
              @keyup.enter="loginAction(loginForm.userId, loginForm.passwd, 'vendor')"
              @click="loginAction(loginForm.userId, loginForm.passwd, 'vendor')"
              >로그인</v-btn
            >
            <v-btn
              v-else-if="loginForm.loginType == 'brand'"
              class="custom-btn btn-blue"
              @keyup.enter="loginAction(loginForm.userId, loginForm.passwd, 'brand')"
              @click="loginAction(loginForm.userId, loginForm.passwd, 'brand')"
              >로그인</v-btn
            >
          </div>
          <div class="join--btn--wrap">
            <v-btn class="custom-btn text--btn" @click="openFindIdModal">아이디 찾기</v-btn>
            <v-btn class="custom-btn text--btn" @click="openFindPwModal">비밀번호 찾기</v-btn>
            <v-btn class="custom-btn text--btn" @click="location('join')">회원가입</v-btn>
          </div>
          <div class="short--login--wrap" v-if="loginForm.loginType == 'influence'">
            <v-btn class="btn--google" @click.stop="onGoogleLogin"></v-btn>
            <v-btn class="btn--kakao" @click.stop="onKakaoLogin"></v-btn>
            <v-btn class="btn--naver" @click.stop="onNaverLogin"></v-btn>
          </div>
        </div>
      </div>

      <!-- footer -->
      <div class="login-footer">
        <div class="login--footer--l">
          <p>COPYRIGHT@2025 SHOPDELI INC. ALL RIGHTS RESERVED.</p>
          <p>마포구 합정동</p>
        </div>
      </div>
    </div>

    <!-- 아이디 찾기 모달 -->
    <v-dialog v-model="showFindIdModal" max-width="600px" persistent>
      <v-card class="inquiry-modal">
        <v-card-title class="modal-header">
          <h3>아이디 찾기</h3>
          <v-btn icon @click="closeFindIdModal" class="close-btn">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </v-card-title>

        <v-card-text class="modal-body">
          <form @submit.prevent="findUserId">
            <div class="form-group">
              <label>이름 <span class="required">*</span></label>
              <v-text-field
                v-model="findIdForm.name"
                variant="outlined"
                hide-details
                placeholder="이름을 입력해주세요"
                class="custom-input"
                :error="!findIdValidation.name"
              ></v-text-field>
            </div>

            <div class="form-group mb--0">
              <label>이메일 <span class="required">*</span></label>
              <div class="email-input-group">
                <v-text-field
                  v-model="findIdForm.emailLocal"
                  variant="outlined"
                  hide-details
                  placeholder="이메일"
                  class="custom-input email-local"
                  :error="!findIdValidation.email"
                ></v-text-field>
                <span class="email-at">@</span>
                <v-combobox
                  v-model="findIdForm.emailDomain"
                  :items="['gmail.com', 'naver.com', 'daum.net', 'hotmail.com', 'yahoo.com']"
                  hide-details
                  variant="outlined"
                  placeholder="도메인 선택"
                  class="custom-select email-domain"
                  :error="!findIdValidation.email"
                ></v-combobox>
              </div>
            </div>

            <div class="form-group" style="display: none;">
              <label>회원 유형 <span class="required">*</span></label>
              <v-select
                v-model="findIdForm.memberType"
                :items="findIdMemberTypes"
                readonly="true"
                variant="outlined"
                placeholder="회원 유형을 선택해주세요"
                class="custom-select"
              ></v-select>
            </div>
          </form>
        </v-card-text>

        <v-card-actions class="modal-footer">
          <v-btn @click="closeFindIdModal" class="cancel-btn">취소</v-btn>
          <v-btn @click="findUserId" class="submit-btn" :loading="findIdLoading">아이디 찾기</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 아이디 찾기 결과 모달 -->
    <v-dialog v-model="showFindIdResultModal" max-width="600px" persistent>
      <v-card class="inquiry-modal">
        <v-card-title class="modal-header">
          <h3>아이디 찾기 결과</h3>
          <v-btn icon @click="closeFindIdResultModal" class="close-btn">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </v-card-title>

        <v-card-text class="modal-body">
          <div v-if="foundUserIds.length > 0" class="result-success">
            <div class="success-icon">✅</div>
            <h4>아이디를 찾았습니다!</h4>
            <div class="found-ids">
              <div v-for="(user, index) in foundUserIds" :key="index" class="user-info">
                <p class="user-id">{{ maskUserId(user.id) }}</p>
                <p class="join-date">가입일: {{ formatDate(user.joinDate) }}</p>
              </div>
            </div>
          </div>
          <div v-else class="result-error">
            <div class="error-icon">❌</div>
            <h4>아이디를 찾을 수 없습니다</h4>
            <p>입력하신 정보와 일치하는 아이디가 없습니다.<br>정보를 다시 확인해 주세요.</p>
          </div>
        </v-card-text>

        <v-card-actions class="modal-footer">
          <v-btn @click="closeFindIdResultModal" class="cancel-btn">닫기</v-btn>
          <v-btn v-if="foundUserIds.length > 0" @click="goToLoginFromModal" class="submit-btn">로그인하기</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 비밀번호 찾기 모달 -->
    <v-dialog v-model="showFindPwModal" max-width="600px" persistent>
      <v-card class="inquiry-modal">
        <v-card-title class="modal-header">
          <h3>비밀번호 찾기</h3>
          <v-btn icon @click="closeFindPwModal" class="close-btn">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </v-card-title>

        <v-card-text class="modal-body">
          <form @submit.prevent="findUserPw">
            <div class="form-group">
              <label>이름 <span class="required">*</span></label>
              <v-text-field
                v-model="findPwForm.name"
                variant="outlined"
                hide-details
                placeholder="이름을 입력해주세요"
                class="custom-input"
                :error="!findPwValidation.name"
              ></v-text-field>
            </div>

            <div class="form-group">
              <label>아이디 <span class="required">*</span></label>
              <v-text-field
                v-model="findPwForm.userId"
                variant="outlined"
                hide-details
                placeholder="아이디를 입력해주세요"
                class="custom-input"
                :error="!findPwValidation.userId"
              ></v-text-field>
            </div>

            <div class="form-group mb--0">
              <label>이메일 <span class="required">*</span></label>
              <div class="email-input-group">
                <v-text-field
                  v-model="findPwForm.emailLocal"
                  variant="outlined"
                  hide-details
                  placeholder="이메일"
                  class="custom-input email-local"
                  :error="!findPwValidation.email"
                ></v-text-field>
                <span class="email-at">@</span>
                <v-combobox
                  v-model="findPwForm.emailDomain"
                  :items="['gmail.com', 'naver.com', 'daum.net', 'hotmail.com', 'yahoo.com']"
                  hide-details
                  variant="outlined"
                  placeholder="도메인 선택"
                  class="custom-select email-domain"
                  :error="!findPwValidation.email"
                ></v-combobox>
              </div>
            </div>

            <div class="form-group" style="display: none;">
              <label>회원 유형 <span class="required">*</span></label>
              <v-select
                v-model="findPwForm.memberType"
                :items="findIdMemberTypes"
                readonly="true"
                variant="outlined"
                placeholder="회원 유형을 선택해주세요"
                class="custom-select"
              ></v-select>
            </div>
          </form>
        </v-card-text>

        <v-card-actions class="modal-footer">
          <v-btn @click="closeFindPwModal" class="cancel-btn">취소</v-btn>
          <v-btn @click="findUserPw" class="submit-btn" :loading="findPwLoading">확인</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 비밀번호 변경 모달 -->
    <v-dialog v-model="showChangePwModal" max-width="600px" persistent>
      <v-card class="inquiry-modal">
        <v-card-title class="modal-header">
          <h3>새 비밀번호 설정</h3>
          <v-btn icon @click="closeChangePwModal" class="close-btn">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </v-card-title>

        <v-card-text class="modal-body">
          <div class="success-message mb--20">
            <div class="success-icon">✅</div>
            <p>회원 정보가 확인되었습니다.<br>새로운 비밀번호를 설정해주세요.</p>
          </div>

          <form @submit.prevent="changePassword">
            <div class="form-group">
              <label>새 비밀번호 <span class="required">*</span></label>
              <v-text-field
                v-model="changePwForm.newPassword"
                :type="showNewPassword ? 'text' : 'password'"
                variant="outlined"
                hide-details
                placeholder="새 비밀번호를 입력해주세요"
                class="custom-input"
                :error="!changePwValidation.newPassword"
              >
                <template v-slot:append-inner>
                  <v-btn icon size="small" @click="showNewPassword = !showNewPassword">
                    <v-icon>{{ showNewPassword ? 'mdi-eye-off' : 'mdi-eye' }}</v-icon>
                  </v-btn>
                </template>
              </v-text-field>
            </div>

            <div class="form-group mb--0">
              <label>새 비밀번호 확인 <span class="required">*</span></label>
              <v-text-field
                v-model="changePwForm.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'"
                variant="outlined"
                hide-details
                placeholder="새 비밀번호를 다시 입력해주세요"
                class="custom-input"
                :error="!changePwValidation.confirmPassword"
              >
                <template v-slot:append-inner>
                  <v-btn icon size="small" @click="showConfirmPassword = !showConfirmPassword">
                    <v-icon>{{ showConfirmPassword ? 'mdi-eye-off' : 'mdi-eye' }}</v-icon>
                  </v-btn>
                </template>
              </v-text-field>
            </div>
          </form>
        </v-card-text>

        <v-card-actions class="modal-footer">
          <v-btn @click="closeChangePwModal" class="cancel-btn">취소</v-btn>
          <v-btn @click="changePassword" class="submit-btn" :loading="changePwLoading">비밀번호 변경</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script setup>
  /************************
   *    import
   ************************/
  //import PrivacyPop from "@/components/login/privacyPop.vue";
  //import AgrNPop from "@/components/terms/agreeNListPop.vue";
  import { useI18n } from "vue-i18n";

  /************************
   *    layout setting
   ************************/
  definePageMeta({
    layout: "loginlayout",
  });

  /************************
   *    plugins inject
   ************************/
  const { $dayjs, $log, $eventBus, $toast, $userAgent } = useNuxtApp();

  const useStore = useDetailStore();
  const route = useRoute();
  /************************
   *    data & created
   ************************/

  // 현재 입력 중인 필드를 설정하는 함수
  const setInputField = (name) => {
    fnValidCheck(name);
  };
  const pageId = "login";
  const gate1 = ref(false);
  const gate2 = ref(false);
  const gate3 = ref(false);
  const loginVisible = ref("N");

  const i18n = useI18n();
  // 다국어
  let listObj = ref({
    langTypeList: {},
  });
  // 로그인 정보
  const loginForm = ref({
    userId: "",
    passwd: "",
    otpNum: "",
    username: "",
    authType: "GOOGLE",
    userAgent: "",
    loginType: "",
    validCheck: {
      input: {
        userId: true,
        passwd: true,
      },
      otp: {
        otpNum: true,
      },
      inputErrorCheck: true,
      inputValidTxt: "",
      otpValidTxt: "",
      loginValidCheck: false,
      btnTxt: "",
      btnTxtType: "",
    },
  });
  // 구글 OTP 1차 팝업
  const authPop1 = ref({
    popYn: false,
    certifyYN: false,
    userId: "",
    passwd: "",
    otpNum: "",
    validOtpKey: true,
    validOtpTxt: "",
    btnTxt: "",
    btnTxtType: "",
    applyBtn: false,
    succOtpYn: false,
    businessName: "",
    agreeChk1: false,
    agreeChk2: false,
    validCheck: {
      userId: true,
      passwd: true,
    },
    validTxt: "",
    errorCheck: false,
  });
  // 구글 OTP 2차 팝업
  const authPop2 = ref({
    popYn: false,
    otpNum: "",
    validOtpKey: true,
    validOtpTxt: "",
    errorCheck: false,
  });
  // 아이디 찾기 모달
  const showFindIdModal = ref(false);
  const showFindIdResultModal = ref(false);
  const findIdLoading = ref(false);
  const foundUserIds = ref([]);
  
  const findIdForm = ref({
    name: '',
    emailLocal: '',
    emailDomain: null,  // 빈 문자열 대신 null로 설정
    memberType: ''
  });
  
  const findIdValidation = ref({
    name: true,
    email: true
  });
  
  const findIdMemberTypes = [
    { title: '회원 유형 선택', value: '', disabled: true },
    { title: '인플루언서', value: 'influence' },
    { title: '벤더사', value: 'vendor' },
    { title: '브랜드사', value: 'brand' }
  ];

  // 비밀번호 찾기 모달
  const showFindPwModal = ref(false);
  const showChangePwModal = ref(false);
  const findPwLoading = ref(false);
  const changePwLoading = ref(false);
  const foundUser = ref(null);
  
  const findPwForm = ref({
    name: '',
    userId: '',
    emailLocal: '',
    emailDomain: null,  // 빈 문자열 대신 null로 설정
    memberType: ''
  });
  
  const findPwValidation = ref({
    name: true,
    userId: true,
    email: true
  });

  const changePwForm = ref({
    newPassword: '',
    confirmPassword: ''
  });

  const changePwValidation = ref({
    newPassword: true,
    confirmPassword: true
  });

  const showNewPassword = ref(false);
  const showConfirmPassword = ref(false);
  // 비밀번호 초기화
  const resetPw = ref({
    popYn: false,
    userId: "",
    email: "",
    otpNum: "",
    validCheck: {
      input: {
        userId: true,
        email: true,
      },
      otp: {
        otpNum: true,
      },
      inputErrorCheck: true,
      inputValidTxt: "",
      otpValidTxt: "",
      resetPwValidCheck: false,
    },
    btnTxt: "",
  });

  // 초기 패스워드 변경
  const initPw = ref({
    popYn: false,
    passwd: "",
    passwd2: "",
    validCheck: {
      passwd: true,
      passwd2: true,
    },
    passwdCheck: false,
    errorTxt: "",
  });

  const selectPlaceholder = ref("");
  const initAuthPop1 = ref({});
  const initAuthPop2 = ref({});
  const initFindId = ref({});
  const initResetPw = ref({});
  const initInitPw = ref({});
  const googleOtpQrCode = ref("");
  const googleOtpSecretKey = ref("");
  const loginInfo = ref({});
  const checkbox = ref(false);
  const langType = ref("");
  const toggleVisibility = () => {
    visible.value = !visible.value;
  };
  const visible = ref(false);
  const isAgrNPop = ref(false);
  const isShowAgrNPop = ref(false);
  let saveId = localStorage.getItem("saveId");
  if (saveId) {
    checkbox.value = true;
    loginForm.value.userId = saveId;
  }

  const handleInfluenceMove = (event) => {
    gate1.value = true;
    gate2.value = false;
    gate3.value = false;
  };

  const handleVendorMove = (event) => {
    gate2.value = true;
    gate1.value = false;
    gate3.value = false;
  };

  const handleBrandMove = (event) => {
    gate3.value = true;
    gate1.value = false;
    gate2.value = false;
  };

  // 개인정보처리방침 이용약관 팝업
  //const privacyPop = ref(false);
  const privacyDetail = ref({
    kr: {
      title: "",
      contents: "",
    },
    en: {
      title: "",
      contents: "",
    },
  });
  const systemInfo = ref({
    mode: "",
  });

  const loginAction = (__ID, __PASS, __TYPE) => {
    let _req = {
      id: __ID,
      password: __PASS,
      logintype: __TYPE,
    };

    useAxios()
      .post("/roulette/login", _req)
      .then((res) => {
        if (res.data) {
          // console.log(res.data);
          useAuthStore().setAuth(res.data);
          useAuthStore().setAccessToken(res.data.accessToken);
          useAuthStore().setRefreshToken(res.data.refreshToken);
          
          // 디버깅: 로그인 후 사용자 정보 확인
          console.log('=== 로그인 성공 디버깅 ===');
          console.log('원본 데이터:', res.data);
          console.log('설정된 auth 정보:', useAuthStore().auth);
          console.log('COMPANY_NUMBER:', useAuthStore().auth.companyNumber);
          console.log('memberType:', useAuthStore().auth.memberType);
          console.log('===========================');
          
          localStorage.setItem("tempAccess", __ID);
          
          // vendor/brand 타입이면 dashboard로, 그 외에는 기존 item 페이지로
          const memberType = useAuthStore().auth.memberType;
          if (memberType === 'VENDOR' || memberType === 'BRAND') {
            useUtil.setPageMove("/view/common/dashboard");
            useStore.menuInfo.menuIndex = "0";
            useStore.menuInfo.menuId = "menu00";
            useStore.menuInfo.pageRtName = "대시보드";
            useStore.menuInfo.pageStatus = null;
          } else {
            useUtil.setPageMove("/view/common/item");
            useStore.menuInfo.menuIndex = "0";
            useStore.menuInfo.menuId = "menu01";
            useStore.menuInfo.pageRtName = "제품 관리";
            useStore.menuInfo.pageStatus = null;
          }
        }
      })
      .catch((error) => {
        if (error.response) {
          console.log("status:", error.response.status, "data:", error.response.data);
          // 안전하게 errCode, message 접근
          const errData = error.response.data || {};
          const errCode = errData.errCode || errData.errorCode || errData.code || "";
          const errMsg = errData.message || "알 수 없는 오류가 발생했습니다.";
          console.log("errCode:", errCode, "message:", errMsg);
        } else {
          console.log("error:", error.message, error.code);
        }
        if (error.response?.status) {
          fnLoginSet(error.response.data.messages.message);
        }
        $log.debug("[login][fnIdPwCheck][error]");
      })
      .finally(() => {
        $log.debug("[login][fnIdPwCheck][finished]");
      });
  };

  const location = (__id) => {
    switch (__id) {
      case "join":
        useUtil.setPageMove("/auth/join?type=" + loginForm.value.loginType);
        break;
      case "findId":
        findId.value.popYn = true;
        break;
      case "resetPw":
        resetPw.value.popYn = true;
        break;
      case "influence":
        useUtil.setPageMove("/?type=influence");
        loginVisible.value = "Y";
        break;
      case "vendor":
        useUtil.setPageMove("/?type=vendor");
        loginVisible.value = "N";
        break;
      case "brand":
        useUtil.setPageMove("/?type=brand");
        loginVisible.value = "N";
        break;
      default:
        break;
    }
  };

  // onMounted
  onMounted(() => {
    //로그인페이지 접근시 파라미터 체크하여 인플루언서, 밴더 구분
    const typeParam = route.query.type;
    if (typeParam == "influence") {
      loginForm.value.loginType = "influence";
    } else if (typeParam == "vendor") {
      loginForm.value.loginType = "vendor";
    } else if (typeParam == "brand") {
      loginForm.value.loginType = "brand"; 
    } else {
      loginVisible.value = "Y";
    }

    //구글 인증 프로세스
    function handleMessage(event) {
      const appBaseUrl = import.meta.env.VITE_APP_API_URL;
      // 개발환경이면 아래처럼 확인
      const allowedOrigins = [
        "http://0.0.0.0:3000",
        "http://localhost:3000",
        appBaseUrl,
      ].filter(Boolean);
      if (allowedOrigins.includes(event.origin)) {
        const { accessToken, refreshToken, user } = event.data;

        if (user?.JOIN === "1") {
          useAuthStore().setTempData(user);
          useUtil.setPageMove("/auth/join?type=" + loginForm.value.loginType);
        } else {
          // SNS 로그인 성공 시 인증 정보 제대로 설정
          const authData = {
            refreshToken: refreshToken,
            user: user,
          };

          // setAuth를 호출하여 auth 스토어에 사용자 정보 저장
          useAuthStore().setAuth(authData);
          useAuthStore().setTempData(authData);
          useAuthStore().setAccessToken(accessToken);
          useAuthStore().setRefreshToken(refreshToken);
          localStorage.setItem("tempAccess", user.ID || user.id || user.SEQ);
          useUtil.setPageMove("/view/common/item");
          useStore.menuInfo.menuIndex = "0";
          useStore.menuInfo.menuId = "menu02";
          useStore.menuInfo.pageRtName = "이벤트 관리";
          useStore.menuInfo.pageStatus = null;
        }
      }
    }
    window.addEventListener("message", handleMessage);
    onBeforeUnmount(() => window.removeEventListener("message", handleMessage));
  });

  watch(
    () => route.query.type,
    (newType) => {
      if (newType === "influence" || newType === "vendor" || newType === "brand") {
        loginForm.value.loginType = newType;
        loginVisible.value = "N"; // 로그인 폼 보이기
      } else {
        loginVisible.value = "Y"; // 게이트 페이지 보이기
      }
    },
    {
      immediate: true, // 컴포넌트가 마운트될 때 즉시 실행
    }
  );

  watchEffect(() => {
    // 감시하고자 하는 데이터를 해당 블럭내에서 사용하면 호출된다.
    // getLang.value를 감시하는 상태
    //QfnGetEnumCode(useLangStore().getLang);
  });

  // $eventBus.off("SET_SUCCESS_POPUP");
  // $eventBus.on("SET_SUCCESS_POPUP", () => {
  //   // 안내 팝업 확인 클릭 팝업 초기화처리
  //   fnOtpPopClose("findId");
  //   fnOtpPopClose("resetPw");
  // });

  // $eventBus.off("PASSWD_CHANGE");
  // $eventBus.on("PASSWD_CHANGE", () => {
  //   fnPasswdChange();
  // });

  // $eventBus.off("INIT_PASSWORD");
  // $eventBus.on("INIT_PASSWORD", () => {
  //   initPw.value.popYn = true;
  // });

  // $eventBus.off("SET_LOGIN");
  // $eventBus.on("SET_LOGIN", () => {
  //   fnLogin();
  // });
  /************************
   *    Methods
   ************************/

  const showComingSoon = () => {
    $eventBus.emit('OPEN_CONFIRM_POP_UP', {
      id: 'coming-soon',
      title: '안내',
      content: '준비중입니다.',
      yes: {
        text: '확인',
        isProc: false
      }
    });
  };

  // 아이디 찾기 모달 관련 함수들
  const openFindIdModal = () => {
    // URL 파라미터에서 type을 가져와서 회원 유형 설정
    const typeParam = route.query.type;
    if (typeParam && ['influence', 'vendor', 'brand'].includes(typeParam)) {
      findIdForm.value.memberType = typeParam;
    } else {
      findIdForm.value.memberType = loginForm.value.loginType || '';
    }
    showFindIdModal.value = true;
  };

  const closeFindIdModal = () => {
    showFindIdModal.value = false;
    resetFindIdForm();
  };

  const closeFindIdResultModal = () => {
    showFindIdResultModal.value = false;
    foundUserIds.value = [];
  };

  const resetFindIdForm = () => {
    // URL 파라미터에서 type을 가져와서 기본값으로 설정
    const typeParam = route.query.type;
    let defaultMemberType = '';
    if (typeParam && ['influence', 'vendor', 'brand'].includes(typeParam)) {
      defaultMemberType = typeParam;
    } else {
      defaultMemberType = loginForm.value.loginType || '';
    }
    
    findIdForm.value = {
      name: '',
      emailLocal: '',
      emailDomain: null,  // 빈 문자열 대신 null로 설정
      memberType: defaultMemberType
    };
    findIdValidation.value = {
      name: true,
      email: true
    };
  };

  const validateFindIdForm = () => {
    let isValid = true;
    
    // 이름 검증
    if (!findIdForm.value.name.trim()) {
      findIdValidation.value.name = false;
      $toast.error("이름을 입력해주세요.");
      isValid = false;
    } else {
      findIdValidation.value.name = true;
    }
    
    // 이메일 검증
    if (!findIdForm.value.emailLocal.trim() || !findIdForm.value.emailDomain) {
      findIdValidation.value.email = false;
      $toast.error("이메일을 입력해주세요.");
      isValid = false;
    } else {
      findIdValidation.value.email = true;
    }
    
    // 회원 타입 검증
    if (!findIdForm.value.memberType) {
      $toast.error("회원 유형을 선택해주세요.");
      isValid = false;
    }
    
    return isValid;
  };

  const findUserId = async () => {
    if (!validateFindIdForm()) {
      return;
    }
    
    findIdLoading.value = true;
    
    try {
      const fullEmail = `${findIdForm.value.emailLocal}@${findIdForm.value.emailDomain}`;
      const response = await useAxios().post('/auth/findId', {
        name: findIdForm.value.name.trim(),
        email: fullEmail,
        memberType: findIdForm.value.memberType
      });
      
      if (response.data && response.data.userIds) {
        foundUserIds.value = response.data.userIds;
      } else {
        foundUserIds.value = [];
      }
      
      closeFindIdModal();
      showFindIdResultModal.value = true;
      
    } catch (error) {
      console.error('Find ID error:', error);
      if (error.response?.status === 404) {
        foundUserIds.value = [];
        closeFindIdModal();
        showFindIdResultModal.value = true;
      } else {
        $toast.error('아이디 찾기 중 오류가 발생했습니다.');
      }
    } finally {
      findIdLoading.value = false;
    }
  };

  const maskUserId = (userId) => {
    if (!userId || userId.length < 3) {
      return userId;
    }
    
    if (userId.length <= 6) {
      return userId.substring(0, 3) + '*'.repeat(userId.length - 3);
    } else {
      return userId.substring(0, 3) + '*'.repeat(4) + userId.substring(userId.length - 2);
    }
  };

  const getMemberTypeText = (type) => {
    const typeMap = {
      'influence': '인플루언서',
      'vendor': '벤더사', 
      'brand': '브랜드사'
    };
    return typeMap[type] || type;
  };

  const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.getFullYear() + '.' + 
           String(date.getMonth() + 1).padStart(2, '0') + '.' + 
           String(date.getDate()).padStart(2, '0');
  };

  const goToLoginFromModal = () => {
    closeFindIdResultModal();
    // 필요시 특정 아이디를 로그인 폼에 미리 채울 수 있음
  };

  // 비밀번호 찾기 모달 관련 함수들
  const openFindPwModal = () => {
    // URL 파라미터에서 type을 가져와서 회원 유형 설정
    const typeParam = route.query.type;
    if (typeParam && ['influence', 'vendor', 'brand'].includes(typeParam)) {
      findPwForm.value.memberType = typeParam;
    } else {
      findPwForm.value.memberType = loginForm.value.loginType || '';
    }
    showFindPwModal.value = true;
  };

  const closeFindPwModal = () => {
    showFindPwModal.value = false;
    resetFindPwForm();
  };

  const closeChangePwModal = () => {
    showChangePwModal.value = false;
    resetChangePwForm();
    foundUser.value = null;
  };

  const resetFindPwForm = () => {
    // URL 파라미터에서 type을 가져와서 기본값으로 설정
    const typeParam = route.query.type;
    let defaultMemberType = '';
    if (typeParam && ['influence', 'vendor', 'brand'].includes(typeParam)) {
      defaultMemberType = typeParam;
    } else {
      defaultMemberType = loginForm.value.loginType || '';
    }
    
    findPwForm.value = {
      name: '',
      userId: '',
      emailLocal: '',
      emailDomain: null,  // 빈 문자열 대신 null로 설정
      memberType: defaultMemberType
    };
    findPwValidation.value = {
      name: true,
      userId: true,
      email: true
    };
  };

  const resetChangePwForm = () => {
    changePwForm.value = {
      newPassword: '',
      confirmPassword: ''
    };
    changePwValidation.value = {
      newPassword: true,
      confirmPassword: true
    };
    showNewPassword.value = false;
    showConfirmPassword.value = false;
  };

  const validateFindPwForm = () => {
    let isValid = true;
    
    // 이름 검증
    if (!findPwForm.value.name.trim()) {
      findPwValidation.value.name = false;
      $toast.error("이름을 입력해주세요.");
      isValid = false;
    } else {
      findPwValidation.value.name = true;
    }

    // 아이디 검증
    if (!findPwForm.value.userId.trim()) {
      findPwValidation.value.userId = false;
      $toast.error("아이디를 입력해주세요.");
      isValid = false;
    } else {
      findPwValidation.value.userId = true;
    }
    
    // 이메일 검증
    if (!findPwForm.value.emailLocal.trim() || !findPwForm.value.emailDomain) {
      findPwValidation.value.email = false;
      $toast.error("이메일을 입력해주세요.");
      isValid = false;
    } else {
      findPwValidation.value.email = true;
    }
    
    return isValid;
  };

  const validateChangePwForm = () => {
    let isValid = true;
    
    // 새 비밀번호 검증
    if (!changePwForm.value.newPassword.trim()) {
      changePwValidation.value.newPassword = false;
      $toast.error("새 비밀번호를 입력해주세요.");
      isValid = false;
    } else if (changePwForm.value.newPassword.length < 6) {
      changePwValidation.value.newPassword = false;
      $toast.error("비밀번호는 최소 6자 이상 입력해주세요.");
      isValid = false;
    } else {
      changePwValidation.value.newPassword = true;
    }

    // 비밀번호 확인 검증
    if (!changePwForm.value.confirmPassword.trim()) {
      changePwValidation.value.confirmPassword = false;
      $toast.error("비밀번호 확인을 입력해주세요.");
      isValid = false;
    } else if (changePwForm.value.newPassword !== changePwForm.value.confirmPassword) {
      changePwValidation.value.confirmPassword = false;
      $toast.error("비밀번호가 일치하지 않습니다.");
      isValid = false;
    } else {
      changePwValidation.value.confirmPassword = true;
    }
    
    return isValid;
  };

  const findUserPw = async () => {
    if (!validateFindPwForm()) {
      return;
    }
    
    findPwLoading.value = true;
    
    try {
      const fullEmail = `${findPwForm.value.emailLocal}@${findPwForm.value.emailDomain}`;
      const response = await useAxios().post('/auth/findPw', {
        name: findPwForm.value.name.trim(),
        userId: findPwForm.value.userId.trim(),
        email: fullEmail,
        memberType: findPwForm.value.memberType,
        step: 'verify' // 첫 번째 단계: 사용자 확인
      });
      
      if (response.data && response.data.user) {
        foundUser.value = response.data.user;
        closeFindPwModal();
        showChangePwModal.value = true;
      } else {
        $toast.error('입력하신 정보와 일치하는 사용자가 없습니다.');
      }
      
    } catch (error) {
      console.error('Find password error:', error);
      if (error.response?.status === 404) {
        $toast.error('입력하신 정보와 일치하는 사용자가 없습니다.');
      } else {
        $toast.error('비밀번호 찾기 중 오류가 발생했습니다.');
      }
    } finally {
      findPwLoading.value = false;
    }
  };

  const changePassword = async () => {
    if (!validateChangePwForm() || !foundUser.value) {
      return;
    }
    
    changePwLoading.value = true;
    
    try {
      const response = await useAxios().post('/auth/findPw', {
        userId: foundUser.value.userId,
        memberType: foundUser.value.memberType,
        newPassword: changePwForm.value.newPassword,
        step: 'change' // 두 번째 단계: 비밀번호 변경
      });
      
      if (response.data && response.data.status === 'success') {
        $toast.success('비밀번호가 성공적으로 변경되었습니다.');
        closeChangePwModal();
      } else {
        $toast.error('비밀번호 변경에 실패했습니다.');
      }
      
    } catch (error) {
      console.error('Change password error:', error);
      $toast.error('비밀번호 변경 중 오류가 발생했습니다.');
    } finally {
      changePwLoading.value = false;
    }
  };

  const fnLoginSet = (__MSG) => {
    let param = {
      id: pageId,
      title: "로그인",
      content: __MSG,
      yes: {
        text: "확인",
        isProc: true,
        event: "FN_LOGIN",
        param: "",
      },
    };
    $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
  };

  // 구글 로그인 인증 시퀀스
  function onGoogleLogin() {
    const appBaseUrl = import.meta.env.VITE_APP_API_URL;
    const clientId =
      "373780605211-diojebh7mug45urv9rnqdil6n0b1ogge.apps.googleusercontent.com"; // 실제 클라이언트 ID로 교체
    //const redirectUri = "https://shopdeli.mycafe24.com/auth/callback"; // 실제 리디렉션 URI로 교체
    const redirectUri = `${appBaseUrl}/auth/callback`;
    const scope = "openid email profile";
    const responseType = "code"; // 또는 'code' (백엔드 연동 시)
    const state = Math.random().toString(36).substring(2);

    const googleAuthUrl = `https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&client_id=${clientId}&redirect_uri=${encodeURIComponent(
      redirectUri
    )}&response_type=${responseType}&scope=${encodeURIComponent(scope)}&state=${state}`;

    const width = 500;
    const height = 600;
    const dualScreenLeft =
      window.screenLeft !== undefined ? window.screenLeft : window.screenX;
    const dualScreenTop =
      window.screenTop !== undefined ? window.screenTop : window.screenY;

    const currentWidth = window.innerWidth
      ? window.innerWidth
      : document.documentElement.clientWidth
      ? document.documentElement.clientWidth
      : screen.width;

    const currentHeight = window.innerHeight
      ? window.innerHeight
      : document.documentElement.clientHeight
      ? document.documentElement.clientHeight
      : screen.height;

    const left = dualScreenLeft + (currentWidth - width) / 2;
    const top = dualScreenTop + (currentHeight - height) / 2;

    window.open(
      googleAuthUrl,
      "googleLogin",
      `width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`
    );
  }

  //카카오 인증 시퀀스
  function onKakaoLogin() {
    const appBaseUrl = import.meta.env.VITE_APP_API_URL;
    const kakaoAuthUrl = `${appBaseUrl}/auth/kakaoLogin`; // 실제 리디렉션 URI로 교체

    const width = 500;
    const height = 600;
    const dualScreenLeft =
      window.screenLeft !== undefined ? window.screenLeft : window.screenX;
    const dualScreenTop =
      window.screenTop !== undefined ? window.screenTop : window.screenY;

    const currentWidth = window.innerWidth
      ? window.innerWidth
      : document.documentElement.clientWidth
      ? document.documentElement.clientWidth
      : screen.width;

    const currentHeight = window.innerHeight
      ? window.innerHeight
      : document.documentElement.clientHeight
      ? document.documentElement.clientHeight
      : screen.height;

    const left = dualScreenLeft + (currentWidth - width) / 2;
    const top = dualScreenTop + (currentHeight - height) / 2;

    window.open(
      kakaoAuthUrl,
      "kakaoLogin",
      `width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`
    );
  }

  //네이버 인증 시퀀스
  function onNaverLogin() {
    const appBaseUrl = import.meta.env.VITE_APP_API_URL;
    const naverAuthUrl = `${appBaseUrl}/auth/naverLogin`; // 실제 리디렉션 URI로 교체

    const width = 500;
    const height = 600;
    const dualScreenLeft =
      window.screenLeft !== undefined ? window.screenLeft : window.screenX;
    const dualScreenTop =
      window.screenTop !== undefined ? window.screenTop : window.screenY;

    const currentWidth = window.innerWidth
      ? window.innerWidth
      : document.documentElement.clientWidth
      ? document.documentElement.clientWidth
      : screen.width;

    const currentHeight = window.innerHeight
      ? window.innerHeight
      : document.documentElement.clientHeight
      ? document.documentElement.clientHeight
      : screen.height;

    const left = dualScreenLeft + (currentWidth - width) / 2;
    const top = dualScreenTop + (currentHeight - height) / 2;

    window.open(
      naverAuthUrl,
      "naverLogin",
      `width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`
    );
  }

  /**
   * @API
   * 최종 로그인 버튼 클릭 시 API
   */
  function fnLogin(__USERID, __USERPASS) {
    // 파라미터 전달 값 [아이디, 비밀번호, otpNum, 브라우저정보]
    //userId: loginForm.value.userId,
    // let _req = {
    //   username: loginForm.value.userId,
    //   password: btoa(loginForm.value.passwd),
    // };

    localStorage.setItem("tempAccess", __USERID);

    if (__USERID == "admin" && __USERPASS == "1234") {
      useUtil.setPageMove("/view/media/newsList");
    } else {
      fnLoginSet("비밀번호가 맞지 않습니다. 확인해주세요.");
    }
    // useAxios()
    //   .post(apiUrl.otpCheck, _req)
    //   .then((res) => {
    //     loginInfo.value = res.data.data;
    //     useAuthStore().setAccessToken(loginInfo.value.accessToken);
    //     useAuthStore().setRefreshToken(loginInfo.value.refreshToken);

    //     // OTP key체크 성공 후 개인정보에 대한 API를 호출 한다.
    //     fnServiceModeCheck();
    //     $log.debug("[login][fnLogin][success]");
    //   })
    //   .catch((error) => {
    //     $log.debug("[login][fnLogin][error]");
    //     let errorData = error.response.data;
    //     errorData.type = "fnLogin";
    //     fnLoginFail(errorData);
    //   })
    //   .finally(() => {
    //     $log.debug("[login][fnLogin][finished]");
    //   });
  }

  /**
   * @SCRIPT
   * 비밀번호확인 validation
   */
  function fnValidCheck(type) {
    // 아이디 체크
    if (type === "id") {
      const id = loginForm.value.userId;

      // 1. 기본 유효성 검사
      if (!id) {
        $toast.error("아이디를 입력해주세요.");
        return false;
      }

      // 2. 아이디 형식 검사 (영문, 숫자 조합 6~20자)
      const idRegex = /^[a-zA-Z0-9]{6,20}$/;
      if (!idRegex.test(id)) {
        $toast.error("아이디는 영문, 숫자 조합 6~20자로 입력해주세요.");
        return false;
      }
    }

    // 다른 유효성 검사가 필요한 경우 여기에 추가
    return true;
  }
</script>

<style scoped>
/* 게이트 컨테이너 */
.gate-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  min-height: 100vh;
  padding: 2rem;
}

/* 게이트 카드 */
.gate-card {
  background: white;
  border-radius: 20px;
  padding: 2.5rem 2rem;
  text-align: center;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 18rem;
  min-height: 320px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.gate-card:hover {
  transform: translateY(-10px);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
}

.gate-card.actv {
  transform: translateY(-15px) scale(1.05);
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.2);
}

/* 게이트 아이콘 */
.gate-icon {
  margin-bottom: 1.5rem;
}

.icon-circle {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2.5rem;
  margin: 0 auto;
  transition: all 0.3s ease;
}

.influencer-bg {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
}

.vendor-bg {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.brand-bg {
  background: linear-gradient(135deg, #d299c2 0%, #fef9d7 100%);
}

.gate-card:hover .icon-circle {
  transform: scale(1.1);
}

/* 게이트 콘텐츠 */
.gate-content h3 {
  font-size: 1.5rem;
  font-weight: 700;
  color: #333;
  margin-bottom: 0.5rem;
}

.gate-content p {
  color: #666;
  font-size: 1rem;
  margin-bottom: 2rem;
  line-height: 1.5;
}

/* 게이트 버튼 */
.gate-btn {
  border-radius: 25px !important;
  padding: 12px 30px !important;
  font-weight: 600 !important;
  text-transform: none !important;
  transition: all 0.3s ease !important;
  border: none !important;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1) !important;
}

.influencer-btn {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%) !important;
  color: white !important;
}

.vendor-btn {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%) !important;
  color: white !important;
}

.brand-btn {
  background: linear-gradient(135deg, #d299c2 0%, #fef9d7 100%) !important;
  color: white !important;
}

.gate-btn:hover {
  transform: translateY(-2px) !important;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15) !important;
}

/* 반응형 디자인 */
@media (max-width: 768px) {
  .gate-container {
    flex-direction: column;
    gap: 1.5rem;
    padding: 1rem;
  }
  
  .gate-card {
    width: 100%;
    max-width: 300px;
    min-height: 280px;
    padding: 2rem 1.5rem;
  }
  
  .icon-circle {
    width: 60px;
    height: 60px;
    font-size: 2rem;
  }
  
  .gate-content h3 {
    font-size: 1.3rem;
  }
  
  .gate-content p {
    font-size: 0.9rem;
    margin-bottom: 1.5rem;
  }
}

/* 기존 스타일과 충돌 방지 */
.login--gate {
  position: relative;
  z-index: 1;
}

/* 아이디 찾기 모달 스타일 - 고객센터 모달과 동일하게 */
.email-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.email-local {
  flex: 2;
}

.email-at {
  color: #333;
  font-weight: 500;
  margin: 0 4px;
  font-size: 16px;
}

.email-domain {
  flex: 2;
}

/* 결과 모달 스타일 */
.result-success .success-icon,
.result-error .error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.result-success h4,
.result-error h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 1.3rem;
  font-weight: 600;
}

.result-error p {
  color: #666;
  line-height: 1.5;
  margin: 0;
}

.found-ids {
  margin-top: 20px;
  text-align: left;
}

.user-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  border: 1px solid #e9ecef;
}

.user-info:last-child {
  margin-bottom: 0;
}

.user-type {
  color: #666;
  font-size: 12px;
  margin: 0 0 6px 0;
  font-weight: 500;
  text-transform: uppercase;
}

.user-id {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0 0 6px 0;
  letter-spacing: 1px;
  font-family: 'Courier New', monospace;
}

.join-date {
  color: #999;
  font-size: 13px;
  margin: 0;
}

/* 반응형 */
@media (max-width: 768px) {
  .email-input-group {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .email-at {
    text-align: center;
    margin: 0;
  }
  
  .email-local,
  .email-domain {
    flex: 1;
  }
}

/* 비밀번호 변경 모달 스타일 */
.success-message {
  text-align: center;
  background: #f0f9f4;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #d1fae5;
}

.success-message .success-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.success-message p {
  color: #065f46;
  line-height: 1.5;
  margin: 0;
}
</style>
