<template>
  <QuestionSummary :title="props.title" :text="props.text">
    <h5 class="mb-6 text-base">
      {{ props.items.length }} {{ $t("feedback.answers") }}
    </h5>
    <div
      v-for="{ label, percentage } in chartItems"
      :key="label"
      class="mb-6 flex flex-row flex-wrap items-center gap-3 gap-y-2"
    >
      <Popover class="relative w-full">
        <PopoverButton class="focus:outline-none">
          <div class="w-full text-base font-bold">{{ label }}</div>
        </PopoverButton>
        <PopoverPanel
          class="absolute top-[-200%] z-10 w-[120px] border border-gray-500 bg-white p-1 text-left text-sm font-normal"
        >
          <p>
            {{
              `"${label}" ${percentage * props.items.length} ${$t("feedback.answers")}`
            }}
          </p>
        </PopoverPanel>
      </Popover>
      <div
        class="h-8 bg-sky-500"
        :style="{ width: `${percentage * 100 * 0.8}%` }"
      ></div>
      <div class="text-sm">{{ (percentage * 100).toFixed(1) }}%</div>
    </div>
  </QuestionSummary>
</template>

<script setup lang="ts">
import QuestionSummary from "@/components/ui/QuestionSummary.vue";
import { Popover, PopoverButton, PopoverPanel } from "@headlessui/vue";
import { computed } from "vue";

interface ChartItem {
  percentage: number;
  label: string;
}

const props = defineProps<{
  title: string;
  text: string;
  items: string[];
}>();

const chartItems = computed<ChartItem[]>(() => {
  const chartItems = props.items.reduce((acc, item) => {
    const itemIndex = acc.findIndex((i) => i.label === item);
    if (itemIndex === -1) {
      acc.push({ label: item, percentage: 1 / props.items.length });
    } else {
      acc[itemIndex].percentage += 1 / props.items.length;
    }
    return acc;
  }, [] as ChartItem[]);
  return chartItems.sort(sort);
});

function sort(a: ChartItem, b: ChartItem) {
  if (a.label > b.label) {
    return -1;
  }
  if (a.label < b.label) {
    return 1;
  }
  return 0;
}
</script>
