<script setup lang="ts">
import { onMounted, onUnmounted, watch } from "vue";
import { useCart } from "../../composables/useCart";
import { useModal } from "../../composables/useModal";
import { useNotifications } from "../../composables/useNotifications";
import { useUsageStats } from "../../composables/useUsageStats";
import type { Template } from "../../types/template";

const { toggleItem, hasItem } = useCart();
const { openModal } = useModal();
const { showNotification } = useNotifications();
const {
  trackCopy,
  trackDownload,
  trackCart,
  getStats,
  fetchStats,
  fetchAllStats,
  formatCount,
  stats,
} = useUsageStats();

// Update card button states based on cart contents
function updateCardStates() {
  document
    .querySelectorAll(".card-add-btn, .add-template-btn")
    .forEach((btn) => {
      const el = btn as HTMLElement;
      const name = el.dataset.name || "";
      const icon = btn.querySelector("i");

      if (hasItem(name)) {
        btn.classList.add("added");
        if (icon) {
          icon.className = "ph-bold ph-check text-sm";
        }
      } else {
        btn.classList.remove("added");
        if (icon) {
          icon.className = "ph-bold ph-plus text-sm";
        }
      }
    });
}

// Handle template card click - open modal
function handleCardClick(e: Event) {
  const card = e.currentTarget as HTMLElement;
  const target = e.target as HTMLElement;

  // Don't open modal if clicking action buttons
  if (target.closest(".icon-btn")) return;

  // Parse files JSON if present (for skills)
  let files;
  if (card.dataset.files) {
    try {
      files = JSON.parse(card.dataset.files);
    } catch {
      files = undefined;
    }
  }

  const template: Template = {
    name: card.dataset.name || "",
    type: card.dataset.type as any,
    description:
      card.querySelector("p")?.textContent || card.dataset.description || "",
    content: card.dataset.content || "",
    path: "",
    files,
    downloadUrl: card.dataset.downloadUrl || "",
    rawUrl: card.dataset.rawUrl || "",
    size: parseInt(card.dataset.size || "0", 10),
  };

  openModal(template);
}

// Handle template item click (stack page) - open modal
function handleItemClick(e: Event) {
  const item = e.currentTarget as HTMLElement;
  const target = e.target as HTMLElement;

  // Don't open modal if clicking action buttons
  if (target.closest(".icon-btn")) return;

  const template: Template = {
    name: item.dataset.name || "",
    type: item.dataset.type as any,
    description: item.dataset.description || "",
    content: item.dataset.content || "",
    path: "",
  };

  openModal(template);
}

// Handle add to cart button
function handleAddClick(e: Event) {
  e.stopPropagation();
  const btn = e.currentTarget as HTMLElement;

  const item = {
    name: btn.dataset.name || "",
    type: btn.dataset.type as any,
    description: btn.dataset.description || "",
  };

  const added = toggleItem(item);
  if (added) {
    trackCart(item.name);
    updateUsageDisplay();
  }
  showNotification(added ? "Added to cart" : "Removed from cart");
}

// Handle copy button - copies npx install command
function handleCopyClick(e: Event) {
  e.stopPropagation();
  const btn = e.currentTarget as HTMLElement;
  const command =
    btn.dataset.command || `npx vibery install ${btn.dataset.name}`;
  const name = btn.dataset.name || "";

  navigator.clipboard
    .writeText(command)
    .then(() => {
      trackCopy(name);
      updateUsageDisplay();
      showNotification("Copied install command");
    })
    .catch(() => {
      showNotification("Failed to copy", "error");
    });
}

