<template>
  <FlexCol padding="space.md">
    <HomeTitle title="我关注/加入的村社" />
    <RequireLogin unLoginMessage="登录后查看我的关注村社" @loginSuccess="villageStore.loadMyFollowVillages()">
      <FlexCol gap="gap.md">
        <Empty v-if="villageList.length === 0" description="还没有关注村社哦" />
        <FlexRow 
          v-for="(item, i) in villageList"
          :key="i"
          justify="space-between" align="center" gap="gap.md"
        >
          <ImageBlock3
            backgroundColor="transparent"
            :src="item.image"
            defaultImage="https://xy.wenlvti.net/app_static/images/village/PlaceholderVillage.jpg"
            :title="item.name"
            :desc="item.address"
            :imageRadius="15"
            :imageWidth="200"
            :imageHeight="140"
            @click="emit('goDetails', item as VillageListItem)"
          />
          <FlexRow justify="flex-end" align="center" gap="gap.md" width="200rpx">
            <Tag v-if="item.isFollow" text="已关注" size="small" />
            <Tag v-if="item.isJoined" text="已加入" size="small" type="primary" />
          </FlexRow>
        </FlexRow>
      </FlexCol>
    </RequireLogin>
  </FlexCol>
</template>

<script setup lang="ts">
import FlexCol from '@/components/layout/FlexCol.vue';
import HomeTitle from '@/common/components/parts/HomeTitle.vue';
import ImageBlock3 from '@/components/display/block/ImageBlock3.vue';
import RequireLogin from '@/common/components/RequireLogin.vue';
import type { VillageListItem } from '@/api/light/LightVillageApi';
import { useVillageStore } from '@/store/village';
import Empty from '@/components/feedback/Empty.vue';
import { computed } from 'vue';
import Tag from '@/components/display/Tag.vue';
import FlexRow from '@/components/layout/FlexRow.vue';

const emit = defineEmits<{
  (e: 'goDetails', item: VillageListItem): void;
}>();
const villageStore = useVillageStore();

const villageList = computed(() => {
  const followMap = new Map<number, typeof villageStore.myFollowVillages[0]>();
  
  villageStore.myFollowVillages.forEach(item => {
    followMap.set(item.id, { ...item, isFollow: true, isJoined: false });
  });
  
  villageStore.myJoinedVillages.forEach(item => {
    const existing = followMap.get(item.id);
    if (existing) {
      existing.isJoined = true;
    } else {
      followMap.set(item.id, { ...item, isFollow: false, isJoined: true });
    }
  });
  
  return Array.from(followMap.values());
});


</script>