<template>
  <div class="loja-page">
    <DefaultHeaderPage class="q-px-md" />

    <div class="q-px-md q-pb-md">

      <div class="q-mb-md">
        <q-input
          v-model="search"
          :placeholder="$t('associado.filter_by_category')"
          outlined
          dense
          bg-color="white"
          clearable
        >
          <template #prepend>
            <q-icon name="mdi-magnify" />
          </template>
        </q-input>
      </div>

      <div class="chips-row q-mb-md">
        <div
          :class="['cat-chip', activeTab === 'all' ? 'cat-chip--selected' : 'cat-chip--default']"
          @click="activeTab = 'all'"
        >
          {{ $t('loja.filter_all') }}
        </div>
        <div
          v-for="cat in storeCategories"
          :key="cat.value"
          :class="['cat-chip', activeTab === cat.value ? 'cat-chip--selected' : 'cat-chip--default']"
          @click="activeTab = cat.value"
        >
          {{ cat.label }}
        </div>
        <div
          :class="['cat-chip', activeTab === 'recent' ? 'cat-chip--selected' : 'cat-chip--default']"
          @click="activeTab = 'recent'"
        >
          {{ $t('loja.filter_recent') }}
        </div>
        <div class="cat-chip cat-chip--disabled">
          {{ $t('loja.filter_others') }}
        </div>
      </div>

      <div v-if="loading" class="flex flex-center q-py-xl">
        <q-spinner color="primary" size="48px" />
      </div>

      <div v-else-if="pagedItems.length === 0" class="text-center text-grey q-py-xl">
        {{ $t('http.errors.no_records_found') }}
      </div>

      <div v-else class="items-list">
        <div
          v-for="item in pagedItems"
          :key="item.id"
        >
          <q-card flat bordered class="store-card">
            <q-card-section class="q-pa-sm">
              <div class="row no-wrap store-card-inner">

                <div class="col column justify-between q-pr-sm">
                  <div>
                    <div class="q-mb-xs">
                      <span v-if="item.category?.name" class="badge-category">
                        {{ item.category.name }}
                      </span>
                    </div>

                    <div class="text-subtitle1 text-weight-bold text-violet-medium q-mb-xs leading-tight">
                      {{ item.name }}
                    </div>

                    <div v-if="item.description" class="text-caption text-grey-7 q-mb-sm ellipsis-2-lines">
                      {{ item.description }}
                    </div>

                    <template v-if="item.variations?.length">
                      <div class="text-caption text-grey-6 q-mb-xs">
                        {{ variationTypeLabel(item) }}
                      </div>
                      <div class="row q-gutter-xs q-mb-sm">
                        <div
                          v-for="v in item.variations"
                          :key="v.id"
                          :class="[
                            'variation-tag',
                            activeVariation(item)?.id === v.id
                              ? 'variation-tag--selected'
                              : 'variation-tag--default'
                          ]"
                          @click="selectVariation(item, v)"
                        >
                          {{ v.variation_label }}
                        </div>
                      </div>
                    </template>
                  </div>

                  <div class="column items-start q-mt-sm">
                    <span
                      v-if="priceInfo(item).regular !== null"
                      class="text-caption text-grey-7"
                    >
                      {{ $t("loja.price_non_associate") }}:
                      R$ {{ formatPrice(priceInfo(item).regular) }}
                    </span>
                    <span
                      v-if="priceInfo(item).associate !== null"
                      class="text-body2 text-weight-bold text-violet-dark"
                    >
                      {{ $t("loja.price_associate") }}:
                      R$ {{ formatPrice(priceInfo(item).associate) }}
                    </span>
                  </div>
                </div>

                <div class="store-card-right column items-stretch no-wrap">
                  <div class="store-card-image col">
                    <img
                      v-if="item.media?.length"
                      :src="item.media[0].url"
                      :alt="item.name"
                      class="store-card-img"
                    />
                    <q-icon
                      v-else
                      name="mdi-image-off-outline"
                      size="32px"
                      color="grey-4"
                      class="absolute-center"
                    />
                  </div>

                  <q-btn
                    unelevated
                    size="sm"
                    class="q-mt-xs"
                    :class="item.user_interested ? 'btn-interested' : 'btn-gradient'"
                    :icon="item.user_interested ? 'mdi-check' : 'mdi-thumb-up'"
                    :label="item.user_interested ? $t('loja.btn_interested') : $t('loja.btn_want')"
                    style="width: 100%"
                    padding="5px 8px"
                    @click="toggleInterest(item)"
                  />
                  <q-btn
                    unelevated
                    size="sm"
                    class="q-mt-xs btn-whatsapp"
                    icon="mdi-whatsapp"
                    style="width: 100%"
                    padding="5px 8px"
                    @click="openWhatsAppDialog(item)"
                  />
                </div>

              </div>
            </q-card-section>
          </q-card>
        </div>
      </div>

      <div v-if="totalPages > 1" class="flex flex-center q-mt-lg">
        <q-pagination
          v-model="currentPage"
          :max="totalPages"
          boundary-links
          color="violet-normal"
        />
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { normalizeString } from "src/helpers/utils";
import { getStoreItemsAssociado, toggleInterestAssociado as apiToggleInterest } from "src/api/storeItem";
import { getCategories } from "src/api/category";
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import WhatsAppLojaDialog from "./components/WhatsAppLojaDialog.vue";

const $q = useQuasar();
const { t } = useI18n();

const items = ref([]);
const loading = ref(true);
const search = ref("");
const activeTab = ref("all");
const storeCategories = ref([]);
const currentPage = ref(1);
const perPage = 12;

