<script lang="ts">
  import { profiles } from '$lib/profiles';
  import { flip } from 'svelte/animate';
  import { quintOut } from 'svelte/easing';
  import { spring } from 'svelte/motion';
  
  interface Profile {
    id: string;
    name: string;
    interests: string[];
    moodImages?: string[];
    location?: {
      x: number;
      y: number;
    };
  }

  // Use proper typing for the stack
  let currentIndex = 0;
  let stack: Profile[] = profiles;
  let connections: Profile[] = [];
  let dragging: Profile | null = null;
  let dragStartOffset = { x: 0, y: 0 };
  
  // Add proper typing to spring
  let dragCoords = spring<{x: number, y: number}>({ x: 0, y: 0 }, {
    stiffness: 0.2,
    damping: 0.7
  });

  // Add proper return type
  const calculateConnectionPath = (connection: Profile): string => {
    const start = connection.location || { x: 500, y: 250 };
    // Store window dimensions to avoid repeated access
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;
    const end = { x: windowWidth - 100, y: windowHeight - 100 };
    const controlPoint = {
      x: (start.x + end.x) / 2,
      y: Math.min(start.y, end.y) - 100
    };
    return `M ${start.x},${start.y} Q ${controlPoint.x},${controlPoint.y} ${end.x},${end.y}`;
  };

  // Type the action parameter properly
  const handleAction = (action: 'skip' | 'decide' | 'add'): void => {
    if (stack.length === 0) return;
    
    const profile = stack[currentIndex];
    
    if (action === 'add') {
      const draggedLocation = { x: $dragCoords.x, y: $dragCoords.y };
      connections = [...connections, { ...profile, location: draggedLocation }];
      
      const suitcase = document.querySelector('#suitcase');
      const profileCard = document.querySelector(`#profile-${profile.id}`);
      
      if (suitcase && profileCard) {
        animateProfileToSuitcase(profileCard, suitcase);
      }
    }

    // Remove the current profile and update the stack
    stack = stack.filter((_, i) => i !== currentIndex);
    currentIndex = Math.min(currentIndex, stack.length - 1);
  };

  // Extract animation logic to a separate function
  const animateProfileToSuitcase = (profileCard: Element, suitcase: Element): void => {
    const clone = profileCard.cloneNode(true) as HTMLElement;
    document.body.appendChild(clone);
    
    const start = profileCard.getBoundingClientRect();
    const end = suitcase.getBoundingClientRect();
    
    clone.style.position = 'fixed';
    clone.style.left = `${start.left}px`;
    clone.style.top = `${start.top}px`;
    clone.style.width = `${start.width}px`;
    clone.style.transition = 'all 0.5s cubic-bezier(0.4, 0, 0.2, 1)';
    clone.style.zIndex = '9999';
    
    requestAnimationFrame(() => {
      clone.style.transform = `translate(${end.left - start.left}px, ${end.top - start.top}px) scale(0.1) rotate(360deg)`;
      clone.style.opacity = '0';
    });
    
    setTimeout(() => clone.remove(), 500);
  };

  const startDrag = (event: MouseEvent, profile: Profile): void => {
    const element = event.currentTarget as HTMLElement;
    const rect = element.getBoundingClientRect();
    
    dragStartOffset = {
      x: event.clientX - rect.left,
      y: event.clientY - rect.top
    };
    
    dragging = profile;
    dragCoords.set({
      x: event.clientX - dragStartOffset.x,
      y: event.clientY - dragStartOffset.y
    });
    
    document.body.style.cursor = 'grabbing';
  };

  function handleMouseMove(event: MouseEvent): void {
    if (dragging) {
      dragCoords.set({
        x: event.clientX - dragStartOffset.x,
        y: event.clientY - dragStartOffset.y
      });
    }
  }

  function handleMouseUp(): void {
    if (dragging) {
      const suitcase = document.querySelector('#suitcase');
      if (suitcase) {
        const suitcaseRect = suitcase.getBoundingClientRect();
        const dragRect = document.querySelector(`#profile-${dragging.id}`)?.getBoundingClientRect();
        
        if (dragRect && isOverlapping(dragRect, suitcaseRect)) {
          handleAction('add');
        }
      }
      dragging = null;
      document.body.style.cursor = '';
    }
  }

  function isOverlapping(rect1: DOMRect, rect2: DOMRect): boolean {
    return !(rect1.right < rect2.left || 
            rect1.left > rect2.right || 
            rect1.bottom < rect2.top || 
            rect1.top > rect2.bottom);
  }

  function handleKeyDown(event: KeyboardEvent, profile: Profile): void {
    if (event.key === 'Enter' || event.key === ' ') {
      const element = event.currentTarget as HTMLElement;
      const rect = element.getBoundingClientRect();
      
      startDrag(new MouseEvent('mousedown', {
        clientX: rect.left + rect.width / 2,
        clientY: rect.top + rect.height / 2
      }), profile);
    }
  }

  // Add cleanup for window event listeners
  import { onDestroy } from 'svelte';
  
  onDestroy(() => {
    document.body.style.cursor = '';
  });
</script>

<svelte:window on:mousemove={handleMouseMove} on:mouseup={handleMouseUp} />

