<script setup lang="ts">
import { ref, onMounted, onActivated, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter, useRoute } from 'vue-router';
import imageCompression from 'browser-image-compression';
import api from '../../api';
import GoldSpinner from '../../components/GoldSpinner.vue';
import { useDepositNotifications } from '../../composables/useDepositNotifications';
import PageBackButton from '../../components/PageBackButton.vue';

const { t } = useI18n();
const router = useRouter();
const route = useRoute();
const { trackPendingOrder } = useDepositNotifications();

const reapplyOrderId = computed(() => {
  const id = route.query.orderId;
  return typeof id === 'string' && id ? id : '';
});
const isReapply = computed(() => !!reapplyOrderId.value);

interface PaymentMethod {
  id: string;
  methodType: string;
  bankName: string | null;
  accountHolder: string | null;
  accountNumber: string | null;
  usdtAddress: string | null;
  qrCodeUrl: string | null;
  displayName: string | null;
}

const methodType = ref<'BANK' | 'USDT'>('BANK');
const methods = ref<PaymentMethod[]>([]);
const selectedMethod = ref<PaymentMethod | null>(null);
const amount = ref<string>('');
const screenshotFile = ref<File | null>(null);
const screenshotPreview = ref<string>('');
const loading = ref(true);
const submitting = ref(false);
const success = ref(false);
const orderNo = ref('');
const compressing = ref(false);

const bankMethods = computed(() => methods.value.filter((m) => m.methodType === 'BANK'));
const usdtMethods = computed(() => methods.value.filter((m) => m.methodType === 'USDT'));
const currentMethods = computed(() => methodType.value === 'BANK' ? bankMethods.value : usdtMethods.value);

function applyReapplyQuery() {
  const type = route.query.methodType;
  if (type === 'BANK' || type === 'USDT') methodType.value = type;
  const methodId = typeof route.query.methodId === 'string' ? route.query.methodId : '';
  if (methodId) {
    const match = methods.value.find((m) => m.id === methodId);
    if (match) selectedMethod.value = match;
  }
  if (!selectedMethod.value && currentMethods.value.length) selectedMethod.value = currentMethods.value[0];
  const amountQuery = typeof route.query.amount === 'string' ? route.query.amount : '';
  const parsedAmount = parseFloat(amountQuery);
  if (amountQuery && parsedAmount > 0) amount.value = amountQuery;
}

async function fetchMethods() {
  loading.value = true;
  try {
    const { data } = await api.get('/player/payment-methods');
    methods.value = (data.data ?? []).map((m: any) => ({ ...m, id: String(m.id) }));
    if (isReapply.value) {
      applyReapplyQuery();
    } else if (currentMethods.value.length) {
      selectedMethod.value = currentMethods.value[0];
    }
  } finally {
    loading.value = false;
  }
}

function selectMethod(m: PaymentMethod) { selectedMethod.value = m; }

function switchType(type: 'BANK' | 'USDT') {
  methodType.value = type;
  selectedMethod.value = currentMethods.value[0] ?? null;
}

async function handleFileChange(e: Event) {
  const file = (e.target as HTMLInputElement).files?.[0];
  if (!file) return;
  try {
    compressing.value = true;
    const compressed = await imageCompression(file, { maxSizeMB: 0.8, maxWidthOrHeight: 1200 });
    screenshotFile.value = compressed;
    screenshotPreview.value = URL.createObjectURL(compressed);
  } catch {
    screenshotFile.value = file;
    screenshotPreview.value = URL.createObjectURL(file);
  } finally {
    compressing.value = false;
  }
}

function clearFile() { screenshotFile.value = null; screenshotPreview.value = ''; }

async function submit() {
  if (!selectedMethod.value || !amount.value || !screenshotFile.value) return;
  submitting.value = true;
  try {
    const fd = new FormData();
    fd.append('paymentMethodId', selectedMethod.value.id);
    fd.append('amount', amount.value);
    fd.append('screenshot', screenshotFile.value);
    if (isReapply.value) fd.append('originalOrderId', reapplyOrderId.value);
    const { data } = await api.post('/player/deposits', fd, { headers: { 'Content-Type': 'multipart/form-data' } });
    orderNo.value = data.data?.orderNo ?? '';
    if (data.data?.id) trackPendingOrder(String(data.data.id));
    success.value = true;
  } catch {
    /* error handled by axios interceptor */
  } finally {
    submitting.value = false;
  }
}

onMounted(fetchMethods);
onActivated(fetchMethods);
</script>

