<template>
  <div id="app" class="h-screen flex flex-col">
    <header class="bg-blue-600 text-white p-4 flex-shrink-0">
      <h1 class="text-2xl font-bold">TrackMap</h1>
    </header>
    
    <div class="flex flex-1 overflow-hidden">
      <!-- Left Sidebar -->
      <TrackList 
        :tracks="tracks" 
        :selectedTrackIndex="selectedTrackIndex"
        @track-selected="handleTrackSelected"
        @files-uploaded="handleFilesUploaded"
      />
      
      <!-- Main Content -->
      <div class="flex-1 flex flex-col overflow-hidden">
        <!-- Map - takes full space when no tracks, or flexible space when tracks exist -->
        <div :class="tracks.length > 0 ? 'flex-1' : 'flex-1'" class="p-4">
          <MapView :tracks="tracks" :selectedTrackIndex="selectedTrackIndex" />
        </div>
        
        <!-- Statistics Section - only shows when tracks exist -->
        <div v-if="tracks.length > 0" class="border-t border-gray-200 bg-white">
          <!-- Selected Track Details -->
          <div v-if="selectedTrack" class="p-4">
            <h3 class="text-lg font-medium mb-3">{{ selectedTrack.name }}</h3>
            <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
              <div class="text-center">
                <div class="text-xl font-bold text-blue-600">{{ formatDistance(selectedTrack.stats?.distance || 0) }}</div>
                <div class="text-sm text-gray-600">Distance</div>
              </div>
              <div class="text-center">
                <div class="text-xl font-bold text-green-600">{{ formatDuration(selectedTrack.stats?.duration || 0) }}</div>
                <div class="text-sm text-gray-600">Duration</div>
              </div>
              <div class="text-center">
                <div class="text-xl font-bold text-orange-600">{{ selectedTrack.stats?.avgSpeed || 0 }} km/h</div>
                <div class="text-sm text-gray-600">Avg Speed</div>
              </div>
              <div class="text-center">
                <div class="text-xl font-bold text-red-600">{{ selectedTrack.stats?.elevationGain || 0 }}m</div>
                <div class="text-sm text-gray-600">Elevation Gain</div>
              </div>
              <div class="text-center">
                <div class="text-xl font-bold text-purple-600">{{ formatDate(selectedTrack.stats?.startTime) }}</div>
                <div class="text-sm text-gray-600">Date</div>
              </div>
            </div>
          </div>
          
          <!-- Total Statistics -->
          <div v-else class="p-4">
            <h3 class="text-lg font-medium mb-3">Total Statistics</h3>
            <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
              <div class="text-center">
                <div class="text-xl font-bold text-blue-600">{{ totalStats.totalTracks }}</div>
                <div class="text-sm text-gray-600">Total Tracks</div>
              </div>
              <div class="text-center">
                <div class="text-xl font-bold text-green-600">{{ totalStats.totalDistance }}</div>
                <div class="text-sm text-gray-600">Total Distance (km)</div>
              </div>
              <div class="text-center">
                <div class="text-xl font-bold text-purple-600">{{ totalStats.totalDuration }}</div>
                <div class="text-sm text-gray-600">Total Hours</div>
              </div>
              <div class="text-center">
                <div class="text-xl font-bold text-orange-600">{{ totalStats.avgSpeed }}</div>
                <div class="text-sm text-gray-600">Avg Speed (km/h)</div>
              </div>
              <div class="text-center">
                <div class="text-xl font-bold text-red-600">{{ totalStats.totalElevationGain }}</div>
                <div class="text-sm text-gray-600">Elevation Gain (m)</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import MapView from './components/MapView.vue'
import FileUpload from './components/FileUpload.vue'
import TrackList from './components/TrackList.vue'
import { useTracks } from './composables/useTracks.js'

export default {
  name: 'App',
  components: {
    MapView,
    FileUpload,
    TrackList
  },
  setup() {
    const { tracks, addTracks, totalStats } = useTracks()
    const isLoading = ref(false)
    const selectedTrackIndex = ref(null)
    
    const selectedTrack = computed(() => {
      return selectedTrackIndex.value !== null ? tracks[selectedTrackIndex.value] : null
    })
    
    const handleFilesUploaded = async (files) => {
      isLoading.value = true
      try {
        const newTracks = await addTracks(files)
        console.log('Parsed tracks:', newTracks)
        console.log('Total stats:', totalStats.value)
      } catch (error) {
        console.error('Error processing files:', error)
      } finally {
        isLoading.value = false
      }
    }
    
    const handleTrackSelected = (index) => {
      selectedTrackIndex.value = selectedTrackIndex.value === index ? null : index
    }
    
    const formatDistance = (distance) => {
      const km = distance / 1000
      return km < 10 ? km.toFixed(2) + ' km' : km.toFixed(1) + ' km'
    }
    
    const formatDuration = (duration) => {
      if (!duration) return '0m'
      const hours = Math.floor(duration / 3600)
      const minutes = Math.floor((duration % 3600) / 60)
      
      if (hours > 0) {
        return `${hours}h ${minutes}m`
      }
      return `${minutes}m`
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return 'Unknown date'
      const date = new Date(dateString)
      return date.toLocaleDateString('en-US', {
        month: 'short',
        day: 'numeric',
        year: 'numeric'
      })
    }
    
    return {
      tracks,
      totalStats,
      isLoading,
      selectedTrackIndex,
      selectedTrack,
      handleFilesUploaded,
      handleTrackSelected,
      formatDistance,
      formatDuration,
      formatDate
    }
  }
}
</script>