<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { showToast, showDialog } from "vant";

import { fetchListing, type Listing } from "@/features/listings/api/listings";
import { createOrder, fetchOrderAgreements, type OrderAgreements } from "@/features/orders/api/orders";
import { useSessionStore } from "@/stores/session";
import { formatMoney } from "@/shared/utils/money";
import {
  assetRegions,
  formatHafCoinM,
  formatRatio,
  getCoinWan,
  getDailyLoss,
  getListingConsumablePrice,
  getListingChips,
  getListingDisplayPrice,
  getListingRentPrice,
  getListingResources,
  getListingSubtitle,
  getListingTitle,
  getLoginMethod,
  getServerRegion,
  readAssetString,
} from "@/utils/listingDisplay";

const route = useRoute();
const router = useRouter();
const session = useSessionStore();
const loading = ref(false);
const ordering = ref(false);
const agreementsLoading = ref(false);
const agreementVisible = ref(false);
const listing = ref<Listing | null>(null);
const agreements = ref<OrderAgreements | null>(null);
const virtualAgreementRead = ref(false);
const renterAgreementRead = ref(false);
const virtualAgreementChecked = ref(false);
const renterAgreementChecked = ref(false);
const virtualAgreementRef = ref<HTMLElement | null>(null);
const renterAgreementRef = ref<HTMLElement | null>(null);

const canCreateOrderAfterAgreement = computed(
  () =>
    virtualAgreementRead.value &&
    renterAgreementRead.value &&
    virtualAgreementChecked.value &&
    renterAgreementChecked.value,
);

onMounted(async () => {
  loading.value = true;
  try {
    listing.value = await fetchListing(String(route.params.id));
  } catch {
    showToast({ message: "加载失败", icon: "warning-o" });
  } finally {
    loading.value = false;
  }
});

const orderTotal = computed(() => {
  if (!listing.value) return "0.0";
  return formatMoney(getListingDisplayPrice(listing.value));
});

const orderPriceBreakdown = computed(() => {
  if (!listing.value) {
    return {
      rent: 0,
      consumable: 0,
    };
  }
  return {
    rent: getListingRentPrice(listing.value),
    consumable: getListingConsumablePrice(listing.value),
  };
});

const detailMetrics = computed(() => {
  if (!listing.value) return [];
  const dailyLoss = getDailyLoss(listing.value);
  return [
    { label: "纯币", value: formatHafCoinM(getCoinWan(listing.value)), tone: "coin" },
    {
      label: "日损耗",
      value: dailyLoss ? `${dailyLoss}/天` : "--",
      tone: "coin",
    },
    { label: "价格", value: `¥${getListingDisplayPrice(listing.value)}`, tone: "price" },
    { label: "押金", value: `¥${listing.value.deposit_amount}`, tone: "" },
  ];
});

const detailScreenshots = computed(() => {
  if (!listing.value) return [];
  const labels = ["纯币截图", "游戏ID截图", "总资产截图", "腾讯安全中心截图", "皮肤截图"];
  return (listing.value.screenshot_urls || []).map((url, index) => ({
    label: labels[index] || `账号截图${index + 1}`,
    url,
  }));
});

const detailSkinGroups = computed(() => {
  if (!listing.value) return [];
  const groups = listing.value.asset_summary?.skin_groups;
  if (typeof groups !== "object" || groups === null) return [];
  const titles: Record<string, string> = {
    melee: "近战皮肤",
    operator: "干员皮肤",
    operatorGold: "干员金皮",
    operatorRed: "干员红皮",
    weapon: "武器皮肤",
  };
  return Object.entries(groups as Record<string, unknown>)
    .map(([key, value]) => ({
      key,
      title: titles[key] || key,
      options: Array.isArray(value)
        ? value.filter((skin): skin is string => typeof skin === "string")
        : [],
    }))
    .filter((group) => group.options.length);
});

