<template>
  <div class="shop">
    <!-- Header -->
    <header class="shop-header">
      <div class="sh-left">
        <router-link to="/" class="sh-back">← Chat</router-link>
        <span class="sh-title">XIP</span>
        <span class="sh-sub">Marketplace</span>
      </div>
      <div class="sh-right">
        <span v-if="ip" class="sh-ip">Connecté&nbsp;: {{ ip }}</span>
        <span class="sh-balance" :class="{ free: freeMode }">
          ◈ {{ displayBalance() }} <span class="sh-cr">cr</span>
        </span>
        <button class="sh-topup" @click="topUp" type="button">💸 Recharger</button>
      </div>
    </header>

    <!-- Flash promo banner -->
    <div class="flash">
      ⚡ OFFRES FLASH — Cadre de Pub -33%, Pack Cosmétique -3 cr — expire dans
      <span class="flash-timer">{{ countdown }}</span>
    </div>

    <div class="shop-body">
      <!-- Category nav -->
      <nav class="shop-nav">
        <button
          v-for="cat in categories"
          :key="cat.id"
          class="nav-item"
          :class="{ active: activeCat === cat.id }"
          @click="activeCat = cat.id"
          type="button"
        >{{ cat.label }}</button>

        <div class="nav-wallet">
          <p class="nav-wallet-label">Ton solde</p>
          <p class="nav-wallet-val" :class="{ free: freeMode }">{{ displayBalance() }} cr</p>
          <button class="nav-topup" @click="topUp" type="button">+ Recharger gratuitement</button>
          <p v-if="freeMode" class="nav-free-note">Mode localhost : tout gratuit 🎉</p>
        </div>
      </nav>

      <!-- Product grid -->
      <main class="shop-main">
        <div v-if="lastError" class="toast toast--err">{{ lastError }}</div>
        <div v-else-if="lastSuccess" class="toast toast--ok">✓ Achat effectué</div>

        <!-- Mes Persos panel -->
        <MesPersos v-if="activeCat === 'perso'" />

        <template v-else>
          <div class="grid">
            <ProductCard
              v-for="p in visibleProducts"
              :key="p.id"
              :product="p"
              :buying="buying === p.id"
              :owns="owns"
              :pet-count="petCount()"
              :owned-pet-chars="ownedPetChars()"
              :free-mode="freeMode"
              @buy="onBuy"
              @go-perso="activeCat = 'perso'"
            />
          </div>
          <p v-if="visibleProducts.length === 0" class="empty">Aucun produit dans cette catégorie.</p>
        </template>
      </main>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useShop, type PurchaseOptions } from '@/composables/useShop';
import { useWallet } from '@/composables/useWallet';
import { parseMeta, type ProductMeta } from '@/composables/useMeta';
import ProductCard from '@/components/shop/ProductCard.vue';
import MesPersos from '@/components/shop/MesPersos.vue';

const { products, buying, lastError, lastSuccess, fetchProducts, fetchMe, owns, petCount, ownedPetChars, purchase } = useShop();
const { ip, freeMode, displayBalance, fetchWallet, topUp: walletTopUp } = useWallet();

// Navigation forcée par catégorie : pas de « Tout voir », on entre directement
// dans une rubrique organisée.
const categories = [
  { id: 'publicite', label: 'Publicité' },
  { id: 'abonnements', label: 'Abonnements' },
  { id: 'cosmetiques', label: 'Cosmétiques' },
  { id: 'premium', label: 'Premium' },
  { id: 'promotions', label: 'Promotions' },
  { id: 'perso', label: '✨ Mes Persos' },
];
const activeCat = ref('publicite');

const visibleProducts = computed(() => {
  const chars = ownedPetChars();
  return products.value
    .filter((p) => p.category === activeCat.value)
    .filter((p) => {
      if (p.kind !== 'pet') return true;
      const designs = parseMeta<ProductMeta>(p.metaJson).designs ?? [];
      return designs.some((d) => !chars.includes(d.char));
    });
});

async function onBuy(productId: string, options: PurchaseOptions): Promise<void> {
  await purchase(productId, options);
}

async function topUp(): Promise<void> {
  await walletTopUp();
}

