<template>
  <div class="shop-wrap">
    <header class="shop-header">
      <h1 class="shop-title">포인트 상점</h1>
    </header>

    <div v-if="loading" class="shop-loading">불러오는 중…</div>

    <template v-else>
      <!-- 포인트 잔액 -->
      <section class="points-bar">
        <span class="points-label">보유 포인트</span>
        <span class="points-value">{{ points.toLocaleString('ko-KR') }} P</span>
      </section>

      <!-- 유료 회원 안내 -->
      <div v-if="isPremium" class="premium-notice">
        유료 멤버십 이용 중 — 모든 기능 무제한 사용 가능합니다.<br>
        포인트 상점 아이템은 무료 회원 전용입니다.
      </div>

      <!-- 상품 목록 -->
      <section v-else class="product-list">
        <!-- 추가 계좌 슬롯 -->
        <div class="product-card">
          <div class="product-icon">🏦</div>
          <div class="product-info">
            <div class="product-name">추가 계좌 슬롯</div>
            <div class="product-desc">
              무료 회원은 종류별 계좌 2개까지 등록 가능합니다.<br>
              슬롯 1개 구매 시 모든 종류에 +1개 추가 (최대 3개 구매 가능).
            </div>
            <div class="product-status">
              보유 슬롯: <strong>{{ status.extraWalletSlots }}</strong> / {{ status.maxExtraSlots }}
            </div>
          </div>
          <div class="product-buy">
            <div class="product-price">{{ status.walletSlotPrice.toLocaleString('ko-KR') }} P</div>
            <button
              type="button"
              class="buy-btn"
              :disabled="status.extraWalletSlots >= status.maxExtraSlots || buying === 'WALLET_SLOT'"
              @click="buy('WALLET_SLOT')"
            >
              <template v-if="status.extraWalletSlots >= status.maxExtraSlots">최대 구매</template>
              <template v-else-if="buying === 'WALLET_SLOT'">구매 중…</template>
              <template v-else>구매</template>
            </button>
          </div>
        </div>

        <!-- AI 통계 분석 -->
        <div class="product-card">
          <div class="product-icon">✨</div>
          <div class="product-info">
            <div class="product-name">AI 통계 분석 {{ status.aiStatPackSize }}회</div>
            <div class="product-desc">
              통계 화면에서 AI 재무 코멘트를 받을 수 있습니다.<br>
              {{ status.aiStatPackSize }}회 이용권 구매 (소진 후 재구매 가능).
            </div>
            <div class="product-status">
              남은 이용권: <strong>{{ status.aiStatCredits }}</strong>회
            </div>
          </div>
          <div class="product-buy">
            <div class="product-price">{{ status.aiStatPrice.toLocaleString('ko-KR') }} P</div>
            <button
              type="button"
              class="buy-btn"
              :disabled="buying === 'AI_STAT'"
              @click="buy('AI_STAT')"
            >
              <template v-if="buying === 'AI_STAT'">구매 중…</template>
              <template v-else>구매</template>
            </button>
          </div>
        </div>
      </section>

      <!-- 포인트 적립 안내 -->
      <section class="earn-guide">
        <h3 class="earn-title">포인트 적립 방법</h3>
        <ul class="earn-list">
          <li>가계부 내역 작성: <strong>10P</strong> (일 5회 한도)</li>
          <li>게시판 글 작성: <strong>10P</strong> (일 5회 한도)</li>
          <li>게시글 추천받기: <strong>5P</strong></li>
          <li>남의 글 추천하기: <strong>1P</strong></li>
          <li>한 달 개근 보너스: <strong>최대 100P</strong></li>
        </ul>
      </section>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useDialog } from '@/composables/dialog'
import { accountApi } from '@/api/accountApi'
import { authApi } from '@/api/authApi'

const router = useRouter()
const auth = useAuthStore()
const dialog = useDialog()

const loading = ref(true)
const buying = ref('')
const points = ref(0)
const status = ref({
  extraWalletSlots: 0,
  aiStatCredits: 0,
  maxExtraSlots: 3,
  walletSlotPrice: 500,
  aiStatPrice: 1000,
  aiStatPackSize: 10,
})

const isPremium = computed(() => auth.user?.plan === 'PREMIUM')

async function load() {
  loading.value = true
  try {
    const [pt, st] = await Promise.all([authApi.points(), accountApi.shopStatus()])
    points.value = pt.points ?? 0
    status.value = st
  } finally {
    loading.value = false
  }
}

