<template>
  <div class="analysis-line-chart">
    <div class="y-axis">
      <span v-for="tick in ticks" :key="tick">{{ tick }}</span>
    </div>
    <div class="plot">
      <svg viewBox="0 0 760 320" preserveAspectRatio="none">
        <defs>
          <linearGradient id="lineFill" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stop-color="#ef6666" stop-opacity="0.26" />
            <stop offset="100%" stop-color="#ef6666" stop-opacity="0" />
          </linearGradient>
        </defs>
        <path :d="areaPath" fill="url(#lineFill)" />
        <path :d="linePath" fill="none" stroke="#df2828" stroke-width="4" stroke-linecap="round" />
      </svg>
    </div>
  </div>
</template>

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

const props = withDefaults(
  defineProps<{
    values: number[];
    max?: number;
  }>(),
  {
    max: 700,
  },
);

const width = 760;
const height = 320;

const points = computed(() => {
  const count = Math.max(props.values.length - 1, 1);
  return props.values.map((value, index) => {
    const x = (index / count) * width;
    const y = height - (value / props.max) * height;
    return { x, y };
  });
});

const linePath = computed(() =>
  points.value
    .map((point, index) => `${index === 0 ? "M" : "L"} ${point.x.toFixed(1)} ${point.y.toFixed(1)}`)
    .join(" "),
);

const areaPath = computed(() => {
  if (!points.value.length) return "";
  const end = points.value[points.value.length - 1];
  return `${linePath.value} L ${end.x.toFixed(1)} ${height} L 0 ${height} Z`;
});

const ticks = computed(() => {
  const step = props.max / 7;
  return Array.from({ length: 7 }, (_, index) => Math.round(props.max - step * (index + 1)));
});
</script>

<style scoped lang="scss">
.analysis-line-chart {
  width: 900px;
  height: 360px;
  margin: 10px auto 0;
  display: flex;
}

.y-axis {
  width: 55px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-end;
  padding: 4px 16px 34px 0;
  color: #a3a8b1;
  font-size: 18px;
}

.plot {
  flex: 1;
  height: 320px;
  background:
    repeating-linear-gradient(
      to bottom,
      rgba(214, 221, 232, 0.35) 0,
      rgba(214, 221, 232, 0.35) 1px,
      transparent 1px,
      transparent 53px
    );
}

svg {
  width: 100%;
  height: 100%;
  overflow: visible;
}
</style>
