<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { useCart } from "../../composables/useCart";
import { useNotifications } from "../../composables/useNotifications";

const props = defineProps<{
  isOpen: boolean;
}>();

const emit = defineEmits<{
  close: [];
}>();

const {
  items,
  count,
  clearCart,
  removeItem,
  generateCommand,
  generateShareUrl,
  getIcon,
} = useCart();
const { showNotification } = useNotifications();

// Computed values
const isEmpty = computed(() => count.value === 0);
const installCommand = computed(() => generateCommand());
const shareUrl = computed(() => generateShareUrl());

// Share cart
async function shareCart() {
  const url = shareUrl.value;
  if (!url) return;

  const shareData = {
    title: "My Vibery Stack",
    text: `Check out my Claude Code template stack with ${count.value} items`,
    url,
  };

  // Try native share API first
  if (navigator.share && navigator.canShare?.(shareData)) {
    try {
      await navigator.share(shareData);
      return;
    } catch (err: any) {
      if (err.name === "AbortError") return;
    }
  }

  // Fallback: copy to clipboard
  try {
    await navigator.clipboard.writeText(url);
    showNotification("Share link copied to clipboard");
  } catch (err) {
    showNotification("Failed to copy link", "error");
  }
}

// Close on Escape key
function handleKeydown(e: KeyboardEvent) {
  if (e.key === "Escape" && props.isOpen) {
    emit("close");
  }
}

// Add/remove keyboard listener
watch(
  () => props.isOpen,
  (open) => {
    if (open) {
      document.addEventListener("keydown", handleKeydown);
    } else {
      document.removeEventListener("keydown", handleKeydown);
    }
  },
);

// Copy command to clipboard
async function copyCommand() {
  const command = installCommand.value;
  if (!command) return;

  try {
    await navigator.clipboard.writeText(command);
    showNotification("Copied to clipboard");
  } catch (err) {
    showNotification("Failed to copy", "error");
  }
}

async function copyAndClose() {
  await copyCommand();
  emit("close");
}
</script>

<template>
  <!-- Backdrop -->
  <Transition
    enter-active-class="transition-all duration-300"
    enter-from-class="opacity-0 invisible"
    enter-to-class="opacity-100 visible"
    leave-active-class="transition-all duration-300"
    leave-from-class="opacity-100 visible"
    leave-to-class="opacity-0 invisible"
  >
    <div
      v-if="isOpen"
      class="fixed inset-0 bg-black/60 backdrop-blur-sm z-[150]"
      @click="emit('close')"
    ></div>
  </Transition>

  <!-- Sidebar -->
  <aside
    :class="[
      'fixed top-0 h-screen w-[400px] max-md:w-full bg-warm-bg-surface border-l-2 border-warm-accent/30 z-[200]',
      'flex flex-col transition-all duration-300 ease-out shadow-warm-lg backdrop-blur-xl',
      isOpen ? 'right-0' : '-right-[400px] max-md:-right-full',
    ]"
  >
    <!-- Header -->
    <div
      class="flex items-center justify-between px-5 py-4 border-b border-warm-border-subtle"
    >
      <h3 class="text-base font-semibold flex items-center gap-2.5">
        <i class="ph-bold ph-stack text-warm-accent text-xl"></i>
        <span class="gradient-text">Your Stack</span>
      </h3>
      <button class="icon-btn" @click="emit('close')" aria-label="Close cart">
        <i class="ph-bold ph-x text-lg"></i>
      </button>
    </div>

    <!-- Cart Items -->
    <div class="flex-1 overflow-y-auto p-5">
      <!-- Empty State -->
      <p
        v-if="isEmpty"
        class="text-warm-text-tertiary text-sm text-center py-12"
      >
        No templates selected
      </p>

      <!-- Cart Items List -->
      <div v-else class="space-y-2">
        <div v-for="item in items" :key="item.name" class="cart-item">
          <i :class="['cart-item-icon ph', getIcon(item.type)]"></i>
          <span class="cart-item-name">{{ item.name }}</span>
          <button
            class="cart-item-remove"
            @click="removeItem(item.name)"
            :aria-label="`Remove ${item.name}`"
          >
            <i class="ph ph-x text-xs"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- Footer -->
    <div
      v-if="!isEmpty"
      class="p-5 border-t border-warm-border-subtle bg-warm-bg-elevated/50"
    >
      <div class="mb-4">
        <label
          class="block text-2xs text-warm-text-tertiary mb-2 uppercase tracking-wider font-semibold"
        >
          Install Command
        </label>
        <div class="flex gap-2">
          <code
            class="flex-1 bg-warm-bg-elevated border border-warm-accent/30 px-4 py-3 rounded-lg font-mono text-xs text-warm-accent overflow-x-auto whitespace-nowrap shadow-accent"
          >
            {{ installCommand }}
          </code>
          <button
            class="icon-btn bg-warm-bg-elevated border border-warm-border-subtle"
            @click="copyCommand"
            aria-label="Copy command"
            title="Copy"
          >
            <i class="ph-bold ph-copy text-sm"></i>
          </button>
        </div>
      </div>
      <div class="flex gap-2">
        <button class="btn-secondary flex-1 justify-center" @click="clearCart">
          <i class="ph-bold ph-trash text-sm"></i>
          Clear
        </button>
        <button
          class="icon-btn bg-warm-bg-elevated border border-warm-border-subtle"
          @click="shareCart"
          aria-label="Share stack"
          title="Share stack"
        >
          <i class="ph-bold ph-share-network text-sm"></i>
        </button>
        <button class="btn-primary flex-1 justify-center" @click="copyAndClose">
          <i class="ph-bold ph-copy text-sm"></i>
          Copy & Close
        </button>
      </div>
    </div>
  </aside>
</template>
