<script setup lang="ts">
import { onMounted, computed } from "vue";
import { useTemplates } from "../../composables/useTemplates";
import { useModal } from "../../composables/useModal";
import { useCart } from "../../composables/useCart";
import { useNotifications } from "../../composables/useNotifications";
import { useUsageStats } from "../../composables/useUsageStats";

const {
  templates: storeTemplates,
  isLoading,
  pagination,
  loadMore,
  fetchTemplates,
  initWithData,
  fetchCounts,
} = useTemplates();
const { openModal } = useModal();
const { toggleItem, hasItem } = useCart();
const { showNotification } = useNotifications();
const { trackCopy, getStats, formatCount, fetchStats, fetchAllStats } =
  useUsageStats();

// Props for SSR initial data
const props = defineProps<{
  initialTemplates?: any[];
  initialCounts?: Record<string, number>;
  initialFilter?: string;
}>();

// Use props directly for SSR, then switch to store after hydration
const templates = computed(() => {
  if (storeTemplates.value.length > 0) {
    return storeTemplates.value;
  }
  return props.initialTemplates || [];
});

onMounted(async () => {
  // Initialize composable with SSR data
  if (props.initialTemplates && props.initialCounts) {
    initWithData(
      props.initialTemplates,
      props.initialCounts,
      props.initialFilter || "all",
    );
  } else {
    fetchCounts();
    fetchTemplates();
  }
  // Fetch usage stats
  await fetchAllStats();
});

function getUsageCount(name: string): number {
  return getStats(name).total;
}

function getIcon(type: string) {
  const icons: Record<string, string> = {
    agent: "ph-robot",
    command: "ph-terminal",
    mcp: "ph-plug",
    skill: "ph-magic-wand",
    setting: "ph-gear",
    hook: "ph-webhooks-logo",
  };
  return icons[type] || "ph-file";
}

function handleCardClick(template: any) {
  openModal(template);
}

function handleCopy(e: Event, template: any) {
  e.stopPropagation();
  const command = `npx vibery install ${template.name}`;
  navigator.clipboard.writeText(command);
  trackCopy(template.name);
  showNotification("Copied install command");
}

function handleAddToCart(e: Event, template: any) {
  e.stopPropagation();
  const added = toggleItem({
    name: template.name,
    type: template.type,
    description: template.description,
  });
  showNotification(added ? "Added to cart" : "Removed from cart");
}

function handleDownload(e: Event, template: any) {
  e.stopPropagation();
  // Prefer tar.gz (handles multi-file templates), fallback to raw single file
  if (template.downloadUrl) {
    window.open(template.downloadUrl, "_blank");
  } else if (template.rawUrl) {
    window.open(template.rawUrl, "_blank");
  }
}
</script>

<template>
  <main class="max-w-6xl mx-auto px-4 py-8">
    <!-- Loading state -->
    <div
      v-if="isLoading && templates.length === 0"
      class="flex justify-center py-16"
    >
      <div
        class="w-10 h-10 border-2 border-warm-accent/30 border-t-warm-accent rounded-full animate-spin"
      ></div>
    </div>

    <!-- Empty state -->
    <div
      v-else-if="templates.length === 0"
      class="col-span-full text-center text-warm-text-secondary py-16 surface-card"
    >
      <i
        class="ph ph-magnifying-glass text-4xl mb-3 block text-warm-text-tertiary"
      ></i>
      <p>No templates found</p>
    </div>

    <!-- Templates grid -->
    <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
      <article
        v-for="template in templates"
        :key="`${template.type}-${template.name}`"
        class="elevated-card p-5 cursor-pointer transition-all duration-300 hover:scale-[1.02] group"
        @click="handleCardClick(template)"
      >
        <!-- Header -->
        <div class="flex items-start justify-between mb-4">
          <div
            class="flex items-center justify-center w-11 h-11 bg-warm-bg-elevated rounded-lg text-warm-text-secondary border border-warm-border-subtle group-hover:border-warm-accent/50 group-hover:text-warm-accent transition-all"
          >
            <i :class="['ph-bold', getIcon(template.type), 'text-xl']"></i>
          </div>
          <span :class="[`badge-${template.type}`, 'font-semibold']">
            {{ template.type }}
          </span>
        </div>

        <!-- Name -->
        <h3
          class="text-base font-semibold mb-2 text-warm-text-primary group-hover:text-warm-accent transition-colors"
        >
          {{ template.name }}
        </h3>

        <!-- Description -->
        <p
          class="text-warm-text-secondary text-sm leading-relaxed mb-4 line-clamp-2"
        >
          {{ template.description }}
        </p>

        <!-- Footer -->
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-2">
            <code
              class="text-xs font-mono text-warm-text-tertiary truncate max-w-[140px] bg-warm-bg-elevated px-2 py-1 rounded border border-warm-border-subtle"
            >
              npx vibery install {{ template.name }}
            </code>
            <span
              v-if="getUsageCount(template.name) > 0"
              class="flex items-center gap-1 text-2xs text-warm-text-tertiary"
            >
              <i class="ph ph-fire text-warm-accent"></i>
              {{ formatCount(getUsageCount(template.name)) }}
            </span>
          </div>
          <div
            class="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-all duration-200"
          >
            <button
              @click="handleCopy($event, template)"
              class="icon-btn"
              title="Copy install command"
            >
              <i class="ph-bold ph-copy text-sm"></i>
            </button>
            <button
              v-if="template.rawUrl || template.downloadUrl"
              @click="handleDownload($event, template)"
              class="icon-btn"
              title="Download"
            >
              <i class="ph-bold ph-download-simple text-sm"></i>
            </button>
            <button
              @click="handleAddToCart($event, template)"
              class="icon-btn"
              :class="{ 'text-warm-accent': hasItem(template.name) }"
              title="Add to stack"
            >
              <i
                :class="[
                  'ph-bold text-sm',
                  hasItem(template.name) ? 'ph-check' : 'ph-plus',
                ]"
              ></i>
            </button>
          </div>
        </div>
      </article>
    </div>

    <!-- Load more -->
    <div v-if="pagination.hasMore" class="flex justify-center mt-8">
      <button @click="loadMore" :disabled="isLoading" class="btn-secondary">
        <span v-if="isLoading">Loading...</span>
        <span v-else>Load More</span>
      </button>
    </div>

    <!-- Loading indicator for pagination -->
    <div
      v-if="isLoading && templates.length > 0"
      class="flex justify-center mt-4"
    >
      <div
        class="w-6 h-6 border-2 border-warm-accent/30 border-t-warm-accent rounded-full animate-spin"
      ></div>
    </div>
  </main>
</template>
