document.head.insertAdjacentHTML('beforeend','<style type="text/tailwindcss">'+stylFns['app/shared/FilterSort/index.styl']+'</style>')

module.exports =
  name: 'FilterSort'
  render: (new Function '_ctx', '_cache', renderFns['app/shared/FilterSort/index.pug'])()
  props:
    items:
      type: Array
      default: -> []
    filters:
      type: Object
      default: -> {}
    sortOptions:
      type: Array
      default: -> [
        { value: 'date-asc', label: 'По дате (сначала ближайшие)' }
        { value: 'date-desc', label: 'По дате (сначала дальние)' }
        { value: 'price-asc', label: 'По цене (сначала дешевые)' }
        { value: 'price-desc', label: 'По цене (сначала дорогие)' }
        { value: 'name-asc', label: 'По названию (А-Я)' }
        { value: 'name-desc', label: 'По названию (Я-А)' }
      ]

  data: ->
    selectedFilters:
      categories: []
      dateRange: 'all'
      priceRange:
        min: 0
        max: 500
    selectedSort: 'date-asc'
    activeFilters: []
    filterOptions:
      categories: [
        { value: 'classical', label: 'Классическая музыка' }
        { value: 'folk', label: 'Фольклор' }
        { value: 'jazz', label: 'Джаз' }
        { value: 'pop', label: 'Поп-музыка' }
        { value: 'theater', label: 'Театр' }
        { value: 'dance', label: 'Танцевальные шоу' }
      ]
      dateRanges: [
        { value: 'today', label: 'Сегодня' }
        { value: 'week', label: 'На этой неделе' }
        { value: 'month', label: 'В этом месяце' }
        { value: 'all', label: 'Все даты' }
      ]

  mounted: ->
    @loadFromURL()
    @updateActiveFilters()

  methods:
    applyFilters: ->
      filteredItems = @filterItems(@items)
      sortedItems = @sortItems(filteredItems)
      @updateURL()
      @$emit 'filter-changed', sortedItems

    filterItems: (items) ->
      items.filter (item) =>
        # Фильтр по категориям
        categoryMatch = @selectedFilters.categories.length == 0 || 
          @selectedFilters.categories.includes(item.category)
        
        # Фильтр по дате (упрощенный)
        dateMatch = @selectedFilters.dateRange == 'all' || 
          @checkDateMatch(item.date, @selectedFilters.dateRange)
        
        # Фильтр по цене
        priceMatch = (!item.price || 
          (item.price >= @selectedFilters.priceRange.min && 
           item.price <= @selectedFilters.priceRange.max))
        
        categoryMatch && dateMatch && priceMatch

    sortItems: (items) ->
      sorted = [...items]
      switch @selectedSort
        when 'date-asc'
          sorted.sort (a, b) -> new Date(a.date) - new Date(b.date)
        when 'date-desc'
          sorted.sort (a, b) -> new Date(b.date) - new Date(a.date)
        when 'price-asc'
          sorted.sort (a, b) -> (a.price || 0) - (b.price || 0)
        when 'price-desc'
          sorted.sort (a, b) -> (b.price || 0) - (a.price || 0)
        when 'name-asc'
          sorted.sort (a, b) -> a.title.localeCompare(b.title)
        when 'name-desc'
          sorted.sort (a, b) -> b.title.localeCompare(a.title)
      sorted

    checkDateMatch: (itemDate, range) ->
      # Упрощенная проверка даты
      now = new Date()
      itemDateObj = new Date(itemDate)
      
      switch range
        when 'today'
          return itemDateObj.toDateString() == now.toDateString()
        when 'week'
          weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
          return itemDateObj >= weekAgo && itemDateObj <= now
        when 'month'
          monthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate())
          return itemDateObj >= monthAgo && itemDateObj <= now
        else
          return true

    handleFilterChange: ->
      @updateActiveFilters()
      @applyFilters()

    handleSortChange: ->
      @applyFilters()

    resetFilters: ->
      @selectedFilters =
        categories: []
        dateRange: 'all'
        priceRange:
          min: 0
          max: 500
      @selectedSort = 'date-asc'
      @updateActiveFilters()
      @applyFilters()

    updateActiveFilters: ->
      active = []
      
      if @selectedFilters.categories.length > 0
        categoryLabels = @selectedFilters.categories.map (cat) =>
          category = @filterOptions.categories.find (c) -> c.value == cat
          category?.label || cat
        active.push("Категории: #{categoryLabels.join(', ')}")
      
      if @selectedFilters.dateRange != 'all'
        dateRange = @filterOptions.dateRanges.find (d) -> d.value == @selectedFilters.dateRange
        active.push("Дата: #{dateRange?.label}")
      
      if @selectedFilters.priceRange.min > 0 || @selectedFilters.priceRange.max < 500
        active.push("Цена: #{@selectedFilters.priceRange.min}-#{@selectedFilters.priceRange.max} сомони")
      
      @activeFilters = active

    removeFilter: (index) ->
      filter = @activeFilters[index]
      
      if filter.startsWith('Категории:')
        @selectedFilters.categories = []
      else if filter.startsWith('Дата:')
        @selectedFilters.dateRange = 'all'
      else if filter.startsWith('Цена:')
        @selectedFilters.priceRange = { min: 0, max: 500 }
      
      @updateActiveFilters()
      @applyFilters()

    updateURL: ->
      # Синхронизация с URL :cite[4]
      return unless window.history
      
      params = new URLSearchParams()
      
      if @selectedFilters.categories.length > 0
        params.set('categories', @selectedFilters.categories.join(','))
      
      if @selectedFilters.dateRange != 'all'
        params.set('date', @selectedFilters.dateRange)
      
      if @selectedFilters.priceRange.min > 0
        params.set('price_min', @selectedFilters.priceRange.min)
      
      if @selectedFilters.priceRange.max < 500
        params.set('price_max', @selectedFilters.priceRange.max)
      
      params.set('sort', @selectedSort)
      
      url = "#{window.location.pathname}?#{params.toString()}"
      window.history.replaceState({}, '', url)

    loadFromURL: ->
      return unless window.location.search
      
      params = new URLSearchParams(window.location.search)
      
      if params.get('categories')
        @selectedFilters.categories = params.get('categories').split(',')
      
      if params.get('date')
        @selectedFilters.dateRange = params.get('date')
      
      if params.get('price_min')
        @selectedFilters.priceRange.min = parseInt(params.get('price_min'))
      
      if params.get('price_max')
        @selectedFilters.priceRange.max = parseInt(params.get('price_max'))
      
      if params.get('sort')
        @selectedSort = params.get('sort')
      
      @updateActiveFilters()

  emits: ['filter-changed', 'sort-changed']
