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

const { isOpen, currentTemplate, closeModal } = useModal();
const { toggleItem, hasItem, getIcon: getCartIcon } = useCart();
const { showNotification } = useNotifications();
const { trackCopy, trackDownload } = useUsageStats();

// Check if this is a skill (skills have folders with scripts, data, etc.)
const isSkill = computed(() => {
  return currentTemplate.value?.type === "skill";
});

// Check if template has downloadUrl (multi-file templates like skills)
const hasDownloadUrl = computed(() => {
  return !!currentTemplate.value?.downloadUrl;
});

// Check if template has content to display
const hasContent = computed(() => {
  return !!currentTemplate.value?.content && !hasDownloadUrl.value;
});

// Check if template has raw file URL (single-file download as .md/.json) but no content
const hasRawDownloadOnly = computed(() => {
  return !!currentTemplate.value?.rawUrl && !currentTemplate.value?.content;
});

const badgeClass = computed(() => {
  if (!currentTemplate.value) return "";
  const type = currentTemplate.value.type;
  return `badge-${type}`;
});

const icon = computed(() => {
  if (!currentTemplate.value) return "ph-file";
  return getCartIcon(currentTemplate.value.type);
});

const installCommand = computed(() => {
  if (!currentTemplate.value) return "";
  return `vibery install ${currentTemplate.value.name}`;
});

const npxCommand = computed(() => {
  if (!currentTemplate.value) return "";
  return `npx vibery install ${currentTemplate.value.name}`;
});

const isInCart = computed(() => {
  if (!currentTemplate.value) return false;
  return hasItem(currentTemplate.value.name);
});

// Share URL for current modal - clean URL format
const shareUrl = computed(() => {
  if (typeof window === "undefined" || !currentTemplate.value) return "";
  return `${window.location.origin}/templates/${currentTemplate.value.type}s/${currentTemplate.value.name}`;
});

function handleOverlayClick(event: MouseEvent) {
  if (event.target === event.currentTarget) {
    closeModal();
  }
}

function handleKeydown(event: KeyboardEvent) {
  if (event.key === "Escape" && isOpen.value) {
    closeModal();
  }
}

async function copyToClipboard(
  text: string,
  message: string,
  isContent = false,
) {
  try {
    await navigator.clipboard.writeText(text);
    if (isContent && currentTemplate.value) {
      trackCopy(currentTemplate.value.name);
    }
    showNotification(message);
  } catch (err) {
    showNotification("Failed to copy to clipboard", "error");
  }
}

async function downloadTemplate() {
  if (!currentTemplate.value) return;

  const template = currentTemplate.value;
  const type = template.type;

  // Prefer zip archive (handles multi-file templates like skills)
  if (template.downloadUrl) {
    console.log("[Modal Download] Using downloadUrl:", template.downloadUrl);
    const a = document.createElement("a");
    a.href = template.downloadUrl;
    a.download = ""; // Force download instead of opening in new tab
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    trackDownload(template.name);
    showNotification(`Downloading ${template.name}.zip...`);
    return;
  }

  // Fallback: download from content as single file
  console.log(
    "[Modal Download] Fallback to blob download, no downloadUrl found",
  );
  if (!template.content) {
    showNotification("No content available to download", "error");
    return;
  }

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

  trackDownload(template.name);
  showNotification(`Downloaded ${template.name}.${ext}`);
}

function handleToggleCart() {
  if (!currentTemplate.value) return;

  const added = toggleItem({
    name: currentTemplate.value.name,
    type: currentTemplate.value.type,
    description: currentTemplate.value.description,
  });

  showNotification(added ? "Added to cart" : "Removed from cart");
}

function copyAndClose() {
  if (!currentTemplate.value?.content) return;
  copyToClipboard(currentTemplate.value.content, "Copied to clipboard", true);
  closeModal();
}

onMounted(() => {
  window.addEventListener("keydown", handleKeydown);
});

onUnmounted(() => {
  window.removeEventListener("keydown", handleKeydown);
  document.body.style.overflow = "";
});
</script>

