<template>
  <div>
    <div class="pb-5 border-b border-gray-200 sm:flex sm:items-center sm:justify-between">
      <h3 class="text-lg leading-6 font-medium text-gray-900">
        Analytics Dashboard
      </h3>
      <div class="mt-3 sm:mt-0 sm:ml-4">
        <div class="flex space-x-3">
          <select
            v-model="platformFilter"
            class="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-md"
          >
            <option value="all">All Platforms</option>
            <option value="TikTok">TikTok</option>
            <option value="YouTube">YouTube</option>
            <option value="Instagram">Instagram</option>
          </select>
          <select
            v-model="timeRange"
            class="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-md"
          >
            <option value="7">Last 7 days</option>
            <option value="30">Last 30 days</option>
            <option value="90">Last 90 days</option>
            <option value="365">Last year</option>
          </select>
          <button
            @click="refreshData"
            class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
          >
            <svg class="-ml-1 mr-2 h-5 w-5 text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z" clip-rule="evenodd" />
            </svg>
            Refresh
          </button>
        </div>
      </div>
    </div>

    <div class="mt-6">
      <div v-if="loading" class="flex justify-center">
        <svg class="animate-spin -ml-1 mr-3 h-10 w-10 text-primary-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
      </div>
      <div v-else>
        <!-- Stats Cards -->
        <div class="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
          <!-- Views Card -->
          <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
              <div class="flex items-center">
                <div class="flex-shrink-0 bg-primary-100 rounded-md p-3">
                  <svg class="h-6 w-6 text-primary-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                  </svg>
                </div>
                <div class="ml-5 w-0 flex-1">
                  <dl>
                    <dt class="text-sm font-medium text-gray-500 truncate">
                      Total Views
                    </dt>
                    <dd>
                      <div class="text-lg font-medium text-gray-900">
                        {{ formatNumber(stats.totalViews) }}
                      </div>
                    </dd>
                  </dl>
                </div>
              </div>
              <div class="mt-4">
                <div class="flex items-center justify-between">
                  <div class="text-sm font-medium text-green-600">
                    <span v-if="stats.viewsGrowth > 0" class="text-green-600">
                      +{{ stats.viewsGrowth }}%
                    </span>
                    <span v-else class="text-red-600">
                      {{ stats.viewsGrowth }}%
                    </span>
                    <span class="text-gray-500">vs. previous period</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Followers Card -->
          <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
              <div class="flex items-center">
                <div class="flex-shrink-0 bg-indigo-100 rounded-md p-3">
                  <svg class="h-6 w-6 text-indigo-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                  </svg>
                </div>
                <div class="ml-5 w-0 flex-1">
                  <dl>
                    <dt class="text-sm font-medium text-gray-500 truncate">
                      Total Followers
                    </dt>
                    <dd>
                      <div class="text-lg font-medium text-gray-900">
                        {{ formatNumber(stats.totalFollowers) }}
                      </div>
                    </dd>
                  </dl>
                </div>
              </div>
              <div class="mt-4">
                <div class="flex items-center justify-between">
                  <div class="text-sm font-medium">
                    <span v-if="stats.followersGrowth > 0" class="text-green-600">
                      +{{ stats.followersGrowth }}%
                    </span>
                    <span v-else class="text-red-600">
                      {{ stats.followersGrowth }}%
                    </span>
                    <span class="text-gray-500">vs. previous period</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Engagement Card -->
          <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
              <div class="flex items-center">
                <div class="flex-shrink-0 bg-red-100 rounded-md p-3">
                  <svg class="h-6 w-6 text-red-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                  </svg>
                </div>
                <div class="ml-5 w-0 flex-1">
                  <dl>
                    <dt class="text-sm font-medium text-gray-500 truncate">
                      Engagement Rate
                    </dt>
                    <dd>
                      <div class="text-lg font-medium text-gray-900">
                        {{ stats.engagementRate }}%
                      </div>
                    </dd>
                  </dl>
                </div>
              </div>
              <div class="mt-4">
                <div class="flex items-center justify-between">
                  <div class="text-sm font-medium">
                    <span v-if="stats.engagementGrowth > 0" class="text-green-600">
                      +{{ stats.engagementGrowth }}%
                    </span>
                    <span v-else class="text-red-600">
                      {{ stats.engagementGrowth }}%
                    </span>
                    <span class="text-gray-500">vs. previous period</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Charts Section -->
        <div class="mt-8 grid grid-cols-1 gap-5 lg:grid-cols-2">
          <!-- Views by Platform Chart -->
          <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
              <h3 class="text-lg leading-6 font-medium text-gray-900">Views by Platform</h3>
              <div class="mt-4 h-64">
                <!-- Chart placeholder - in a real app, you would use a chart library like Chart.js -->
                <div class="h-full flex items-center justify-center bg-gray-50 rounded-lg">
                  <div class="text-center">
                    <p class="text-gray-500">Platform Distribution</p>
                    <div class="mt-4 flex justify-center space-x-4">
                      <div v-for="(platform, index) in platformData" :key="index" class="flex flex-col items-center">
                        <div class="w-24 bg-gray-200 rounded-full h-2.5">
                          <div 
                            class="h-2.5 rounded-full" 
                            :class="[
                              index === 0 ? 'bg-blue-600' : 
                              index === 1 ? 'bg-red-600' : 
                              'bg-pink-600'
                            ]"
                            :style="{ width: platform.percentage + '%' }"
                          ></div>
                        </div>
                        <span class="mt-2 text-sm text-gray-600">{{ platform.name }}: {{ platform.percentage }}%</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Growth Trend Chart -->
          <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
              <h3 class="text-lg leading-6 font-medium text-gray-900">Growth Trend</h3>
              <div class="mt-4 h-64">
                <!-- Chart placeholder - in a real app, you would use a chart library like Chart.js -->
                <div class="h-full flex items-center justify-center bg-gray-50 rounded-lg">
                  <div class="text-center">
                    <p class="text-gray-500">Follower Growth Over Time</p>
                    <div class="mt-4 relative h-40 w-full">
                      <div class="absolute bottom-0 left-0 right-0 flex items-end justify-between h-full">
                        <div v-for="(month, index) in growthData" :key="index" class="w-8 mx-1">
                          <div 
                            class="bg-primary-500 rounded-t-sm" 
                            :style="{ height: (month.value / maxGrowthValue * 100) + '%' }"
                          ></div>
                          <div class="text-xs text-gray-500 mt-1">{{ month.label }}</div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Content Performance -->
        <div class="mt-8">
          <div class="bg-white shadow overflow-hidden sm:rounded-lg">
            <div class="px-4 py-5 sm:px-6">
              <h3 class="text-lg leading-6 font-medium text-gray-900">
                Top Performing Content
              </h3>
              <p class="mt-1 max-w-2xl text-sm text-gray-500">
                Your most viewed and engaged content
              </p>
            </div>
            <div class="border-t border-gray-200">
              <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                  <tr>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Content
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Platform
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Views
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Engagement
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Published
                    </th>
                  </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                  <tr v-for="(content, index) in topContent" :key="index">
                    <td class="px-6 py-4 whitespace-nowrap">
                      <div class="flex items-center">
                        <div class="flex-shrink-0 h-10 w-10 bg-gray-200 rounded"></div>
                        <div class="ml-4">
                          <div class="text-sm font-medium text-gray-900">
                            {{ content.title }}
                          </div>
                        </div>
                      </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                      <span :class="[
                        content.platform === 'TikTok' ? 'bg-blue-100 text-blue-800' : 
                        content.platform === 'YouTube' ? 'bg-red-100 text-red-800' : 
                        'bg-pink-100 text-pink-800',
                        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium'
                      ]">
                        {{ content.platform }}
                      </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {{ formatNumber(content.views) }}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {{ content.engagement }}%
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {{ formatDate(content.published) }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';

export default {
  name: 'Analytics',
  setup() {
    const loading = ref(true);
    const platformFilter = ref('all');
    const timeRange = ref('30');
    const stats = ref({
      totalViews: 0,
      viewsGrowth: 0,
      totalFollowers: 0,
      followersGrowth: 0,
      engagementRate: 0,
      engagementGrowth: 0
    });
    const platformData = ref([]);
    const growthData = ref([]);
    const topContent = ref([]);
    
    const maxGrowthValue = computed(() => {
      if (growthData.value.length === 0) return 100;
      return Math.max(...growthData.value.map(item => item.value));
    });
    
    const fetchData = async () => {
      loading.value = true;
      try {
        // In a real app, this would be an API call
        // const response = await axios.get(`/api/analytics?platform=${platformFilter.value}&timeRange=${timeRange.value}`);
        // const data = response.data;
        
        // For demo purposes, we'll use mock data
        setTimeout(() => {
          // Mock stats data
          stats.value = {
            totalViews: 1254789,
            viewsGrowth: 12.5,
            totalFollowers: 87432,
            followersGrowth: 8.3,
            engagementRate: 4.7,
            engagementGrowth: -1.2
          };
          
          // Mock platform distribution data
          platformData.value = [
            { name: 'TikTok', percentage: 45 },
            { name: 'YouTube', percentage: 35 },
            { name: 'Instagram', percentage: 20 }
          ];
          
          // Mock growth data
          growthData.value = [
            { label: 'Jan', value: 45 },
            { label: 'Feb', value: 52 },
            { label: 'Mar', value: 48 },
            { label: 'Apr', value: 70 },
            { label: 'May', value: 75 },
            { label: 'Jun', value: 85 }
          ];
          
          // Mock top content data
          topContent.value = [
            {
              title: 'Relaxing Rain Sounds ASMR',
              platform: 'YouTube',
              views: 254789,
              engagement: 6.8,
              published: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000) // 15 days ago
            },
            {
              title: 'Tapping Sounds for Sleep',
              platform: 'TikTok',
              views: 187432,
              engagement: 7.2,
              published: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) // 7 days ago
            },
            {
              title: 'Whisper ASMR Session',
              platform: 'YouTube',
              views: 142567,
              engagement: 5.9,
              published: new Date(Date.now() - 21 * 24 * 60 * 60 * 1000) // 21 days ago
            },
            {
              title: 'Calming Sounds for Anxiety',
              platform: 'Instagram',
              views: 98765,
              engagement: 4.5,
              published: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000) // 10 days ago
            },
            {
              title: 'Sleep-Inducing ASMR',
              platform: 'TikTok',
              views: 87654,
              engagement: 8.1,
              published: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000) // 5 days ago
            }
          ];
          
          loading.value = false;
        }, 1000);
      } catch (error) {
        console.error('Error fetching analytics data:', error);
        loading.value = false;
      }
    };
    
    const refreshData = () => {
      fetchData();
    };
    
    const formatNumber = (num) => {
      if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M';
      }
      if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K';
      }
      return num.toString();
    };
    
    const formatDate = (date) => {
      if (!date) return '';
      
      const d = new Date(date);
      return d.toLocaleDateString('en-US', {
        month: 'short',
        day: 'numeric',
        year: 'numeric'
      });
    };
    
    onMounted(() => {
      fetchData();
    });
    
    return {
      loading,
      platformFilter,
      timeRange,
      stats,
      platformData,
      growthData,
      maxGrowthValue,
      topContent,
      refreshData,
      formatNumber,
      formatDate
    };
  }
};
</script> 