<script setup lang="ts">
import type { IPlazaPostItem } from "#shared/types";
import { ImageService } from "~/services";

const plazaPosts = ref<IPlazaPostItem[]>([]);
const loading = ref(false);
const errorMessage = ref("");

const loadPlazaPosts = async () => {
  loading.value = true;
  errorMessage.value = "";

  try {
    const res = await ImageService.GetPlazaPosts(1, 20);

    if (res.code === 0 && res.data) {
      plazaPosts.value = res.data.items;
      return;
    }

    errorMessage.value = res.msg || "获取广场图片失败";
  } catch (error) {
    errorMessage.value = getErrorMessage(error, "获取广场图片失败");
  } finally {
    loading.value = false;
  }
};

onMounted(loadPlazaPosts);
</script>

<template>
  <section class="w-full space-y-3">
    <div class="flex items-center justify-between">
      <h2 class="text-base font-medium text-gray-900">广场</h2>
      <el-button size="small" :loading="loading" @click="loadPlazaPosts">
        刷新
      </el-button>
    </div>

    <p v-if="errorMessage" class="text-sm text-red-500">
      {{ errorMessage }}
    </p>

    <p v-else-if="!loading && plazaPosts.length === 0" class="text-sm text-gray-500">
      暂无广场图片
    </p>

    <div v-else class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
      <article
        v-for="item in plazaPosts"
        :key="item.id"
        class="overflow-hidden rounded border border-gray-200 bg-white"
      >
        <img
          :src="item.hostedImageUrl"
          alt="广场图片"
          class="block w-full object-cover"
        />

        <div class="space-y-2 p-3">
          <p class="text-sm leading-6 text-gray-800">
            {{ item.prompt }}
          </p>

          <p class="text-xs text-gray-500">
            {{ item.authorDisplayName }}
          </p>
        </div>
      </article>
    </div>
  </section>
</template>
