<template>
  <div class="min-h-screen bg-[var(--bg-secondary)]">
    <!-- Hero Header -->
    <div class="relative py-16 overflow-hidden">
      <!-- Background -->
      <div
        class="absolute inset-0 bg-gradient-to-br from-primary-950/30 via-zinc-900 to-zinc-900"
      ></div>
      <div
        class="absolute top-0 left-1/4 w-96 h-96 bg-primary-500/10 rounded-full blur-[100px]"
      ></div>
      <div
        class="absolute bottom-0 right-1/4 w-96 h-96 bg-emerald-500/10 rounded-full blur-[100px]"
      ></div>
      <div class="relative max-w-7xl mx-auto px-4">
        <div class="flex items-center gap-4 mb-4">
          <div
            class="w-14 h-14 rounded-2xl bg-gradient-to-br from-primary-500 to-emerald-600 flex items-center justify-center shadow-lg shadow-primary-500/25"
          >
            <svg
              class="w-7 h-7 text-[var(--text-primary)]"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M14 10l-2 1m0 0l-2-1m2 1v2.5M20 7l-2 1m2-1l-2-1m2 1v2.5M14 4l-2-1-2 1M4 7l2-1M4 7l2 1M4 7v2.5M12 21l-2-1m2 1l2-1m-2 1v-2.5M6 18l-2-1v-2.5M18 18l2-1v-2.5"
              />
            </svg>
          </div>
          <div>
            <h1
              class="text-3xl sm:text-4xl font-bold text-[var(--text-primary)]"
            >
              {{ t("mods.browse_mods") }}
            </h1>
            <p class="text-[var(--text-muted)] mt-1">{{ t("mods.subtitle") }}</p>
          </div>
        </div>
      </div>
    </div>
    <!-- Filter Bar -->
    <div
      class="bg-[var(--bg-card)] backdrop-blur-xl border-b border-[var(--border-primary)] sticky top-0 z-40"
    >
      <div class="max-w-7xl mx-auto px-4 py-4">
        <div
          class="flex flex-col md:flex-row md:items-center md:justify-between gap-4"
        >
          <!-- Search -->
          <div class="relative flex-1 max-w-md">
            <input
              v-model="filters.search"
              type="text"
              :placeholder="t('mods.search_placeholder')"
              class="w-full bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-xl px-4 py-2.5 pl-11 text-[var(--text-primary)] placeholder-[var(--text-muted)] focus:outline-none focus:border-primary-500/50 focus:ring-1 focus:ring-primary-500/50 transition-all"
              @input="debouncedSearch"
            />
            <svg
              class="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-[var(--text-muted)] "
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
              />
            </svg>
          </div>
          <!-- Filters -->
          <div class="flex flex-wrap items-center gap-3">
            <!-- Game filter -->
            <select
              v-model="filters.game"
              class="bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-xl px-4 py-2.5 text-[var(--text-primary)] text-sm focus:outline-none focus:border-primary-500/50 transition-colors cursor-pointer"
            >
              <option value="">{{ t("mods.all_games") }}</option>
              <option v-for="game in games" :key="game.id" :value="game.id">
                {{ game.name }}
              </option>
            </select>
            <!-- Category filter -->
            <select
              v-model="filters.category"
              class="bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-xl px-4 py-2.5 text-[var(--text-primary)] text-sm focus:outline-none focus:border-primary-500/50 transition-colors cursor-pointer"
            >
              <option value="">{{ t("mods.all_categories") }}</option>
              <option
                v-for="category in categories"
                :key="category.id"
                :value="category.id"
              >
                {{ category.name }}
              </option>
            </select>
            <!-- Sort -->
            <select
              v-model="filters.sort"
              class="bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-xl px-4 py-2.5 text-[var(--text-primary)] text-sm focus:outline-none focus:border-primary-500/50 transition-colors cursor-pointer"
            >
              <option value="latest">{{ t("mods.sort_latest") }}</option>
              <option value="popular">{{ t("mods.sort_popular") }}</option>
              <option value="downloads">{{ t("mods.sort_downloads") }}</option>
              <option value="rating">{{ t("mods.sort_rating") }}</option>
            </select>
            <!-- Clear filters -->
            <button
              v-if="hasActiveFilters"
              @click="clearFilters"
              class="text-primary-400 hover:text-primary-300 text-sm font-medium transition-colors flex items-center gap-1"
            >
              <svg
                class="w-4 h-4"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
              {{ t("common.clear_filters") }}
            </button>
          </div>
        </div>
        <!-- Results count -->
        <div
          class="flex items-center justify-between mt-4 pt-4 border-t border-[var(--border-primary)]/50"
        >
          <p class="text-sm text-[var(--text-muted)] ">
            <span class="text-[var(--text-primary)] font-semibold">{{ totalMods }}</span>
            {{ t("mods.mods_found") }}
          </p>
          <!-- View mode toggle could go here -->
        </div>
      </div>
    </div>
    <!-- Mods grid -->
    <div class="max-w-7xl mx-auto px-4 py-8">
      <!-- Loading state -->
      <div
        v-if="loading"
        class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6"
      >
        <div v-for="i in 8" :key="i" class="animate-pulse">
          <div
            class="bg-[var(--bg-card)] border border-[var(--border-primary)] rounded-2xl overflow-hidden"
          >
            <div class="aspect-[16/10] bg-[var(--bg-tertiary)]"></div>
            <div class="p-4 space-y-3">
              <div class="h-5 bg-[var(--bg-tertiary)] rounded w-3/4"></div>
              <div
                class="h-4 bg-[var(--bg-tertiary)] rounded w-full"
              ></div>
              <div class="h-4 bg-[var(--bg-tertiary)] rounded w-1/2"></div>
            </div>
          </div>
        </div>
      </div>
      <!-- Empty state -->
      <div
        v-else-if="mods.length === 0"
        class="text-center py-20 bg-[var(--bg-primary)]/50 border border-[var(--border-primary)] rounded-2xl"
      >
        <div
          class="w-20 h-20 mx-auto bg-[var(--bg-tertiary)] rounded-2xl flex items-center justify-center mb-6"
        >
          <svg
            class="w-10 h-10 text-[var(--text-muted)] "
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            />
          </svg>
        </div>
        <h3 class="text-xl font-semibold text-[var(--text-primary)] mb-2">
          {{ t("mods.no_mods_found") }}
        </h3>
        <p class="text-[var(--text-muted)] max-w-md mx-auto">
          {{ t("mods.try_different_filters") }}
        </p>
        <button @click="clearFilters" class="mt-6 btn-primary">
          {{ t("common.clear_filters") }}
        </button>
      </div>
      <!-- Mods list -->
      <div
        v-else
        class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 animate-stagger"
      >
        <ModCard v-for="mod in mods" :key="mod.id" :mod="mod" />
      </div>
      <!-- Pagination -->
      <div v-if="totalPages > 1" class="flex justify-center mt-8">
        <nav class="flex items-center space-x-2">
          <button
            @click="goToPage(currentPage - 1)"
            :disabled="currentPage === 1"
            class="px-3 py-2 rounded-xl bg-[var(--bg-tertiary)] text-[var(--text-muted)] hover:bg-[var(--bg-hover)] hover:text-[var(--text-primary)] disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <svg
              class="h-5 w-5"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M15 19l-7-7 7-7"
              />
            </svg>
          </button>
          <template v-for="page in visiblePages" :key="page">
            <span
              v-if="page === '...'"
              class="px-3 py-2 text-[var(--text-muted)] "
              >...</span
            >
            <button
              v-else
              @click="goToPage(Number(page))"
              :class="[
                'px-4 py-2 rounded-xl font-medium transition-colors',
                currentPage === page
                  ? 'bg-primary-500 text-black'
                  : 'bg-[var(--bg-tertiary)] text-[var(--text-muted)] hover:bg-[var(--bg-hover)] hover:text-[var(--text-primary)]',
              ]"
            >
              {{ page }}
            </button>
          </template>
          <button
            @click="goToPage(currentPage + 1)"
            :disabled="currentPage === totalPages"
            class="px-3 py-2 rounded-xl bg-[var(--bg-tertiary)] text-[var(--text-muted)] hover:bg-[var(--bg-hover)] hover:text-[var(--text-primary)] disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <svg
              class="h-5 w-5"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M9 5l7 7-7 7"
              />
            </svg>
          </button>
        </nav>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { logger } from "@/utils/logger";