<template>
  <Transition
    enter-active-class="transition-opacity duration-300"
    enter-from-class="opacity-0"
    enter-to-class="opacity-100"
    leave-active-class="transition-opacity duration-300"
    leave-from-class="opacity-100"
    leave-to-class="opacity-0"
  >
    <div
      v-if="isOpen && currentTemplate"
      class="fixed inset-0 z-[1100] flex items-center justify-center bg-black/70 backdrop-blur-md p-3 sm:p-4"
      @click="handleOverlayClick"
    >
      <div
        class="bg-warm-bg-surface border-2 border-warm-accent/30 rounded-2xl shadow-warm-lg max-w-3xl w-full max-h-[90vh] overflow-hidden flex flex-col"
      >
        <!-- Header -->
        <div
          class="flex items-center justify-between px-4 py-3 sm:px-6 sm:py-5 border-b border-warm-border-subtle bg-warm-bg-elevated/50"
        >
          <div class="flex items-center gap-3 sm:gap-4 min-w-0">
            <div
              class="flex-shrink-0 flex items-center justify-center w-10 h-10 sm:w-12 sm:h-12 bg-warm-bg-elevated border border-warm-accent/30 rounded-lg text-warm-accent shadow-accent"
            >
              <i :class="['ph-bold', icon, 'text-xl sm:text-2xl']"></i>
            </div>
            <div class="min-w-0">
              <h2
                class="text-base sm:text-lg font-bold text-warm-text-primary mb-0.5 sm:mb-1 truncate"
              >
                {{ currentTemplate.name }}
              </h2>
              <span :class="badgeClass">
                {{ currentTemplate.type }}
              </span>
            </div>
          </div>
          <div class="flex items-center gap-2">
            <ShareButton
              :title="currentTemplate.name + ' - Vibery'"
              :text="currentTemplate.description"
              :url="shareUrl"
              variant="inline"
            />
            <button
              @click="closeModal"
              class="icon-btn flex-shrink-0"
              aria-label="Close modal"
            >
              <i class="ph-bold ph-x text-xl"></i>
            </button>
          </div>
        </div>

        <!-- Content -->
        <div class="flex-1 overflow-y-auto p-4 sm:p-6">
          <p
            class="text-warm-text-secondary text-sm sm:text-base mb-4 sm:mb-6 leading-relaxed"
          >
            {{ currentTemplate.description }}
          </p>

          <!-- Install Commands -->
          <div class="mb-4 sm:mb-6 space-y-3">
            <label
              class="block text-xs text-warm-text-tertiary uppercase tracking-wider font-semibold"
            >
              Install Command
            </label>
            <!-- Default: vibery install -->
            <div
              class="flex items-center gap-2 sm:gap-3 bg-warm-bg-elevated border-2 border-warm-accent/30 rounded-lg p-3 sm:p-4 shadow-accent"
            >
              <i
                class="ph-bold ph-terminal-window text-warm-accent text-lg sm:text-xl flex-shrink-0"
              ></i>
              <code
                class="flex-1 font-mono text-xs sm:text-sm text-warm-accent font-semibold truncate"
              >
                {{ installCommand }}
              </code>
              <button
                @click="
                  copyToClipboard(installCommand, 'Copied install command')
                "
                class="icon-btn flex-shrink-0"
                title="Copy command"
              >
                <i class="ph-bold ph-copy text-base"></i>
              </button>
            </div>
            <!-- Quick install: npx -->
            <div
              class="flex items-center gap-2 sm:gap-3 bg-warm-bg-elevated border border-warm-border-subtle rounded-lg p-2.5 sm:p-3"
            >
              <i
                class="ph-bold ph-lightning text-warm-text-tertiary text-base sm:text-lg flex-shrink-0"
              ></i>
              <div class="flex-1 min-w-0">
                <code
                  class="font-mono text-xs text-warm-text-secondary truncate block"
                >
                  {{ npxCommand }}
                </code>
                <span class="text-2xs text-warm-text-tertiary"
                  >Quick install - no setup needed</span
                >
              </div>
              <button
                @click="copyToClipboard(npxCommand, 'Copied npx command')"
                class="icon-btn flex-shrink-0"
                title="Copy npx command"
              >
                <i class="ph-bold ph-copy text-sm"></i>
              </button>
            </div>
          </div>

          <!-- Template Content -->
          <div>
            <label
              class="block text-xs text-warm-text-tertiary mb-2 uppercase tracking-wider font-semibold"
            >
              Template Content
            </label>
            <!-- Multi-file archive download (.zip for skills) -->
            <div
              v-if="hasDownloadUrl"
              class="bg-warm-bg-elevated border border-warm-border-subtle rounded-lg p-4 sm:p-6 text-center"
            >
              <i
                class="ph-bold ph-file-zip text-3xl text-warm-accent mb-3 block"
              ></i>
              <p class="text-warm-text-secondary text-sm mb-4">
                This skill contains multiple files (scripts, data, references).
              </p>
              <a
                :href="currentTemplate.downloadUrl"
                download
                class="btn-primary inline-flex items-center gap-2"
              >
                <i class="ph-bold ph-download-simple"></i>
                Download .zip
              </a>
              <p class="text-warm-text-tertiary text-xs mt-3">
                Extract to
                <code class="text-warm-accent">.claude/skills/</code> directory
              </p>
            </div>
            <!-- Content preview (single-file templates) -->
            <div v-else-if="hasContent" class="relative">
              <pre
                class="bg-warm-bg-elevated border border-warm-border-subtle rounded-lg p-3 sm:p-5 text-xs font-mono text-warm-text-secondary overflow-x-auto max-h-[200px] sm:max-h-[320px] whitespace-pre-wrap break-words leading-relaxed"
                >{{ currentTemplate.content }}</pre
              >
              <button
                @click="
                  copyToClipboard(
                    currentTemplate.content,
                    'Copied content to clipboard',
                    true,
                  )
                "
                class="absolute top-2 right-2 sm:top-3 sm:right-3 icon-btn bg-warm-bg-surface border border-warm-border-subtle"
                title="Copy content"
              >
                <i class="ph-bold ph-copy text-sm"></i>
              </button>
            </div>
            <!-- Single-file download only (.md/.json) - no content available -->
            <div
              v-else-if="hasRawDownloadOnly"
              class="bg-warm-bg-elevated border border-warm-border-subtle rounded-lg p-4 sm:p-6 text-center"
            >
              <i
                class="ph-bold ph-file-text text-3xl text-warm-accent mb-3 block"
              ></i>
              <p class="text-warm-text-secondary text-sm mb-4">
                Download as
                {{
                  ["mcp", "setting", "hook"].includes(currentTemplate.type)
                    ? ".json"
                    : ".md"
                }}
                file
              </p>
              <a
                :href="currentTemplate.rawUrl"
                target="_blank"
                class="btn-primary inline-flex items-center gap-2"
              >
                <i class="ph-bold ph-download-simple"></i>
                Download {{ currentTemplate.name }}.{{
                  ["mcp", "setting", "hook"].includes(currentTemplate.type)
                    ? "json"
                    : "md"
                }}
              </a>
              <p class="text-warm-text-tertiary text-xs mt-3">
                Size:
                {{
                  currentTemplate.size
                    ? (currentTemplate.size / 1024).toFixed(1) + " KB"
                    : "Unknown"
                }}
              </p>
            </div>
            <!-- No content fallback -->
            <div
              v-else
              class="bg-warm-bg-elevated border border-warm-border-subtle rounded-lg p-4 sm:p-6 text-center text-warm-text-tertiary"
            >
              No content available
            </div>
          </div>
        </div>

        <!-- Actions -->
        <div
          class="flex flex-col sm:flex-row items-stretch sm:items-center justify-between px-4 py-3 sm:px-6 sm:py-5 border-t border-warm-border-subtle bg-warm-bg-elevated/50 gap-2 sm:gap-3"
        >
          <button
            @click="downloadTemplate"
            class="btn-secondary order-2 sm:order-1"
          >
            <i
              :class="[
                'ph-bold',
                hasDownloadUrl ? 'ph-file-zip' : 'ph-download-simple',
              ]"
            ></i>
            {{ hasDownloadUrl ? "Download .zip" : "Download" }}
          </button>
          <div class="flex gap-2 sm:gap-3 order-1 sm:order-2">
            <button
              @click="handleToggleCart"
              :class="isInCart ? 'btn-added' : 'btn-secondary'"
              class="flex-1 sm:flex-none"
            >
              <i :class="['ph-bold', isInCart ? 'ph-check' : 'ph-plus']"></i>
              <span class="sm:hidden">{{ isInCart ? "Added" : "Add" }}</span>
              <span class="hidden sm:inline">{{
                isInCart ? "Added" : "Add to Stack"
              }}</span>
            </button>
            <button
              v-if="hasContent && !hasDownloadUrl"
              @click="copyAndClose"
              class="btn-primary flex-1 sm:flex-none"
            >
              <i class="ph-bold ph-copy"></i>
              <span class="sm:hidden">Copy</span>
              <span class="hidden sm:inline">Copy & Close</span>
            </button>
            <button
              v-else
              @click="closeModal"
              class="btn-primary flex-1 sm:flex-none"
            >
              <i class="ph-bold ph-x"></i>
              <span>Close</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </Transition>
</template>
