<template>
  <div class="analysis-donut-chart">
    <div class="legend">
      <span v-for="item in items" :key="item.label">
        <i :style="{ backgroundColor: item.color }"></i>
        {{ item.label }}
      </span>
    </div>

    <div class="donut-wrap">
      <span
        v-for="(item, index) in labelItems"
        :key="item.label"
        class="donut-label"
        :class="`label-${index}`"
        :style="{ color: item.color }"
      >
        {{ item.label }} <strong>{{ item.percent }}%</strong>
      </span>
      <div class="donut" :style="{ background: donutGradient }"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";

export interface AnalysisDonutItem {
  label: string;
  value: number;
  color: string;
}

const props = defineProps<{
  items: AnalysisDonutItem[];
}>();

const total = computed(() => props.items.reduce((sum, item) => sum + item.value, 0) || 1);

const labelItems = computed(() =>
  props.items.map((item) => ({
    ...item,
    percent: ((item.value / total.value) * 100).toFixed(1),
  })),
);

const donutGradient = computed(() => {
  let start = 0;
  const segments = props.items.map((item) => {
    const end = start + (item.value / total.value) * 100;
    const segment = `${item.color} ${start}% ${end}%`;
    start = end;
    return segment;
  });
  return `conic-gradient(${segments.join(", ")})`;
});
</script>

<style scoped lang="scss">
.analysis-donut-chart {
  width: 620px;
  margin: 0 auto;
}

.legend {
  display: flex;
  justify-content: center;
  gap: 34px;
  color: #4f5967;
  font-size: 16px;

  span {
    display: inline-flex;
    align-items: center;
    gap: 8px;
  }

  i {
    width: 8px;
    height: 8px;
    border-radius: 2px;
  }
}

.donut-wrap {
  position: relative;
  height: 330px;
  margin-top: 14px;
}

.donut {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 250px;
  height: 250px;
  transform: translate(-50%, -50%);
  border-radius: 50%;

  &::after {
    content: "";
    position: absolute;
    inset: 74px;
    border-radius: 50%;
    background: #fff;
  }
}

.donut-label {
  position: absolute;
  color: #98a3ad;
  font-size: 20px;
  white-space: nowrap;

  strong {
    margin-left: 8px;
    font-weight: 700;
  }
}

.label-0 {
  left: 8px;
  top: 205px;
}

.label-1 {
  right: 0;
  top: 82px;
}

.label-2 {
  right: 4px;
  top: 245px;
}

.label-3 {
  left: 0;
  top: 66px;
  color: #9da7b2 !important;
}
</style>
