<template>
  <div v-if="store.isDetailsModalVisible" class="modal-overlay" @click="store.closeDetailsModal">
    <div class="modal-content" @click.stop>
      <button class="close-btn" @click="store.closeDetailsModal">×</button>
      <div ref="detailsChartRef" class="details-chart-container"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onUnmounted, nextTick } from 'vue';
import { useKeyNodeStore } from '@/store/keyNodeStore';
import * as echarts from 'echarts/core';
import { SVGRenderer } from 'echarts/renderers';
import { LineChart } from 'echarts/charts';
import { GridComponent, TooltipComponent } from 'echarts/components';

echarts.use([SVGRenderer, LineChart, GridComponent, TooltipComponent]);

const store = useKeyNodeStore();
const detailsChartRef = ref(null);
let myChart = null;

watch(() => store.isDetailsModalVisible, async (isVisible) => {
  if (isVisible && store.detailsModalChartConfig) {
    await nextTick();
    if (detailsChartRef.value) {
        myChart = echarts.init(detailsChartRef.value);
        myChart.setOption(store.detailsModalChartConfig.option);
    }
  } else if (!isVisible && myChart) {
    myChart.dispose();
    myChart = null;
  }
});

onUnmounted(() => {
  if (myChart) {
    myChart.dispose();
  }
});
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.modal-content {
  position: relative;
  background-color: #0d1b38;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #3a95ff;
  box-shadow: 0 0 25px rgba(58, 149, 255, 0.5);
  width: 50vw;
  height: 45vh;
  display: flex;
  flex-direction: column;
}
.close-btn {
  position: absolute;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  top: 10px;
  right: 15px;
  border: none;
  color: #a7c5d4;
  background: none;
  font-size: 24px;
  cursor: pointer;
}
.details-chart-container {
  width: 100%;
  flex-grow: 1;
}
</style>