<template>
  <div class="text-sm">
    <div class="flex items-center gap-1 font-medium text-gray-700 mb-1">
      <span class="material-icons" style="font-size: 14px">manage_accounts</span>
      <span>{{ t("pluginManageRoles.previewCount", customRoles.length, { named: { count: customRoles.length } }) }}</span>
    </div>
    <div v-for="role in customRoles" :key="role.id" class="text-xs text-gray-600 flex items-center gap-1">
      <span class="material-icons" style="font-size: 12px">{{ role.icon }}</span>
      {{ role.name }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import type { ToolResultComplete } from "gui-chat-protocol/vue";
import type { ManageRolesData, CustomRole } from "./index";
import { useFreshPluginData } from "../../composables/useFreshPluginData";
import { pluginEndpoints } from "../api";
import type { RolesEndpoints } from "./definition";
import { parseCustomRoles } from "./roleForm";

const { t } = useI18n();

const props = defineProps<{ result: ToolResultComplete<ManageRolesData> }>();
const customRoles = ref<CustomRole[]>(props.result.data?.customRoles ?? []);

const endpoints = pluginEndpoints<RolesEndpoints>("roles");

const { refresh } = useFreshPluginData<CustomRole[]>({
  endpoint: () => endpoints.list,
  extract: parseCustomRoles,
  apply: (data) => {
    customRoles.value = data;
  },
});

// Watch the data itself — not just uuid — because the View emits
// updateResult with the same uuid after an in-place edit. A uuid-only
// watch would miss those updates and the preview would go stale.
watch(
  () => props.result.data?.customRoles,
  (next) => {
    customRoles.value = next ?? [];
  },
  { deep: true },
);

watch(
  () => props.result.uuid,
  () => {
    void refresh();
  },
);
</script>
