<template>
  <div
    class="barneo-sort-widget"
    :class="{
      'barneo-sort-widget--dark': mergedConfig.darkMode === true,
      'barneo-sort-widget--light': mergedConfig.darkMode === false,
    }"
  >
    <!-- Состояние ошибки -->
    <div v-if="state.error" class="barneo-sort-error">
      <slot name="error" :error="state.error">
        <div class="barneo-sort-error-message">
          {{ state.error }}
        </div>
      </slot>
    </div>

    <!-- Основной контент -->
    <div v-else class="barneo-sort-content">
      <slot name="sort-options" :sort-options="sortOptions" :current-sort="state.currentSort" :is-loading="isLoading" :handle-sort-change="handleSortChangeWithEmit">
        <div class="barneo-sort-options">
          <button
            v-for="option in sortOptions"
            :key="option.value"
            :class="[
              'barneo-sort-option',
              {
                'barneo-sort-option--active': option.value === state.currentSort,
                'barneo-sort-option--disabled': isLoading,
              },
            ]"
            :disabled="isLoading"
            @click="handleSortChangeWithEmit(option.value)"
          >
            <slot
              name="sort-option"
              :option="option"
              :is-active="option.value === state.currentSort"
              :is-disabled="isLoading"
            >
              <div class="barneo-sort-option-content">
                <span class="barneo-sort-option-label">{{ option.label }}</span>
              </div>
            </slot>

            <!-- Индикатор загрузки только для активной сортировки -->
            <div
              v-if="option.value === state.currentSort && isLoading"
              class="barneo-sort-loading-indicator"
            >
              <div class="barneo-sort-loading-spinner"></div>
            </div>
          </button>
        </div>
      </slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useSortWidget } from "../composables/useSortWidget";
import { useBarneoConfig } from "../../../config/BarneoConfigManager";
import { computed } from "vue";
import type { BarneoSortWidgetProps, SortWidgetEmits } from "../types";

const props = withDefaults(defineProps<BarneoSortWidgetProps>(), {
  config: () => ({}),
});

const emit = defineEmits<SortWidgetEmits>();

// Получаем глобальную конфигурацию
const { sortWidgetConfig } = useBarneoConfig();

// Объединяем глобальную конфигурацию с пропсами
const mergedConfig = computed(() => ({
  ...sortWidgetConfig,
  ...props.config,
}));

const { state, sortOptions, isLoading, handleSortChange } = useSortWidget(
  mergedConfig.value
);

// Эмитим события при изменении состояния
const handleSortChangeWithEmit = async (sortValue: string) => {
  await handleSortChange(sortValue);
  emit("sort-change", sortValue);
  emit("loading", isLoading.value);
  if (state.value.error) {
    emit("error", state.value.error);
  }
};
</script>