/* 下单 */
async function handleCreateOrder() {
  if (!listing.value) return;

  if (!session.token) {
    showDialog({
      title: "请先登录",
      message: "下单需要登录账号，是否前往登录？",
      confirmButtonText: "去登录",
      cancelButtonText: "取消",
      showCancelButton: true,
    }).then(() => {
      router.push({ path: "/m/login", query: { redirect: route.fullPath } });
    });
    return;
  }

  if (session.realnameStatus !== "verified") {
    try {
      await session.loadMe();
    } catch {
      // 401 会由全局拦截器处理。
    }
  }

  if (session.realnameStatus !== "verified") {
    showDialog({
      title: "请先实名认证",
      message: "租号下单前需要完成实名认证。",
      confirmButtonText: "去认证",
      cancelButtonText: "取消",
      showCancelButton: true,
    }).then(() => {
      router.push({ path: "/m/realname", query: { redirect: route.fullPath } });
    });
    return;
  }

  await openAgreementBeforeOrder();
}

async function openAgreementBeforeOrder() {
  agreementsLoading.value = true;
  try {
    agreements.value = await fetchOrderAgreements();
    virtualAgreementRead.value = false;
    renterAgreementRead.value = false;
    virtualAgreementChecked.value = false;
    renterAgreementChecked.value = false;
    agreementVisible.value = true;
    await nextTick();
    updateAgreementReadState("virtual");
    updateAgreementReadState("renter");
  } catch (error) {
    showToast({ message: readError(error, "协议加载失败"), icon: "cross" });
  } finally {
    agreementsLoading.value = false;
  }
}

async function handleConfirmAgreementAndCreateOrder() {
  if (!canCreateOrderAfterAgreement.value) {
    showToast("请先阅读并勾选两份协议");
    return;
  }
  agreementVisible.value = false;
  await submitOrder();
}

async function submitOrder() {
  if (!listing.value) return;
  ordering.value = true;
  try {
    await createOrder(listing.value.id);
    showToast({ message: "订单已创建，请完成支付", icon: "passed" });
    await router.push(`/m/orders`);
  } catch (error) {
    showToast({ message: readError(error, "下单失败"), icon: "cross" });
  } finally {
    ordering.value = false;
  }
}

function handleAgreementScroll(type: "virtual" | "renter") {
  updateAgreementReadState(type);
}

function updateAgreementReadState(type: "virtual" | "renter") {
  const el = type === "virtual" ? virtualAgreementRef.value : renterAgreementRef.value;
  if (!el) return;
  const read = el.scrollTop + el.clientHeight >= el.scrollHeight - 8;
  if (type === "virtual") {
    virtualAgreementRead.value = read;
  } else {
    renterAgreementRead.value = read;
  }
}

function readError(error: unknown, fallback: string) {
  if (typeof error === "object" && error && "response" in error) {
    const response = (error as { response?: { data?: { message?: string } } })
      .response;
    return response?.data?.message || fallback;
  }
  return fallback;
}

/** 判断当前底部导航是否激活 */
function isNavActive(path: string) {
  if (path === "/m") return route.path === "/m";
  return route.path.startsWith(path);
}
</script>

