<template>
  <div class="login-wrap">
    <!-- <div class="login--gate" v-show="loginVisible == 'Y'">
      <div
        class="inf--gate"
        :class="gate1 ? 'actv' : ''"
        @mousemove.stop="handleInfluenceMove"
      >        
        <div class="btn--contents">
          <h2>influence</h2>
          <v-btn class="loc--btn" @click.stop="location('influence')"
            >Discover more ></v-btn
          >
        </div>
      </div>
      <div
        class="ven--gate"
        :class="gate2 ? 'actv' : ''"
        @mousemove.stop="handleVendorMove"
      >        
        <div class="btn--contents">
          <h2>vendor</h2>
          <v-btn class="loc--btn" @click.stop="location('vendor')">Discover more ></v-btn>
        </div>
      </div>
    </div>

    <div class="login--cock" v-show="loginVisible == 'N'">
     -->

    <div class="login--cock">
      <!-- header -->
      <div class="login--header">
        <div class="login--header--l">
          <div class="logo">
            <!-- prettier-ignore  -->
            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>로그인</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)"
                @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)"
                @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
              class="custom-btn btn-blue"
              @keyup.enter="loginAction(loginForm.userId, loginForm.passwd)"
              @click="loginAction(loginForm.userId, loginForm.passwd)"
              >로그인</v-btn
            >
          </div>
          <div class="join--btn--wrap">
            <v-btn class="custom-btn text--btn">아이디 찾기</v-btn>
            <v-btn class="custom-btn text--btn">비밀번호 찾기</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'"> -->
          <div class="short--login--wrap">
            <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>
  </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 loginVisible = ref("N");

  const i18n = useI18n();
  // 다국어
  let listObj = ref({
    langTypeList: {},
  });

  const handleInfluenceMove = (event) => {
    const el = event.currentTarget;
    const rect = el.getBoundingClientRect();
    const mouseX = event.clientX;

    // 요소 너비의 15%를 좌우 여백으로 계산 (중앙 70% 영역)
    const margin = rect.width * 0.15;
    const leftBound = rect.left + margin;
    const rightBound = rect.right - margin;

    if (mouseX >= leftBound && mouseX <= rightBound) {
      gate1.value = true;
      gate2.value = false;
    } else {
      gate1.value = false;
    }
  };

  const handleVendorMove = (event) => {
    const el = event.currentTarget;
    const rect = el.getBoundingClientRect();
    const mouseX = event.clientX;

    // 요소 너비의 15%를 좌우 여백으로 계산 (중앙 70% 영역)
    const margin = rect.width * 0.15;
    const leftBound = rect.left + margin;
    const rightBound = rect.right - margin;

    if (mouseX >= leftBound && mouseX <= rightBound) {
      gate2.value = true;
      gate1.value = false;
    } else {
      gate2.value = false;
    }
  };

  // 로그인 정보
  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 findId = ref({
    popYn: false,
    //tenantName: '',
    email: "",
    otpNum: "",
    validCheck: {
      input: {
        //tenantName: true,
        email: true,
      },
      otp: {
        otpNum: true,
      },
      inputErrorCheck: true,
      inputValidTxt: "",
      otpValidTxt: "",
      findIdValidCheck: false,
    },
    btnTxt: "",
  });
  // 비밀번호 초기화
  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 privacyPop = ref(false);
  const privacyDetail = ref({
    kr: {
      title: "",
      contents: "",
    },
    en: {
      title: "",
      contents: "",
    },
  });
  const systemInfo = ref({
    mode: "",
  });

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

    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);
          localStorage.setItem("tempAccess", __ID);
          useUtil.setPageMove("/view/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 = "N";
        break;
      case "vendor":
        useUtil.setPageMove("/?type=vendor");
        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 {
      loginVisible.value = "Y";
    }

    //구글 인증 프로세스
    function handleMessage(event) {
      const appBaseUrl = import.meta.env.VITE_APP_BASE_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");
        } else {
          //useAuthStore().setAuth(res.data);

          const result = {
            refreshToken: refreshToken,
            user: user,
          };

          //console.log(result);

          //return;

          useAuthStore().setTempData(result);
          useAuthStore().setAccessToken(accessToken);
          useAuthStore().setRefreshToken(refreshToken);
          localStorage.setItem("tempAccess", result.user);
          useUtil.setPageMove("/view/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") {
        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 fnLoginSet = (__MSG) => {
    let param = {
      id: pageId,
      title: "로그인",
      content: __MSG,
      yes: {
        text: "확인",
        isProc: true,
        event: "FN_LOGIN",
        param: "",
      },
      no: {
        text: "취소",
        isProc: false,
      },
    };
    $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
  };

  // 구글 로그인 인증 시퀀스
  function onGoogleLogin() {
    const appBaseUrl = import.meta.env.VITE_APP_API_DOMAIN;
    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_DOMAIN;
    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_BASE_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>
