<template>
  <div class="bg-neutral-light min-h-screen py-8 px-4">
    <div class="max-w-md mx-auto">
      <!-- Language Selector -->
      <div class="flex justify-end mb-4">
        <div class="relative language-dropdown">
          <button 
            @click="toggleLanguageDropdown" 
            class="flex items-center space-x-1 px-3 py-1 bg-white rounded-lg shadow text-sm text-neutral-dark hover:bg-neutral-light transition-colors duration-200"
          >
            <span>{{ currentLanguageName }}</span>
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
            </svg>
          </button>
          
          <div 
            v-if="showLanguageDropdown" 
            class="absolute right-0 mt-1 w-36 bg-white rounded-lg shadow-lg py-1 z-10"
          >
            <button 
              v-for="(name, code) in availableLanguages" 
              :key="code" 
              @click.stop="changeLanguage(code)" 
              class="block w-full text-left px-4 py-2 text-sm text-neutral-dark hover:bg-neutral-light"
              :class="{ 'bg-neutral-light': currentLocale === code }"
            >
              {{ name }}
            </button>
          </div>
        </div>
      </div>
      
      <!-- User Profile -->
      <div class="text-center mb-8">
        <div class="w-24 h-24 rounded-full bg-primary mx-auto mb-4 flex items-center justify-center text-white text-2xl font-bold">
          {{ userInitials }}
        </div>
        <h1 class="text-2xl font-bold text-neutral-dark mb-1">{{ userData.name || username }}</h1>
        <p v-if="userData.bio" class="text-neutral">{{ userData.bio }}</p>
      </div>
      
      <!-- Links -->
      <div v-if="loading" class="flex justify-center py-8">
        <div class="spinner"></div>
      </div>
      
      <div v-else-if="links.length === 0" class="text-center py-8 text-neutral">
        {{ $t('linktree.noLinks') }}
      </div>
      
      <div v-else class="space-y-4">
        <!-- Social Media Links -->
        <div v-if="socialLinks.length > 0" class="mb-6">
          <h2 class="text-lg font-medium text-neutral-dark mb-3">{{ $t('linktree.categories.social') }}</h2>
          <div class="space-y-3">
            <a 
              v-for="link in socialLinks" 
              :key="link.id" 
              :href="link.url" 
              target="_blank" 
              class="block w-full py-3 px-4 bg-white rounded-lg shadow text-center font-medium text-primary hover:bg-primary hover:text-white transition-colors duration-200"
            >
              {{ link.title }}
            </a>
          </div>
        </div>
        
        <!-- Donation Links -->
        <div v-if="donationLinks.length > 0" class="mb-6">
          <h2 class="text-lg font-medium text-neutral-dark mb-3">{{ $t('linktree.categories.donation') }}</h2>
          <div class="space-y-3">
            <a 
              v-for="link in donationLinks" 
              :key="link.id" 
              :href="link.url" 
              target="_blank" 
              class="block w-full py-3 px-4 bg-secondary-lavender rounded-lg shadow text-center font-medium text-white hover:bg-secondary-lavender-dark transition-colors duration-200"
            >
              {{ link.title }}
            </a>
          </div>
        </div>
        
        <!-- Affiliate Links -->
        <div v-if="affiliateLinks.length > 0" class="mb-6">
          <h2 class="text-lg font-medium text-neutral-dark mb-3">{{ $t('linktree.categories.affiliate') }}</h2>
          <div class="space-y-3">
            <a 
              v-for="link in affiliateLinks" 
              :key="link.id" 
              :href="link.affiliate_url || link.url" 
              target="_blank" 
              class="block w-full py-3 px-4 bg-accent-yellow rounded-lg shadow text-center font-medium text-neutral-dark hover:bg-accent-yellow-dark transition-colors duration-200"
            >
              {{ link.title }}
            </a>
          </div>
        </div>
        
        <!-- Wishlists -->
        <div v-if="wishlistLinks.length > 0" class="mb-6">
          <h2 class="text-lg font-medium text-neutral-dark mb-3">{{ $t('linktree.categories.wishlist') }}</h2>
          
          <div v-for="link in wishlistLinks" :key="link.id" class="mb-6">
            <h3 class="text-md font-medium text-neutral-dark mb-2">{{ link.title }}</h3>
            
            <div v-if="loadingWishlistItems[link.id]" class="flex justify-center py-4">
              <div class="spinner"></div>
            </div>
            
            <div v-else-if="!wishlistItems[link.id] || wishlistItems[link.id].length === 0" class="bg-white rounded-lg p-4 text-center text-neutral">
              {{ $t('linktree.wishlist.noItems') }}
            </div>
            
            <div v-else class="bg-white rounded-lg p-4 shadow">
              <div class="grid grid-cols-1 gap-4">
                <div 
                  v-for="item in wishlistItems[link.id]" 
                  :key="item.id" 
                  class="border border-neutral-light rounded-lg p-3"
                >
                  <div class="font-medium text-neutral-dark mb-1">{{ item.item_name }}</div>
                  <div v-if="item.price" class="text-sm text-neutral mb-2">
                    {{ item.price }} {{ item.currency }}
                  </div>
                  <a 
                    :href="item.item_url" 
                    target="_blank" 
                    class="inline-block px-3 py-1 bg-accent-coral rounded-lg text-white text-sm font-medium hover:bg-accent-coral-dark transition-colors duration-200"
                  >
                    {{ $t('linktree.wishlist.buyNow') }}
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Footer -->
      <div class="text-center text-sm text-neutral mt-8">
        <p>{{ $t('linktree.publicTitle') }} {{ userData.name || username }}</p>
        <p class="mt-1">
          <a href="/" class="text-primary hover:underline">{{ $t('app.title') }}</a>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import axios from 'axios';