<template>
  <main class="mobile-detail">
    <!-- 顶部导航 -->
    <header class="page-header">
      <button class="back-btn" @click="router.back()">
        <van-icon name="arrow-left" :size="20" />
      </button>
      <h1>账号详情</h1>
      <span class="header-spacer"></span>
    </header>

    <van-loading v-if="loading" class="center-loading" size="24px" vertical>
      加载中...
    </van-loading>

    <template v-else-if="listing">
      <!-- 防骗提示 -->
      <div class="fraud-tip">
        <van-icon name="shield-o" :size="14" color="#ff9800" />
        <span
          >防骗提示：下单后请按平台交接流程确认收号与归还，不要私下交易。</span
        >
      </div>

      <!-- 封面图 -->
      <div class="cover-area">
        <img
          v-if="detailScreenshots[0]?.url"
          :src="detailScreenshots[0].url"
          :alt="getListingTitle(listing)"
          class="cover-img"
          decoding="async"
        />
        <div v-else class="cover-placeholder">
          <van-icon name="photo-o" :size="40" color="#ccc" />
          <span>暂无截图</span>
        </div>
        <!-- 截图指示器 -->
        <div
          v-if="detailScreenshots.length > 1"
          class="cover-count"
        >
          {{ detailScreenshots.length }}张
        </div>
      </div>

      <!-- 标题信息 -->
      <div class="info-card">
        <div class="info-tag-row">
          <van-tag plain type="primary" size="medium">{{
            getServerRegion(listing)
          }}</van-tag>
          <van-tag v-if="getLoginMethod(listing)" plain type="primary" size="medium">
            {{ getLoginMethod(listing) }}
          </van-tag>
          <van-tag v-if="listing.rank_level" plain size="medium">{{
            listing.rank_level
          }}</van-tag>
        </div>
        <h2 class="detail-title">{{ getListingTitle(listing) }}</h2>
        <p class="detail-desc">{{ getListingSubtitle(listing) }}</p>
      </div>

      <!-- 资产指标 -->
      <div class="metric-row">
        <div v-for="metric in detailMetrics" :key="metric.label" class="metric-item">
          <span class="metric-label">{{ metric.label }}</span>
          <strong class="metric-value" :class="metric.tone">{{ metric.value }}</strong>
        </div>
      </div>

      <!-- 基础信息 -->
      <div class="info-card">
        <h3 class="card-subtitle">账号资料</h3>
        <div class="detail-chip-row">
          <span
            v-for="chip in getListingChips(listing)"
            :key="chip.label"
          >
            {{ chip.label }}:{{ chip.value }}
          </span>
        </div>
        <div class="info-line">
          <span class="info-label">M单价</span>
          <span class="info-text">{{ formatRatio(listing) }}</span>
        </div>
        <div class="info-line">
          <span class="info-label">常用登录地</span>
          <span class="info-text">{{ assetRegions(listing).join("、") || "--" }}</span>
        </div>
        <div v-if="readAssetString(listing, 'ban_record')" class="info-line">
          <span class="info-label">封禁记录</span>
          <span class="info-text">{{ readAssetString(listing, "ban_record") }}</span>
        </div>
      </div>

      <div v-if="getListingResources(listing).length" class="info-card">
        <h3 class="card-subtitle">额外消耗品</h3>
        <div class="resource-grid">
          <div
            v-for="resource in getListingResources(listing)"
            :key="resource.key"
            class="resource-pill"
          >
            <span>{{ resource.label }}</span>
            <strong>{{ resource.quantity }}</strong>
            <em>
              <b>{{ resource.mode || "--" }}</b>
              <small v-if="resource.amount > 0">¥{{ resource.amount }}</small>
              <small v-else-if="resource.mode === '收费'">{{ resource.price || "¥0" }}</small>
              <small v-else>无额外收费</small>
            </em>
          </div>
        </div>
      </div>

      <div v-if="detailSkinGroups.length" class="info-card">
        <h3 class="card-subtitle">皮肤</h3>
        <div v-for="group in detailSkinGroups" :key="group.key" class="skin-detail-group">
          <p>{{ group.title }}</p>
          <div class="detail-chip-row">
            <span v-for="skin in group.options" :key="skin">{{ skin }}</span>
          </div>
        </div>
      </div>

      <div v-if="listing.description" class="info-card">
        <h3 class="card-subtitle">备注</h3>
        <p class="detail-desc">{{ listing.description }}</p>
      </div>

      <!-- 截图列表 -->
      <div v-if="detailScreenshots.length" class="info-card">
        <h3 class="card-subtitle">账号截图</h3>
        <div class="screenshot-grid">
          <figure v-for="shot in detailScreenshots" :key="shot.url" class="screenshot-item">
            <img :src="shot.url" class="screenshot-thumb" loading="lazy" decoding="async" />
            <figcaption>{{ shot.label }}</figcaption>
          </figure>
        </div>
      </div>

      <!-- 留白给底部下单栏 -->
      <div class="bottom-spacer"></div>

      <!-- 底部下单栏（固定） -->
      <div class="order-bar">
        <div class="order-bar-left">
          <div class="order-price">
            <span class="price-label">价格</span>
            <span class="price-amount">¥{{ orderTotal }}</span>
          </div>
          <div class="order-price-detail">
            <span>租金 ¥{{ orderPriceBreakdown.rent }}</span>
            <span>额外 ¥{{ orderPriceBreakdown.consumable }}</span>
          </div>
        </div>
        <van-button
          type="primary"
          round
          class="order-btn"
          :loading="ordering || agreementsLoading"
          :disabled="listing.in_transaction"
          loading-text="下单中..."
          @click="handleCreateOrder"
        >
          {{ listing.in_transaction ? "交易中" : "立即下单" }}
        </van-button>
      </div>

      <van-popup v-model:show="agreementVisible" round closeable position="bottom" lock-scroll class="agreement-popup">
        <div v-if="agreements" class="agreement-popup-body">
          <h3>下单协议确认</h3>
          <p>请完整阅读并勾选以下两份协议后继续下单。</p>
          <section class="agreement-panel">
            <strong>{{ agreements.virtual_asset_purchase.title }}</strong>
            <div
              ref="virtualAgreementRef"
              class="agreement-content"
              @scroll="handleAgreementScroll('virtual')"
            >
              {{ agreements.virtual_asset_purchase.content }}
            </div>
            <van-checkbox v-model="virtualAgreementChecked" :disabled="!virtualAgreementRead" icon-size="18px">
              我已阅读并同意《{{ agreements.virtual_asset_purchase.title }}》
            </van-checkbox>
            <span v-if="!virtualAgreementRead" class="agreement-read-hint">请下拉阅读至底部</span>
          </section>
          <section class="agreement-panel">
            <strong>{{ agreements.renter_agreement.title }}</strong>
            <div
              ref="renterAgreementRef"
              class="agreement-content"
              @scroll="handleAgreementScroll('renter')"
            >
              {{ agreements.renter_agreement.content }}
            </div>
            <van-checkbox v-model="renterAgreementChecked" :disabled="!renterAgreementRead" icon-size="18px">
              我已阅读并同意《{{ agreements.renter_agreement.title }}》
            </van-checkbox>
            <span v-if="!renterAgreementRead" class="agreement-read-hint">请下拉阅读至底部</span>
          </section>
          <van-button
            block
            round
            type="primary"
            class="agreement-confirm-btn"
            :loading="ordering"
            :disabled="!canCreateOrderAfterAgreement"
            @click="handleConfirmAgreementAndCreateOrder"
          >
            同意协议并下单
          </van-button>
        </div>
      </van-popup>
    </template>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <van-icon name="info-o" :size="48" color="#ccc" />
      <p>未找到该账号信息</p>
    </div>
  </main>