import { ref, reactive, computed, watch, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useI18nStore } from "@/stores/i18n";
import api from "@/services/api";
import { formatNumber as _formatNumber } from "@/utils/numberHelper";
import ModCard from "@/components/mods/ModCard.vue";
import type { Mod, Game, Category } from "@/types";

const route = useRoute();
const router = useRouter();
const { t } = useI18nStore();

// State
const mods = ref<Mod[]>([]);
const games = ref<Game[]>([]);
const categories = ref<Category[]>([]);
const loading = ref(true);
const currentPage = ref(1);
const totalPages = ref(1);
const totalMods = ref(0);
const perPage = 20;

const filters = reactive({
  search: "",
  game: "",
  category: "",
  sort: "latest",
});

// Computed
const hasActiveFilters = computed(() => {
  return (
    filters.search ||
    filters.game ||
    filters.category ||
    filters.sort !== "latest"
  );
});

const visiblePages = computed(() => {
  const pages: (number | string)[] = [];
  const total = totalPages.value;
  const current = currentPage.value;
  if (total <= 7) {
    for (let i = 1; i <= total; i++) {
      pages.push(i);
    }
  } else {
    pages.push(1);
    if (current > 3) {
      pages.push("...");
    }

    const start = Math.max(2, current - 1);
    const end = Math.min(total - 1, current + 1);
    for (let i = start; i <= end; i++) {
      pages.push(i);
    }
    if (current < total - 2) {
      pages.push("...");
    }
    pages.push(total);
  }
  return pages;
});