const selectedVariations = ref({});

const selectVariation = (item, variation) => {
  selectedVariations.value[item.id] = variation;
};

const activeVariation = (item) =>
  selectedVariations.value[item.id] ?? item.variations?.[0] ?? null;

const hasPrice = (price) => price !== null && price !== undefined && price !== "";

const priceInfo = (item) => {
  const v = activeVariation(item);
  const associate = hasPrice(v?.variation_value) ? v.variation_value : item.associate_price;

  if (hasPrice(item.price) && hasPrice(associate)) {
    return { regular: item.price, associate };
  }
  const single = hasPrice(associate) ? associate : item.price;
  return { regular: null, associate: hasPrice(single) ? single : null };
};

const variationTypeLabel = (item) => {
  const type = item.variations?.[0]?.variation_type;
  if (type === "tamanho") return t("loja.variation_tamanho");
  if (type === "cor")     return t("loja.variation_cor");
  if (type === "modelo")  return t("loja.variation_modelo");
  return "";
};

const formatPrice = (price) =>
  Number(price).toLocaleString("pt-BR", { minimumFractionDigits: 2 });

const filteredItems = computed(() => {
  let list = items.value;

  if (activeTab.value === "recent") {
    const cutoff = new Date().setDate(new Date().getDate() - 30);
    list = list.filter((i) => new Date(i.created_at).getTime() >= cutoff);
  } else if (activeTab.value !== "all") {
    list = list.filter((i) => i.category_id === activeTab.value);
  }

  if (search.value) {
    const needle = normalizeString(search.value);
    list = list.filter((i) => normalizeString(i.name || "").includes(needle));
  }

  return list;
});

const totalPages = computed(() => Math.ceil(filteredItems.value.length / perPage));

const pagedItems = computed(() => {
  const start = (currentPage.value - 1) * perPage;
  return filteredItems.value.slice(start, start + perPage);
});

watch([search, activeTab], () => {
  currentPage.value = 1;
});

const toggleInterest = async (item) => {
  try {
    const result = await apiToggleInterest(item.id);
    item.user_interested = result.interested;
    item.interests_count = (item.interests_count ?? 0) + (result.interested ? 1 : -1);
  } catch {
    // silent
  }
};

const openWhatsAppDialog = (item) => {
  const variation = activeVariation(item);
  $q.dialog({
    component: WhatsAppLojaDialog,
    componentProps: {
      item,
      variationLabel: variation?.variation_label ?? null,
    },
  });
};

onMounted(async () => {
  try {
    const [itemsData, catsData] = await Promise.all([
      getStoreItemsAssociado(),
      getCategories("store"),
    ]);
    items.value = itemsData;
    storeCategories.value = catsData.map((c) => ({ label: c.name, value: c.id }));
    itemsData.forEach((item) => {
      if (item.variations?.length) {
        selectedVariations.value[item.id] = item.variations[0];
      }
    });
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
});
</script>

<style scoped lang="scss">
@use "src/css/quasar.variables.scss" as vars;

.loja-page {
  background: vars.$violet-light;
  min-height: calc(100dvh - 68px);
  box-sizing: border-box;
  overflow-x: hidden;
}

.chips-row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 8px;
}

.items-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.store-card {
  width: 100%;
  box-sizing: border-box;
  transition: box-shadow 0.2s;
  border-radius: 12px !important;
  background: white !important;
  overflow: hidden;
  &:hover { box-shadow: 0 4px 16px rgba(102, 29, 117, 0.12); }
}

.store-card-inner {
  min-height: 0;
}

.store-card-right {
  width: 110px;
  min-width: 110px;
  flex-shrink: 0;
}

.store-card-image {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid rgba(102, 29, 117, 0.15);
  background: #f5f0f7;
  min-height: 110px;
}

.store-card-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.ellipsis-2-lines {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

// --- category chips ---
.cat-chip {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 28px;
  padding: 0 12px;
  border-radius: 5px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  user-select: none;
  transition: background 0.15s, color 0.15s;

  &--default  { background: #c9a3dc; color: #fff; }
  &--selected { background: #4d1658; color: #fff; }
  &--disabled {
    background: #c9a3dc;
    color: rgba(255, 255, 255, 0.5);
    cursor: default;
    pointer-events: none;
  }
}

// --- category badge on card ---
.badge-category {
  display: inline-flex;
  align-items: center;
  background: #ede0f5;
  color: #4d1658;
  font-size: 10px;
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 20px;
  line-height: 1.4;
}

// --- variation tags ---
.variation-tag {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 28px;
  height: 26px;
  padding: 0 7px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;
  cursor: pointer;
  user-select: none;
  transition: background 0.15s, color 0.15s;

  &--default  { background: #ede0f5; color: #4d1658; }
  &--selected { background: #4d1658; color: #ede0f5; }
}

// --- buttons ---
.btn-gradient {
  background: linear-gradient(90deg, #4d1658 0%, #8b30a5 100%) !important;
  color: white !important;
  border-radius: 8px !important;
}

.btn-gradient :deep(.q-icon) { color: white !important; }

.btn-interested {
  background: #22c55e !important;
  color: white !important;
  border-radius: 8px !important;
}

.btn-interested :deep(.q-icon) { color: white !important; }

.btn-whatsapp {
  background: #25d366 !important;
  color: white !important;
  border-radius: 8px !important;
}

.btn-whatsapp :deep(.q-icon) { color: white !important; }

// --- text colors ---
.text-violet-dark   { color: #4d1658; }
.text-violet-medium { color: #7b2d97; }
.leading-tight      { line-height: 1.25; }
</style>