<template>
  <div class="desktop-account-page">
    <main class="account-main">
      <div class="recharge-layout">
        <div class="page-header">
          <PageBackButton fallback="/wallet" />
          <h1 class="page-title">{{ t('recharge.title') }}</h1>
        </div>

        <div v-if="loading" class="loading-state">
          <GoldSpinner :size="36" />
        </div>

        <div v-else-if="success" class="success-card">
          <svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="1.6"><circle cx="12" cy="12" r="9"/><path d="m8 12 3 3 5-5"/></svg>
          <h2>{{ t('recharge.success_title') }}</h2>
          <p class="order-no">{{ t('recharge.order_no') }}: {{ orderNo }}</p>
          <p class="success-hint">{{ t('recharge.success_hint') }}</p>
          <button type="button" class="action-btn" @click="router.push('/wallet/recharge/history')">
            {{ t('recharge.history_title') }}
          </button>
        </div>

        <template v-else>
          <!-- Method type tabs -->
          <div class="type-tabs">
            <button type="button" class="type-tab" :class="{ active: methodType === 'BANK' }" @click="switchType('BANK')">
              {{ t('recharge.bank_transfer') || '银行转账' }}
            </button>
            <button type="button" class="type-tab" :class="{ active: methodType === 'USDT' }" @click="switchType('USDT')">
              USDT
            </button>
          </div>

          <div class="recharge-cols">
          <!-- Method list -->
          <div class="method-list">
            <p class="section-label">{{ t('recharge.choose_method') || '选择收款账户' }}</p>
            <div v-if="currentMethods.length === 0" class="no-methods">
              {{ t('recharge.no_methods') || '暂无可用收款账户' }}
            </div>
            <button
              v-for="m in currentMethods"
              :key="m.id"
              type="button"
              class="method-card"
              :class="{ selected: selectedMethod?.id === m.id }"
              @click="selectMethod(m)"
            >
              <span class="method-name">{{ m.displayName || m.bankName || 'USDT' }}</span>
              <span class="method-account">{{ m.accountNumber || m.usdtAddress || '' }}</span>
            </button>
          </div>

          <!-- Form -->
          <div v-if="selectedMethod" class="recharge-form">
            <!-- Bank details -->
            <div v-if="methodType === 'BANK'" class="bank-detail-card">
              <div class="detail-row">
                <span class="detail-label">{{ t('recharge.bank_name') || '银行名称' }}</span>
                <span class="detail-val">{{ selectedMethod.bankName }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">{{ t('recharge.account_holder') || '持卡人' }}</span>
                <span class="detail-val">{{ selectedMethod.accountHolder }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">{{ t('recharge.account_number') || '账号' }}</span>
                <span class="detail-val mono">{{ selectedMethod.accountNumber }}</span>
              </div>
            </div>

            <!-- USDT QR -->
            <div v-if="methodType === 'USDT' && selectedMethod.qrCodeUrl" class="qr-wrap">
              <img :src="selectedMethod.qrCodeUrl" alt="USDT QR" class="qr-img" />
            </div>
            <div v-if="methodType === 'USDT'" class="detail-row">
              <span class="detail-label">{{ t('recharge.usdt_address') || 'USDT地址' }}</span>
              <span class="detail-val mono break-all">{{ selectedMethod.usdtAddress }}</span>
            </div>

            <!-- Amount input -->
            <div class="field">
              <label class="field-label">{{ t('recharge.amount') || '充值金额' }}</label>
              <input
                v-model="amount"
                type="number"
                min="0"
                class="field-input"
                :placeholder="t('recharge.amount_placeholder') || '请输入金额'"
              />
            </div>

            <!-- Screenshot upload -->
            <div class="field">
              <label class="field-label">{{ t('recharge.screenshot') || '上传凭证截图' }}</label>
              <div v-if="screenshotPreview" class="preview-wrap">
                <img :src="screenshotPreview" alt="preview" class="preview-img" />
                <button type="button" class="clear-btn" @click="clearFile">✕</button>
              </div>
              <label v-else class="upload-zone">
                <input type="file" accept="image/*" class="hidden-input" @change="handleFileChange" />
                <GoldSpinner v-if="compressing" :size="24" />
                <template v-else>
                  <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" opacity="0.5"><path d="M4 17v1a2 2 0 002 2h12a2 2 0 002-2v-1M12 3v12M8 7l4-4 4 4"/></svg>
                  <span class="upload-hint">{{ t('recharge.click_to_upload') || '点击上传截图' }}</span>
                </template>
              </label>
            </div>

            <button
              type="button"
              class="submit-btn"
              :disabled="submitting || !amount || !screenshotFile"
              @click="submit"
            >
              <GoldSpinner v-if="submitting" :size="18" />
              <span v-else>{{ t('recharge.submit') || '提交充值' }}</span>
            </button>
          </div>
        </div>
      </template>
      </div>
    </main>
  </div>
</template>

<style scoped>
.desktop-account-page { display: flex; flex-direction: column; min-height: 0; flex: 1; width: 100%; }

.recharge-layout {
  display: flex;
  flex-direction: column;
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
}

.account-main {
  flex: 1;
  min-width: 0;
  padding: 24px 28px;
  overflow-y: auto;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: 800;
  color: var(--primary-light);
  margin: 0;
  letter-spacing: 0.02em;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 80px 0;
}

.success-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 14px;
  padding: 60px 20px;
  text-align: center;
}

.success-card h2 {
  font-size: 20px;
  font-weight: 800;
  color: var(--primary-light);
  margin: 0;
}

.order-no {
  font-size: 13px;
  color: var(--text-muted);
  margin: 0;
  font-weight: 700;
}

.success-hint {
  font-size: 13px;
  color: var(--text-muted);
  margin: 0;
}

.action-btn {
  padding: 9px 24px;
  border-radius: 6px;
  background: var(--primary);
  color: var(--bg-card);
  font-size: 13px;
  font-weight: 800;
  border: none;
  cursor: pointer;
  transition: opacity 0.2s;
  text-decoration: none;
  display: inline-block;
}

.action-btn:hover { opacity: 0.88; }

.type-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
}