// Methods
const fetchMods = async () => {
  loading.value = true;
  try {
    const params: Record<string, any> = {
      page: currentPage.value,
      per_page: perPage,
    };
    if (filters.search) params.q = filters.search;
    if (filters.game) params.game_id = filters.game;
    if (filters.category) params.category_id = filters.category;
    if (filters.sort) params.sort = filters.sort;
    const response = await api.mods.list(params);
    mods.value = response.data.data as Mod[];
    // Backend returns 'meta' with 'last_page', not 'pagination' with 'total_pages'
    const meta = response.data.meta || response.data.pagination;
    totalPages.value = meta?.last_page || 1;
    currentPage.value = meta?.page || 1;
    totalMods.value = meta?.total || mods.value.length;
  } catch (error) {
    logger.error("Failed to fetch mods:", error);
  } finally {
    loading.value = false;
  }
};

const fetchGames = async () => {
  try {
    const response = await api.games.list();
    games.value = response.data.data;
  } catch (error) {
    logger.error("Failed to fetch games:", error);
  }
};

const fetchCategories = async () => {
  try {
    const response = await api.categories.list();
    categories.value = response.data.data;
  } catch (error) {
    logger.error("Failed to fetch categories:", error);
  }
};

let searchTimeout: ReturnType<typeof setTimeout> | null = null;

const debouncedSearch = () => {
  if (searchTimeout) clearTimeout(searchTimeout);
  searchTimeout = setTimeout(() => {
    currentPage.value = 1;
    fetchMods();
    updateUrl();
  }, 300);
};

const clearFilters = () => {
  filters.search = "";
  filters.game = "";
  filters.category = "";
  filters.sort = "latest";
  currentPage.value = 1;
  fetchMods();
  router.push({ query: {} });
};

const goToPage = (page: number) => {
  if (page < 1 || page > totalPages.value) return;
  currentPage.value = page;
  fetchMods();
  updateUrl();
  window.scrollTo({ top: 0, behavior: "smooth" });
};

const updateUrl = () => {
  const query: Record<string, string> = {};
  if (filters.search) query.q = filters.search;
  if (filters.game) query.game = filters.game;
  if (filters.category) query.category = filters.category;
  if (filters.sort !== "latest") query.sort = filters.sort;
  if (currentPage.value > 1) query.page = currentPage.value.toString();
  router.push({ query });
};

// Watch filters
watch([() => filters.game, () => filters.category, () => filters.sort], () => {
  currentPage.value = 1;
  fetchMods();
  updateUrl();
});

// Initialize from URL
onMounted(() => {
  if (route.query.q) filters.search = route.query.q as string;
  if (route.query.game) filters.game = route.query.game as string;
  if (route.query.category) filters.category = route.query.category as string;
  if (route.query.sort) filters.sort = route.query.sort as string;
  if (route.query.page)
    currentPage.value = parseInt(route.query.page as string) || 1;
  fetchGames();
  fetchCategories();
  fetchMods();
});
</script>