// Handle download button
function handleDownloadClick(e: Event) {
  e.stopPropagation();
  const btn = e.currentTarget as HTMLElement;
  const content = btn.dataset.content || "";
  const name = btn.dataset.name || "";
  const ext = btn.dataset.ext || "md";

  if (content) {
    const blob = new Blob([content], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `${name}.${ext}`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    trackDownload(name);
    updateUsageDisplay();
    showNotification(`Downloaded ${name}.${ext}`);
  } else {
    showNotification(`No content for ${name}`, "warning");
  }
}

// Handle sort change
function handleSortChange(e: Event) {
  const select = e.target as HTMLSelectElement;
  const sortBy = select.value;
  const grid = document.getElementById("templatesGrid");
  if (!grid) return;

  const cards = Array.from(
    grid.querySelectorAll(".template-card"),
  ) as HTMLElement[];

  cards.sort((a, b) => {
    if (sortBy === "popular") {
      const statsA = getStats(a.dataset.name || "");
      const statsB = getStats(b.dataset.name || "");
      // Higher total first, then alphabetically
      if (statsB.total !== statsA.total) return statsB.total - statsA.total;
      return (a.dataset.name || "").localeCompare(b.dataset.name || "");
    } else {
      // Name A-Z
      return (a.dataset.name || "").localeCompare(b.dataset.name || "");
    }
  });

  // Reorder in DOM
  cards.forEach((card) => grid.appendChild(card));
}

// Update usage count display on cards
function updateUsageDisplay() {
  document.querySelectorAll(".template-card").forEach((card) => {
    const el = card as HTMLElement;
    const name = el.dataset.name || "";
    const s = getStats(name);

    // Find or create usage badge
    let badge = el.querySelector(".usage-badge") as HTMLElement;
    const codeWrapper = el.querySelector("code")?.parentElement;

    if (!badge && s.total > 0 && codeWrapper) {
      badge = document.createElement("span");
      badge.className =
        "usage-badge flex items-center gap-1 text-2xs text-warm-text-tertiary";
      codeWrapper.appendChild(badge);
    }

    if (badge) {
      if (s.total > 0) {
        badge.innerHTML = `<i class="ph ph-fire text-warm-accent"></i> ${formatCount(s.total)}`;
        badge.style.display = "";
      } else {
        badge.style.display = "none";
      }
    }
  });
}

// Fetch stats for visible templates
async function loadStats() {
  const cards = document.querySelectorAll(".template-card");
  const names = Array.from(cards)
    .map((c) => (c as HTMLElement).dataset.name || "")
    .filter(Boolean);
  if (names.length > 50) {
    await fetchAllStats();
  } else if (names.length > 0) {
    await fetchStats(names);
  }
  updateUsageDisplay();
}

// Setup event listeners
function setupListeners() {
  // Sort dropdowns (desktop and mobile)
  const sortSelect = document.getElementById("sortSelect");
  const sortSelectMobile = document.getElementById("sortSelectMobile");

  if (sortSelect) {
    sortSelect.addEventListener("change", handleSortChange);
  }
  if (sortSelectMobile) {
    sortSelectMobile.addEventListener("change", handleSortChange);
  }

  // Load stats and apply initial sort after stats are ready
  loadStats().then(() => {
    const activeSort = sortSelect || sortSelectMobile;
    if (activeSort) {
      handleSortChange({ target: activeSort } as any);
    }
  });

  // Template card clicks (main templates grid)
  document.querySelectorAll(".template-card").forEach((card) => {
    card.addEventListener("click", handleCardClick);
  });

  // Template item clicks (stack detail page)
  document.querySelectorAll(".template-item").forEach((item) => {
    item.addEventListener("click", handleItemClick);
  });

  // Add to cart buttons (both class names used in different pages)
  document
    .querySelectorAll(".card-add-btn, .add-template-btn")
    .forEach((btn) => {
      btn.addEventListener("click", handleAddClick);
    });

  // Copy buttons
  document.querySelectorAll(".copy-btn").forEach((btn) => {
    btn.addEventListener("click", handleCopyClick);
  });

  // Download buttons
  document.querySelectorAll(".download-btn").forEach((btn) => {
    btn.addEventListener("click", handleDownloadClick);
  });

  // Initial card state update
  updateCardStates();
}

// Cleanup event listeners
function cleanupListeners() {
  const sortSelect = document.getElementById("sortSelect");
  const sortSelectMobile = document.getElementById("sortSelectMobile");
  if (sortSelect) {
    sortSelect.removeEventListener("change", handleSortChange);
  }
  if (sortSelectMobile) {
    sortSelectMobile.removeEventListener("change", handleSortChange);
  }

  document.querySelectorAll(".template-card").forEach((card) => {
    card.removeEventListener("click", handleCardClick);
  });

  document.querySelectorAll(".template-item").forEach((item) => {
    item.removeEventListener("click", handleItemClick);
  });

  document
    .querySelectorAll(".card-add-btn, .add-template-btn")
    .forEach((btn) => {
      btn.removeEventListener("click", handleAddClick);
    });

  document.querySelectorAll(".copy-btn").forEach((btn) => {
    btn.removeEventListener("click", handleCopyClick);
  });

  document.querySelectorAll(".download-btn").forEach((btn) => {
    btn.removeEventListener("click", handleDownloadClick);
  });
}

// Re-setup listeners on astro:page-load for View Transitions
function handlePageLoad() {
  setupListeners();
}

onMounted(() => {
  setupListeners();
  document.addEventListener("astro:page-load", handlePageLoad);
});

onUnmounted(() => {
  cleanupListeners();
  document.removeEventListener("astro:page-load", handlePageLoad);
});

// Watch cart changes and update button states
const { items } = useCart();
watch(items, updateCardStates, { deep: true });
</script>

<template>
  <!-- This component has no visual output, it only handles interactions -->
</template>