.type-tab {
  padding: 6px 20px;
  border-radius: 6px;
  border: 1px solid var(--desktop-border);
  background: transparent;
  color: var(--text-muted);
  font-size: 13px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.2s;
}

.type-tab.active {
  border-color: var(--border-active);
  color: var(--primary-light);
  background: rgba(0, 102, 204,0.08);
}

.recharge-cols {
  display: grid;
  grid-template-columns: 240px 1fr;
  gap: 24px;
  align-items: start;
  max-width: 800px;
  margin: 0 auto;
}

.section-label {
  font-size: 11px;
  font-weight: 700;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: 0.06em;
  margin: 0 0 10px;
}

.no-methods {
  font-size: 13px;
  color: var(--text-muted);
  padding: 12px 0;
}

.method-list {
  display: flex;
  flex-direction: column;
}

.method-card {
  display: flex;
  flex-direction: column;
  padding: 12px 16px;
  border-radius: 8px;
  border: 1px solid var(--desktop-border);
  background: var(--bg-card);
  backdrop-filter: blur(12px);
  cursor: pointer;
  margin-bottom: 8px;
  text-align: left;
  transition: all 0.2s;
}

.method-card:hover { border-color: rgba(0, 0, 0, 0.08); }

.method-card.selected {
  border-color: var(--border-active);
  background: rgba(0, 102, 204,0.06);
}

.method-name {
  font-size: 13px;
  font-weight: 800;
  color: var(--text);
}

.method-account {
  font-size: 11px;
  color: var(--text-muted);
}

.recharge-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.bank-detail-card {
  background: var(--bg-card);
  backdrop-filter: blur(12px);
  border: 1px solid rgba(0, 0, 0, 0.04);
  border-radius: 8px;
  padding: 16px 18px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.detail-row {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.detail-label {
  width: 80px;
  flex-shrink: 0;
  font-size: 11px;
  font-weight: 700;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: 0.05em;
  padding-top: 1px;
}

.detail-val {
  flex: 1;
  font-size: 13px;
  font-weight: 700;
  color: var(--text);
}

.mono { font-family: 'SF Mono', 'Consolas', monospace; letter-spacing: 0.04em; }
.break-all { word-break: break-all; }

.qr-wrap {
  display: flex;
  justify-content: center;
  padding: 12px 0;
}

.qr-img {
  width: 140px;
  height: 140px;
  object-fit: contain;
  border-radius: 8px;
  border: 1px solid var(--desktop-border);
}

.field {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.field-label {
  font-size: 12px;
  font-weight: 700;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: 0.06em;
}

.field-input {
  padding: 10px 14px;
  border-radius: 6px;
  border: 1px solid var(--desktop-border);
  background: var(--bg-card);
  color: var(--text);
  font-size: 14px;
  font-weight: 700;
  outline: none;
  transition: border-color 0.2s;
  max-width: 320px;
}

.field-input:focus { border-color: var(--border-active); }

.preview-wrap {
  position: relative;
  display: inline-block;
}

.preview-img {
  max-width: 180px;
  max-height: 180px;
  border-radius: 8px;
  border: 1px solid var(--desktop-border);
  object-fit: cover;
  display: block;
}

.clear-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  background: var(--bg-hover);
  border: none;
  color: var(--text-muted);
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-zone {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 180px;
  height: 120px;
  border: 2px dashed var(--desktop-border);
  border-radius: 8px;
  cursor: pointer;
  transition: border-color 0.2s;
}

.upload-zone:hover { border-color: var(--border-active); }

.hidden-input { display: none; }

.upload-hint {
  font-size: 12px;
  color: var(--text-muted);
  font-weight: 600;
}

.submit-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 11px 32px;
  border-radius: 6px;
  background: var(--primary);
  color: var(--bg-card);
  font-size: 14px;
  font-weight: 800;
  border: none;
  cursor: pointer;
  transition: opacity 0.2s;
  align-self: flex-start;
}

.submit-btn:hover:not(:disabled) { opacity: 0.88; }
.submit-btn:disabled { opacity: 0.45; cursor: default; }
</style>