export default {
  setup() {
    const route = useRoute();
    const { t, locale } = useI18n();
    const username = ref(route.params.username);
    const userData = ref({});
    const links = ref([]);
    const loading = ref(true);
    const wishlistItems = ref({});
    const loadingWishlistItems = ref({});
    const showLanguageDropdown = ref(false);
    
    // Language settings
    const availableLanguages = {
      de: 'Deutsch',
      en: 'English',
      ru: 'Русский'
    };
    
    // Initialisiere die Sprache aus dem localStorage
    onMounted(() => {
      const savedLocale = localStorage.getItem('user-locale');
      if (savedLocale && availableLanguages[savedLocale]) {
        locale.value = savedLocale;
      }
    });
    
    const currentLocale = computed(() => locale.value);
    
    const currentLanguageName = computed(() => {
      return availableLanguages[locale.value] || 'Deutsch';
    });
    
    const toggleLanguageDropdown = () => {
      showLanguageDropdown.value = !showLanguageDropdown.value;
    };
    
    const changeLanguage = (lang) => {
      console.log('Changing language to:', lang);
      locale.value = lang;
      localStorage.setItem('user-locale', lang);
      showLanguageDropdown.value = false;
    };
    
    // Close dropdown when clicking outside
    onMounted(() => {
      document.addEventListener('click', (e) => {
        // Nur schließen, wenn außerhalb des Dropdowns geklickt wird
        if (showLanguageDropdown.value && !e.target.closest('.language-dropdown')) {
          showLanguageDropdown.value = false;
        }
      });
    });
    
    // Mock data
    const mockUserData = {
      id: 1,
      name: 'ASMR Creator',
      username: 'asmr_creator',
      bio: 'ASMR Content Creator | Tingles & Relaxation | Neue Videos jeden Mittwoch & Samstag'
    };
    
    const mockLinks = [
      {
        id: 1,
        title: 'Mein TikTok',
        url: 'https://tiktok.com/@asmr_creator',
        category: 'social',
        link_order: 0
      },
      {
        id: 2,
        title: 'YouTube Kanal',
        url: 'https://youtube.com/c/asmr_creator',
        category: 'social',
        link_order: 1
      },
      {
        id: 3,
        title: 'Instagram',
        url: 'https://instagram.com/asmr_creator',
        category: 'social',
        link_order: 2
      },
      {
        id: 4,
        title: 'Unterstütze mich auf Ko-Fi',
        url: 'https://ko-fi.com/asmr_creator',
        category: 'donation',
        link_order: 3
      },
      {
        id: 5,
        title: 'Mein Patreon',
        url: 'https://patreon.com/asmr_creator',
        category: 'donation',
        link_order: 4
      },
      {
        id: 6,
        title: 'Amazon Affiliate Shop',
        url: 'https://amazon.com/shop/asmr_creator',
        category: 'affiliate',
        affiliate_url: 'https://amazon.com/shop/asmr_creator?tag=aff123',
        link_order: 5
      },
      {
        id: 7,
        title: 'Meine ASMR Ausrüstung',
        url: 'https://amazon.com/wishlist/asmr_creator',
        category: 'wishlist',
        link_order: 6
      }
    ];
    
    const mockWishlistItems = {
      7: [
        {
          id: 1,
          user_link_id: 7,
          item_name: '3Dio Free Space Binaural Microphone',
          item_url: 'https://amazon.com/3dio-microphone',
          price: 499.99,
          currency: 'EUR'
        },
        {
          id: 2,
          user_link_id: 7,
          item_name: 'Zoom H6 Recorder',
          item_url: 'https://amazon.com/zoom-h6',
          price: 329.99,
          currency: 'EUR'
        },
        {
          id: 3,
          user_link_id: 7,
          item_name: 'Rode NT1 Mikrofon',
          item_url: 'https://amazon.com/rode-nt1',
          price: 249.99,
          currency: 'EUR'
        }
      ]
    };
    
    // Computed properties for categorized links
    const socialLinks = computed(() => {
      return links.value.filter(link => link.category === 'social');
    });
    
    const donationLinks = computed(() => {
      return links.value.filter(link => link.category === 'donation');
    });
    
    const affiliateLinks = computed(() => {
      return links.value.filter(link => link.category === 'affiliate');
    });
    
    const wishlistLinks = computed(() => {
      return links.value.filter(link => link.category === 'wishlist');
    });
    
    const userInitials = computed(() => {
      if (!userData.value.name) return '';
      
      const nameParts = userData.value.name.split(' ');
      if (nameParts.length === 1) {
        return nameParts[0].charAt(0).toUpperCase();
      }
      
      return (nameParts[0].charAt(0) + nameParts[nameParts.length - 1].charAt(0)).toUpperCase();
    });
    
    // Fetch user data and links
    onMounted(() => {
      // Simulate API call delay
      setTimeout(() => {
        userData.value = mockUserData;
        links.value = mockLinks;
        
        // Initialize wishlist items loading state
        for (const link of links.value) {
          if (link.category === 'wishlist') {
            loadingWishlistItems.value[link.id] = true;
            fetchWishlistItems(link.id);
          }
        }
        
        loading.value = false;
      }, 500);
    });
    
    // Fetch wishlist items
    const fetchWishlistItems = async (linkId) => {
      loadingWishlistItems.value[linkId] = true;
      
      // Simulate API call delay
      setTimeout(() => {
        wishlistItems.value[linkId] = mockWishlistItems[linkId] || [];
        loadingWishlistItems.value[linkId] = false;
      }, 800);
    };
    
    return {
      username,
      userData,
      links,
      loading,
      wishlistItems,
      loadingWishlistItems,
      socialLinks,
      donationLinks,
      affiliateLinks,
      wishlistLinks,
      userInitials,
      showLanguageDropdown,
      availableLanguages,
      currentLocale,
      currentLanguageName,
      toggleLanguageDropdown,
      changeLanguage
    };
  }
};
</script>

<style scoped>
.spinner {
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top: 3px solid #5A8FDD;
  width: 24px;
  height: 24px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 