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

const { isStackModalOpen, currentStack, closeStackModal } = useStackModal();
const { addItem, hasItem, getIcon } = useCart();
const { showNotification } = useNotifications();

const installCommand = computed(() => {
  if (!currentStack.value) return "";
  return `vibery install --stack ${currentStack.value.id}`;
});

const npxCommand = computed(() => {
  if (!currentStack.value) return "";
  return `npx vibery install --stack ${currentStack.value.id}`;
});

// Count templates in cart
const templatesInCart = computed(() => {
  if (!currentStack.value) return 0;
  return currentStack.value.templates.filter((t) => hasItem(t.name)).length;
});

const allInCart = computed(() => {
  if (!currentStack.value) return false;
  return templatesInCart.value === currentStack.value.templates.length;
});

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

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

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

async function copyToClipboard(text: string, message: string) {
  try {
    await navigator.clipboard.writeText(text);
    showNotification(message);
  } catch (err) {
    showNotification("Failed to copy to clipboard", "error");
  }
}

function addAllToCart() {
  if (!currentStack.value) return;

  let added = 0;
  for (const tpl of currentStack.value.templates) {
    if (
      addItem({
        name: tpl.name,
        type: tpl.type as
          | "agent"
          | "command"
          | "mcp"
          | "setting"
          | "hook"
          | "skill",
        description: "",
      })
    ) {
      added++;
    }
  }

  if (added > 0) {
    showNotification(
      `Added ${added} template${added !== 1 ? "s" : ""} to cart`,
    );
  } else {
    showNotification("All templates already in cart");
  }
}

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="isStackModalOpen && currentStack"
      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',
                  currentStack.icon || 'ph-stack',
                  '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"
              >
                {{ currentStack.name }}
              </h2>
              <span class="badge-stack">stack</span>
            </div>
          </div>
          <div class="flex items-center gap-2">
            <ShareButton
              :title="currentStack.name + ' - Vibery'"
              :text="currentStack.description"
              :url="shareUrl"
            />
            <button
              @click="closeStackModal"
              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"
          >
            {{ currentStack.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 Stack
            </label>
            <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>
            <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>

          <!-- Templates in Stack -->
          <div class="mb-4 sm:mb-6">
            <label
              class="block text-xs text-warm-text-tertiary mb-3 uppercase tracking-wider font-semibold"
            >
              Templates ({{ currentStack.templates.length }})
            </label>
            <ul class="space-y-2">
              <li
                v-for="tpl in currentStack.templates"
                :key="tpl.name"
                class="flex items-center gap-3 px-3 py-2 bg-warm-bg-elevated border border-warm-border-subtle rounded-lg"
              >
                <div
                  class="w-7 h-7 rounded-md bg-warm-bg-deep flex items-center justify-center flex-shrink-0"
                >
                  <i
                    :class="[
                      'ph',
                      getIcon(tpl.type as any),
                      'text-warm-accent text-sm',
                    ]"
                  ></i>
                </div>
                <span class="font-mono text-sm text-warm-text-primary flex-1">{{
                  tpl.name
                }}</span>
                <span :class="['badge-' + tpl.type, 'text-2xs']">{{
                  tpl.type
                }}</span>
                <i
                  v-if="hasItem(tpl.name)"
                  class="ph-bold ph-check-circle text-green-500 text-base"
                  title="In cart"
                ></i>
              </li>
            </ul>
          </div>

          <!-- Credits -->
          <div
            v-if="currentStack.credits"
            class="text-xs text-warm-text-tertiary italic border-t border-warm-border-subtle pt-4"
          >
            {{ currentStack.credits }}
          </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"
        >
          <div class="text-xs text-warm-text-tertiary order-2 sm:order-1">
            {{ templatesInCart }}/{{ currentStack.templates.length }} in cart
          </div>
          <div class="flex gap-2 sm:gap-3 order-1 sm:order-2">
            <button
              @click="addAllToCart"
              :class="allInCart ? 'btn-added' : 'btn-primary'"
              class="flex-1 sm:flex-none"
            >
              <i :class="['ph-bold', allInCart ? 'ph-check' : 'ph-plus']"></i>
              <span class="sm:hidden">{{
                allInCart ? "All Added" : "Add All"
              }}</span>
              <span class="hidden sm:inline">{{
                allInCart ? "All in Cart" : "Add All to Cart"
              }}</span>
            </button>
            <button
              @click="closeStackModal"
              class="btn-secondary flex-1 sm:flex-none"
            >
              <i class="ph-bold ph-x"></i>
              Close
            </button>
          </div>
        </div>
      </div>
    </div>
  </Transition>
</template>