<div class="h-full font-handwritten relative overflow-hidden">
  <!-- Interactive World Map Background -->
  <div class="absolute inset-0 opacity-25 z-0 pointer-events-none">
    <svg viewBox="0 0 1000 500" class="w-full h-full" role="presentation">
      {#each connections as connection (connection.id)}
        <path d={calculateConnectionPath(connection)} 
              class="stroke-pink-400/40 stroke-2 animate-dash" 
              fill="none" />
      {/each}
    </svg>
  </div>

  <!-- Suitcase Collector -->
  <div id="suitcase" 
       role="button"
       tabindex="0"
       aria-label="Collected connections: {connections.length}"
       class="fixed bottom-8 right-8 w-24 h-16 bg-amber-500/80 rotate-12 shadow-xl rounded-lg z-30 
              transition-all hover:rotate-6 hover:scale-110 hover:shadow-2xl
              {dragging ? 'scale-125 ring-4 ring-green-400 ring-opacity-50' : ''}"
       style="transform-origin: center;">
    <span class="absolute -top-2 -left-2 text-4xl" aria-hidden="true">🧳</span>
    <span class="absolute bottom-1 right-1 text-sm font-bold text-white" aria-hidden="true">
      {connections.length}
    </span>
  </div>

  <!-- Profile Stack -->
  <div class="relative h-screen flex items-center justify-center">
    {#each stack as profile, i (profile.id)}
      <div id={`profile-${profile.id}`}
           role="button"
           tabindex="0"
           aria-label="Profile card for {profile.name}"
           class="absolute cursor-grab active:cursor-grabbing transition-transform duration-200
                  {dragging === profile ? 'z-50' : ''}"
           style={`transform: ${dragging !== profile ? 
                  `rotate(${Math.random() * 8 - 4}deg) 
                   translate(${Math.random() * 20 - 10}px, ${Math.random() * 20 - 10}px)` : 
                  'none'};
                  z-index: ${1000 - i};
                  ${dragging === profile ? 
                    `position: fixed; left: ${$dragCoords.x}px; top: ${$dragCoords.y}px; transform: none;` : 
                    ''}`}
           animate:flip={{ delay: i * 50, duration: 800, easing: quintOut }}
           on:mousedown={(e) => startDrag(e, profile)}
           on:keydown={(e) => handleKeyDown(e, profile)}>
        <div class="bg-white p-6 rounded-lg shadow-xl border-4 border-double border-amber-700
                    transition-all hover:shadow-2xl hover:scale-105 origin-center
                    backdrop-blur-sm bg-opacity-90"
             style="width: min(80vw, 400px);">
          <h3 class="text-3xl mb-4 text-cyan-800">{profile.name}</h3>
          <div class="flex flex-wrap gap-2 mb-4">
            {#each profile.interests as interest (interest)}
              <span class="px-3 py-1 bg-yellow-200/50 rounded-full 
                          border-2 border-dashed border-amber-600/30">
                {interest}
              </span>
            {/each}
          </div>
          <div class="h-48 bg-stone-50 rounded border-2 border-stone-200 mb-4 relative overflow-hidden">
            {#if profile.moodImages}
              {#each profile.moodImages as img, index (img)}
                <img src={img} 
                     alt={`Mood image ${index + 1} for ${profile.name}`}
                     class="absolute w-16 h-16 object-cover shadow-lg border-4 border-white"
                     style={`left: ${Math.random() * 60}%; 
                            top: ${Math.random() * 60}%;
                            transform: rotate(${Math.random() * 24 - 12}deg);`} />
              {/each}
            {/if}
          </div>
        </div>
      </div>
    {/each}
  </div>

  <!-- Action Buttons -->
  <div class="fixed bottom-8 left-8 flex gap-4 z-30">
    <button on:click={() => handleAction('skip')}
            aria-label="Skip profile"
            class="h-24 w-24 bg-red-500/90 rotate-12 shadow-xl rounded-lg 
                   flex items-center justify-center text-white text-4xl
                   hover:rotate-0 hover:scale-125 transition-all active:scale-95
                   disabled:opacity-50 disabled:cursor-not-allowed"
            disabled={stack.length === 0}>
      <span class="rotate--12" aria-hidden="true">✕</span>
    </button>
    
    <button on:click={() => handleAction('decide')}
            aria-label="Decide later"
            class="h-24 w-24 bg-purple-500/90 -rotate-6 shadow-xl rounded-lg 
                   flex items-center justify-center text-white text-4xl
                   hover:rotate-3 hover:scale-125 transition-all active:scale-95
                   disabled:opacity-50 disabled:cursor-not-allowed"
            disabled={stack.length === 0}>
      <span class="rotate-6" aria-hidden="true">⌛</span>
    </button>
    
    <button on:click={() => handleAction('add')}
            aria-label="Add to connections"
            class="h-24 w-24 bg-green-500/90 rotate-3 shadow-xl rounded-lg 
                   flex items-center justify-center text-white text-4xl
                   hover:-rotate-12 hover:scale-125 transition-all active:scale-95
                   disabled:opacity-50 disabled:cursor-not-allowed"
            disabled={stack.length === 0}>
      <span class="rotate--3" aria-hidden="true">➕</span>
    </button>
  </div>

  <!-- Dragging Preview -->
  {#if dragging}
    <div class="fixed pointer-events-none z-50"
         role="status"
         aria-live="polite"
         style={`left: ${$dragCoords.x}px; top: ${$dragCoords.y}px;
                transform: translate(-50%, -50%) rotate(${Math.random() * 25 - 12.5}deg);`}>
      <div class="bg-white p-4 rounded shadow-xl border-2 border-dashed border-amber-600">
        Taking {dragging.name} on adventure!
      </div>
    </div>
  {/if}
</div>

<style>
  @keyframes dash {
    to {
      stroke-dashoffset: -100;
    }
  }

  .animate-dash {
    stroke-dasharray: 10;
    animation: dash 10s linear infinite;
  }

  .cursor-grab {
    cursor: grab;
    user-select: none;
  }

  .cursor-grabbing {
    cursor: grabbing;
    user-select: none;
  }
</style>