</template>

<style scoped>
.mobile-detail {
  min-height: 100dvh;
  background: #f5f7fa;
  padding-bottom: calc(80px + env(safe-area-inset-bottom));
}

/* ========== 顶部导航 ========== */
.page-header {
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  height: 48px;
  padding: 0 12px;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.page-header h1 {
  flex: 1;
  margin: 0;
  font-size: 17px;
  font-weight: 700;
  text-align: center;
}

.back-btn {
  display: grid;
  width: 36px;
  height: 36px;
  place-items: center;
  border: none;
  background: none;
  color: #333;
  cursor: pointer;
}

.header-spacer {
  width: 36px;
}

.center-loading {
  display: flex;
  justify-content: center;
  padding: 60px 0;
}

/* ========== 防骗提示 ========== */
.fraud-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: #fff8e1;
  font-size: 11px;
  color: #e65100;
  line-height: 1.4;
}

/* ========== 封面图 ========== */
.cover-area {
  position: relative;
  width: 100%;
  aspect-ratio: 16 / 9;
  background: #e8e8e8;
  overflow: hidden;
}

.cover-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 6px;
  color: #999;
  font-size: 12px;
}

.cover-count {
  position: absolute;
  right: 10px;
  bottom: 10px;
  padding: 2px 8px;
  border-radius: 8px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 11px;
}