// Cosmetic countdown timer (purely decorative, like the mockups).
const countdown = ref('02:47:33');
let timer: ReturnType<typeof setInterval> | null = null;
let remaining = 2 * 3600 + 47 * 60 + 33;
function tick(): void {
  remaining = remaining > 0 ? remaining - 1 : 0;
  const h = Math.floor(remaining / 3600);
  const m = Math.floor((remaining % 3600) / 60);
  const s = remaining % 60;
  const pad = (n: number) => String(n).padStart(2, '0');
  countdown.value = `${pad(h)}:${pad(m)}:${pad(s)}`;
}

onMounted(() => {
  fetchProducts();
  fetchMe();
  fetchWallet();
  timer = setInterval(tick, 1000);
});
onUnmounted(() => { if (timer) clearInterval(timer); });
</script>

<style scoped>
.shop {
  width: 100vw;
  height: 100dvh;
  background: #08080e;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  font-family: Arial, sans-serif;
}

/* Header */
.shop-header {
  flex-shrink: 0;
  height: 56px;
  background: #0e0e18;
  border-bottom: 1px solid #1a1a2e;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}
.sh-left { display: flex; align-items: center; gap: 12px; }
.sh-back {
  color: #00ddff; text-decoration: none; font-size: 12px; font-weight: bold;
  border: 1px solid #00aaff44; border-radius: 10px; padding: 4px 10px;
}
.sh-back:hover { background: #00aaff14; }
.sh-title { font-size: 18px; font-weight: bold; color: #6699aa; }
.sh-sub { font-size: 13px; color: #8888aa; }
.sh-right { display: flex; align-items: center; gap: 12px; }
.sh-ip { font-family: 'Courier New', monospace; font-size: 11px; color: #5566aa; }
.sh-balance { font-family: 'Courier New', monospace; font-size: 15px; font-weight: bold; color: #ccaa44; }
.sh-balance.free { color: #44aa77; }
.sh-cr { font-size: 10px; color: #886633; }
.sh-topup {
  background: #1a2a1a; border: 1px solid #33aa55; color: #44dd77;
  font-size: 12px; font-weight: bold; padding: 6px 14px; border-radius: 16px; cursor: pointer;
  box-shadow: none;
}
.sh-topup:hover { background: #234a23; }

/* Flash banner */
.flash {
  flex-shrink: 0;
  background: linear-gradient(90deg, #2a0a0a, #1a0a1a);
  border-bottom: 1px solid #44113344;
  color: #ff8866; font-size: 12px; text-align: center; padding: 7px;
}
.flash-timer { font-family: 'Courier New', monospace; color: #ffcc44; font-weight: bold; }

/* Body */
.shop-body { flex: 1; display: flex; min-height: 0; }

.shop-nav {
  width: 200px; flex-shrink: 0; background: #0b0b14; border-right: 1px solid #1a1a2a;
  padding: 14px 10px; display: flex; flex-direction: column; gap: 4px; overflow-y: auto;
}
.nav-item {
  text-align: left; background: none; border: none; color: #8888aa;
  font-size: 13px; padding: 9px 12px; border-radius: 7px; cursor: pointer;
}
.nav-item:hover { background: #14142080; color: #aaaacc; }
.nav-item.active { background: #00aaff18; color: #00ddff; font-weight: bold; }

.nav-wallet {
  margin-top: auto; background: #0e0e1a; border: 1px solid #20203a; border-radius: 8px; padding: 12px;
}
.nav-wallet-label { font-size: 10px; color: #6a6a90; margin: 0 0 4px; text-transform: uppercase; letter-spacing: 1px; }
.nav-wallet-val { font-family: 'Courier New', monospace; font-size: 20px; font-weight: bold; color: #ffdd66; margin: 0 0 10px; }
.nav-wallet-val.free { color: #33ff99; }
.nav-topup { width: 100%; background: #1a2a1a; border: 1px solid #33aa55; color: #44dd77; font-size: 11px; font-weight: bold; padding: 8px; border-radius: 14px; cursor: pointer; }
.nav-topup:hover { background: #234a23; }
.nav-free-note { font-size: 10px; color: #33aa66; margin: 8px 0 0; text-align: center; }

.shop-main { flex: 1; overflow-y: auto; padding: 20px; }
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  align-items: start;
}
.empty { color: #44446a; text-align: center; padding: 40px; }

.toast {
  margin-bottom: 14px; padding: 10px 14px; border-radius: 8px; font-size: 13px;
}
.toast--err { background: #2a0e12; border: 1px solid #aa3344; color: #ff8899; }
.toast--ok { background: #0e2a16; border: 1px solid #33aa55; color: #66ffaa; }
</style>
