<script setup>
import BarChart from "@/components/chart/BarChart.vue";
import { ref, inject, watch } from "vue";
import { useI18n } from "vue-i18n";

const { t, locale } = useI18n();
const { taipower_data } = inject("energy_data");

const defaultChartOption = ref({
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow",
    },
  },
  legend: {
    data: [t("energy.carbon_equivalent")],
    textStyle: {
      color: "#ffffff",
      fontSize: 14,
    },
    orient: "horizontal",
    bottom: "0%",
  },
  grid: {
    top: "5%",
    left: "0%",
    right: "2%",
    bottom: "15%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    data: [], 
    axisLabel: {
      color: "#ffffff",
    },
  },
  yAxis: {
    type: "value",
    axisLabel: {
      color: "#ffffff",
    },
  },
  series: [
    {
      name: t("energy.carbon_equivalent"),
      type: "bar",
      data: [], 
      itemStyle: {
        color: "#45f4ef",
      },
    },
  ],
});

// 監聽 taipower_data 的變化
watch(
  taipower_data,
  () => {
    // 提取月份和碳排放數據
    const months = taipower_data.value.map(item => item.month);
    const carbonTotal = taipower_data.value.map(item => item.carbon);

    // 更新圖表的 xAxis 和 series
    defaultChartOption.value.xAxis.data = months;
    defaultChartOption.value.series[0].data = carbonTotal;
  },
  { deep: true }
);
</script>

<template>
  <div class="bg-slate-800 p-3">
    <div class="text-white mb-3 text-base">
      {{ $t("energy.monthly_carbon_emission_and_reduction") }}
    </div>
    <div class="bar-box">
      <BarChart
        id="electricity_bill_chart"
        class="min-h-[200px] w-full h-full"
        :option="defaultChartOption"
        ref="bill_chart"
      />
    </div>
  </div>
</template>
