<template>
  <main class="models--page">
    <div class="models--container">
      <!-- 헤더 -->
      <div class="models--header">
        <h1 class="models--title">Audi Models</h1>
      </div>

      <!-- 필터 -->
      <div class="models--filter--section">
        <div class="filter--group">
          <!-- 연료 타입 필터 -->
          <div class="filter--dropdown">
            <button
              v-for="fuel in filters.fuelType"
              :key="fuel.id"
              :class="['filter--btn', { active: activeFuelType === fuel.id }]"
              @click="activeFuelType = fuel.id"
            >
              {{ fuel.name }}
            </button>
          </div>

          <!-- 그룹 네임 필터 -->
          <div class="filter--dropdown">
            <button
              v-for="group in filters.groupName"
              :key="group.id"
              :class="['filter--btn', { active: activeGroupName === group.id }]"
              @click="activeGroupName = group.id"
            >
              {{ group.name }}
            </button>
          </div>

          <!-- 바디 타입 필터 -->
          <div class="filter--dropdown">
            <button
              v-for="body in filters.bodyType"
              :key="body.id"
              :class="['filter--btn', { active: activeBodyType === body.id }]"
              @click="activeBodyType = body.id"
            >
              {{ body.name }}
            </button>
          </div>
        </div>
      </div>

      <!-- 차량 그리드 -->
      <div class="models--list--wrap">
        <div class="all--models">전체 모델({{ filteredModels.length }})</div>
        <div class="models--list">
          <div v-for="model in filteredModels" :key="model.id" class="model--item">
            <!-- 이미지 -->
            <h2 class="model--name">
              {{ model.groupName }}
              <div v-if="model.fuelType === 'etron'" class="etron">
                <svg
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                  aria-hidden="true"
                  width="16px"
                  height="16px"
                  class="sc-AxhUy kMyssS sc-fzoant LAaNs"
                >
                  <use href="/img/charging-xs.svg#main"></use>
                </svg>
              </div>
            </h2>
            <div class="model--image--wrap">
              <NuxtLink :to="model.link">
                <img :src="model.image" :alt="model.name" />
              </NuxtLink>
            </div>

            <!-- 정보 -->
            <div class="model--info--wrap">
              {{ getGroupModelCount(model.groupName) }}개의 모델
              <i class="ico"></i>
            </div>
          </div>
        </div>
      </div>

      <!-- 모든 차량 리스트 -->
      <div class="models--list--car">
        <div class="all--car--title">모든 차량 ({{ modelsData.models.length }})</div>
        <div class="car--list">
          <div v-for="car in modelsData.models" :key="car.id" class="car--item">
            <div class="bedge--wrap">
              <div v-if="car.fuelType === 'etron'" class="etron">
                <svg
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                  aria-hidden="true"
                  width="16px"
                  height="16px"
                  class="sc-AxhUy kMyssS sc-fzoant LAaNs"
                >
                  <use href="/img/charging-xs.svg#main"></use>
                </svg>
                Electrified
              </div>
            </div>
            <div class="car--image">
              <NuxtLink :to="car.link">
                <img :src="car.image" :alt="car.name" />
              </NuxtLink>
            </div>
            <div class="car--info">
              <h3 class="car--name">{{ car.fullName }}</h3>
              <NuxtLink :to="car.link" class="car--link">자세히 보기</NuxtLink>
            </div>
          </div>
        </div>
      </div>
    </div>
  </main>
</template>

<script setup>
  const modelsData = ref({
    models: [],
    filters: { fuelType: [], bodyType: [], groupName: [] },
  });
  const activeFuelType = ref("all");
  const activeBodyType = ref("all");
  const activeGroupName = ref("all");

  // 필터 옵션
  const filters = computed(() => modelsData.value.filters);

  // groupName별 모델 개수를 계산하는 함수
  const getGroupModelCount = (groupName) => {
    return modelsData.value.models.filter((model) => model.groupName === groupName)
      .length;
  };

  // 연료 타입 이름 가져오기
  const getFuelTypeName = (fuelType) => {
    const fuelTypes = {
      etron: "전기차",
      hybrid: "하이브리드",
      "gas-diesel": "가솔린/디젤",
    };
    return fuelTypes[fuelType] || fuelType;
  };

  // 필터링된 모델 계산
  const filteredModels = computed(() => {
    let filtered = modelsData.value.models;

    // 연료 타입 필터
    if (activeFuelType.value !== "all") {
      filtered = filtered.filter((model) => model.fuelType === activeFuelType.value);
    }

    // 바디 타입 필터
    if (activeBodyType.value !== "all") {
      filtered = filtered.filter((model) =>
        model.bodyType.includes(activeBodyType.value)
      );
    }

    // 그룹 네임 필터
    if (activeGroupName.value !== "all") {
      filtered = filtered.filter((model) => model.groupName === activeGroupName.value);
    }

    // groupName별로 그룹화하고 각 그룹의 첫 번째 모델만 추출
    const groupedByName = {};

    filtered.forEach((model) => {
      // groupName을 키로 사용
      const groupName = model.groupName;

      // 해당 groupName 그룹이 없으면 생성하고 첫 번째 모델 저장
      if (!groupedByName[groupName]) {
        groupedByName[groupName] = model;
      }
    });

    // 그룹화된 객체에서 값(첫 번째 모델들)만 배열로 반환
    return Object.values(groupedByName);
  });

  onMounted(async () => {
    try {
      const response = await fetch("/models.json");
      const data = await response.json();
      modelsData.value = data;

      console.log("Models data loaded:", data);
    } catch (error) {
      console.error("Failed to load models data:", error);
    }
  });
</script>
