import { ref, computed } from 'vue'
import { parseGPXFile } from '../utils/gpxParser.js'

const tracks = ref([])

export const useTracks = () => {
  const addTracks = async (files) => {
    const newTracks = []
    
    for (const file of files) {
      try {
        const parsedTracks = await parseGPXFile(file)
        newTracks.push(...parsedTracks)
      } catch (error) {
        console.error(`Error parsing ${file.name}:`, error)
      }
    }
    
    tracks.value.push(...newTracks)
    return newTracks
  }
  
  const removeTracks = (trackIndices) => {
    trackIndices.sort((a, b) => b - a) // Sort descending to remove from end first
    trackIndices.forEach(index => {
      tracks.value.splice(index, 1)
    })
  }
  
  const clearAllTracks = () => {
    tracks.value = []
  }
  
  const totalStats = computed(() => {
    if (tracks.value.length === 0) {
      return {
        totalTracks: 0,
        totalDistance: 0,
        totalDuration: 0,
        totalElevationGain: 0,
        avgSpeed: 0
      }
    }
    
    const totals = tracks.value.reduce((acc, track) => {
      if (track.stats) {
        acc.distance += track.stats.distance || 0
        acc.duration += track.stats.duration || 0
        acc.elevationGain += track.stats.elevationGain || 0
      }
      return acc
    }, { distance: 0, duration: 0, elevationGain: 0 })
    
    return {
      totalTracks: tracks.value.length,
      totalDistance: Math.round(totals.distance / 1000 * 10) / 10, // km
      totalDuration: Math.round(totals.duration / 3600 * 10) / 10, // hours
      totalElevationGain: Math.round(totals.elevationGain), // meters
      avgSpeed: totals.duration > 0 ? 
        Math.round((totals.distance / totals.duration) * 3.6 * 10) / 10 : 0 // km/h
    }
  })
  
  return {
    tracks: tracks.value,
    addTracks,
    removeTracks,
    clearAllTracks,
    totalStats
  }
}