async function buy(item) {
  const labels = { WALLET_SLOT: '추가 계좌 슬롯', AI_STAT: `AI 통계 분석 ${status.value.aiStatPackSize}회` }
  const prices = { WALLET_SLOT: status.value.walletSlotPrice, AI_STAT: status.value.aiStatPrice }

  const ok = await dialog.confirm(
    `${labels[item]} (${prices[item].toLocaleString('ko-KR')}P)를 구매하시겠습니까?`
  )
  if (!ok) return

  buying.value = item
  try {
    status.value = await accountApi.buyShopItem(item)
    const pt = await authApi.points()
    points.value = pt.points ?? 0
    dialog.alert('구매가 완료되었습니다!')
  } catch (e) {
    const msg = e.response?.data?.message
    if (msg === 'SHOP_NOT_ENOUGH_POINTS') {
      dialog.alert('포인트가 부족합니다.')
    } else if (msg === 'SHOP_WALLET_SLOT_MAX') {
      dialog.alert('추가 계좌 슬롯은 최대 3개까지 구매할 수 있습니다.')
    } else {
      dialog.alert('구매 중 오류가 발생했습니다.')
    }
  } finally {
    buying.value = ''
  }
}

onMounted(load)
</script>

<style scoped>
.shop-wrap {
  max-width: 480px;
  margin: 0 auto;
  padding: 0 0 40px;
  min-height: 100vh;
  background: var(--color-bg, #f7f8fa);
}

.shop-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px 16px 12px;
  background: var(--color-surface, #fff);
  border-bottom: 1px solid var(--color-border, #e8eaed);
}

.back-btn {
  font-size: 22px;
  line-height: 1;
  background: none;
  border: none;
  cursor: pointer;
  color: var(--color-text, #222);
  padding: 0 4px;
}

.shop-title {
  font-size: 17px;
  font-weight: 700;
  margin: 0;
}

.shop-loading {
  padding: 48px;
  text-align: center;
  color: var(--color-muted, #888);
}

.points-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 20px;
  background: var(--color-surface, #fff);
  margin: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 1px 4px rgba(0,0,0,.07);
}

.points-label {
  font-size: 14px;
  color: var(--color-muted, #888);
}

.points-value {
  font-size: 18px;
  font-weight: 700;
  color: #2563eb;
}

.premium-notice {
  margin: 12px 16px;
  padding: 16px;
  border-radius: 12px;
  background: #f0fdf4;
  color: #166534;
  font-size: 14px;
  line-height: 1.6;
  border: 1px solid #bbf7d0;
}

.product-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 0 16px;
  margin-top: 4px;
}

.product-card {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  background: var(--color-surface, #fff);
  border-radius: 14px;
  box-shadow: 0 1px 4px rgba(0,0,0,.07);
}

.product-icon {
  font-size: 28px;
  flex-shrink: 0;
  margin-top: 2px;
}

.product-info {
  flex: 1;
  min-width: 0;
}

.product-name {
  font-size: 15px;
  font-weight: 700;
  margin-bottom: 4px;
}

.product-desc {
  font-size: 13px;
  color: var(--color-muted, #888);
  line-height: 1.5;
  margin-bottom: 6px;
}

.product-status {
  font-size: 13px;
  color: var(--color-text, #222);
}

.product-buy {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
  flex-shrink: 0;
}

.product-price {
  font-size: 15px;
  font-weight: 700;
  color: #2563eb;
  white-space: nowrap;
}

.buy-btn {
  padding: 7px 16px;
  border-radius: 8px;
  border: none;
  background: #2563eb;
  color: #fff;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  white-space: nowrap;
  transition: opacity .15s;
}

.buy-btn:disabled {
  background: #c0c8d8;
  cursor: default;
}

.earn-guide {
  margin: 20px 16px 0;
  padding: 16px;
  background: var(--color-surface, #fff);
  border-radius: 14px;
  box-shadow: 0 1px 4px rgba(0,0,0,.07);
}

.earn-title {
  font-size: 14px;
  font-weight: 700;
  margin: 0 0 10px;
}

.earn-list {
  margin: 0;
  padding: 0 0 0 18px;
  list-style: disc;
  font-size: 13px;
  color: var(--color-muted, #888);
  line-height: 1.8;
}

.earn-list strong {
  color: var(--color-text, #222);
}

@media (prefers-color-scheme: dark) {
  .shop-wrap { background: #111; }
  .shop-header { background: #1c1c1e; border-color: #2c2c2e; }
  .points-bar, .product-card, .earn-guide { background: #1c1c1e; box-shadow: none; }
  .premium-notice { background: #052e16; color: #bbf7d0; border-color: #166534; }
}
</style>