/* ========== 信息卡片 ========== */
.info-card {
  margin: 10px 12px;
  padding: 14px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.info-tag-row {
  display: flex;
  gap: 6px;
  margin-bottom: 8px;
}

.detail-title {
  margin: 0 0 6px;
  font-size: 20px;
  font-weight: 700;
  color: #1a1a1a;
  line-height: 1.35;
}

.detail-desc {
  margin: 0;
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

/* ========== 资产指标 ========== */
.metric-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
  padding: 0 12px;
}

.metric-item {
  background: #fff;
  border-radius: 10px;
  padding: 10px 6px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.metric-label {
  display: block;
  font-size: 11px;
  color: #999;
  margin-bottom: 4px;
}

.metric-value {
  display: block;
  overflow: hidden;
  font-size: 15px;
  color: #1a1a1a;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.metric-value.coin {
  color: #1477ff;
}

.metric-value.price {
  color: #ff5f00;
}

/* ========== 账号资料 ========== */
.info-line {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f5f5f5;
  font-size: 13px;
}

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

.info-label {
  color: #999;
}

.info-text {
  color: #333;
  font-weight: 500;
}

/* ========== 截图列表 ========== */
.card-subtitle {
  margin: 0 0 10px;
  font-size: 14px;
  font-weight: 700;
}

.detail-chip-row {
  display: flex;
  flex-wrap: wrap;
  gap: 7px;
  margin-bottom: 10px;
}

.detail-chip-row span {
  display: inline-flex;
  align-items: center;
  min-height: 28px;
  border: 1px solid #ff8a1f;
  border-radius: 5px;
  color: #ff7900;
  padding: 0 7px;
  font-size: 12px;
  font-weight: 800;
}

.resource-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 8px;
}

.resource-pill {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: 4px 8px;
  border-radius: 8px;
  background: #f7f9fc;
  padding: 10px;
}

.resource-pill span {
  min-width: 0;
  color: #5f6b7a;
  font-size: 12px;
  font-weight: 700;
}

.resource-pill strong {
  color: #17233d;
  font-size: 14px;
}

.resource-pill em {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 6px;
  grid-column: 1 / -1;
  font-size: 11px;
  font-style: normal;
  font-weight: 800;
}

.resource-pill em b {
  color: #ff7900;
}

.resource-pill em small {
  min-width: 0;
  color: #17233d;
  font-size: 11px;
  font-weight: 800;
  text-align: right;
}

.skin-detail-group + .skin-detail-group {
  margin-top: 12px;
}

.skin-detail-group p {
  margin: 0 0 8px;
  color: #5f6b7a;
  font-size: 12px;
  font-weight: 900;
}

.screenshot-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}

.screenshot-item {
  margin: 0;
}

.screenshot-thumb {
  width: 100%;
  aspect-ratio: 4 / 3;
  object-fit: cover;
  border-radius: 8px;
  cursor: pointer;
}

.screenshot-item figcaption {
  margin-top: 4px;
  color: #6b7280;
  font-size: 11px;
  font-weight: 700;
  text-align: center;
}

/* ========== 底部留白 ========== */
.bottom-spacer {
  height: 20px;
}

/* ========== 底部下单栏 ========== */
.order-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px calc(8px + env(safe-area-inset-bottom));
  background: #fff;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.04);
}

.order-bar-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.order-price {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.price-label {
  font-size: 11px;
  color: #999;
}

.price-amount {
  font-size: 18px;
  font-weight: 900;
  color: #ff5f00;
}

.order-price-detail {
  display: flex;
  flex-wrap: wrap;
  gap: 4px 8px;
  color: #8a5a12;
  font-size: 10px;
  font-weight: 700;
  line-height: 1.3;
}

.order-btn {
  flex-shrink: 0;
  padding: 0 20px;
  height: 40px;
  font-size: 14px;
  font-weight: 700;
  background: #ff6a00 !important;
  border: none !important;
}

.agreement-popup {
  max-height: 92vh;
}

.agreement-popup-body {
  display: grid;
  gap: 12px;
  max-height: 92vh;
  overflow: auto;
  padding: 20px 16px calc(16px + env(safe-area-inset-bottom));
}

.agreement-popup-body h3 {
  margin: 0;
  color: #17233d;
  font-size: 18px;
  font-weight: 900;
}

.agreement-popup-body > p {
  margin: 0;
  color: #6b7280;
  font-size: 13px;
  font-weight: 700;
}

.agreement-panel {
  display: grid;
  gap: 8px;
}

.agreement-panel > strong {
  color: #17233d;
  font-size: 14px;
}

.agreement-content {
  height: 190px;
  overflow: auto;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: #f8fafc;
  padding: 12px;
  color: #1f2937;
  font-size: 12px;
  font-weight: 700;
  line-height: 1.7;
  white-space: pre-wrap;
}

.agreement-read-hint {
  color: #ff6a00;
  font-size: 12px;
  font-weight: 800;
}

.agreement-confirm-btn {
  margin-top: 4px;
  background: #ff6a00 !important;
  border: none !important;
  font-weight: 800;
}

/* ========== 空状态 ========== */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 80px 0;
  color: #999;
  font-size: 14px;
}
</style>
