<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import Plotly from 'plotly.js-dist-min'
import type { EquityPoint } from '@/api/types'

const props = defineProps<{
  data: EquityPoint[]
  title?: string
}>()

const chartRef = ref<HTMLDivElement | null>(null)

const CHART_COLORS = {
  equity: '#58a6ff',
  grid: '#30363d',
  text: '#8b949e',
}

function renderChart() {
  if (!chartRef.value || props.data.length === 0) return
  
  const timestamps = props.data.map(p => p.timestamp)
  const values = props.data.map(p => p.value)
  
  const traces: Plotly.Data[] = [
    {
      x: timestamps,
      y: values,
      type: 'scatter',
      mode: 'lines',
      name: 'Portfolio Value',
      line: { color: CHART_COLORS.equity, width: 2 },
      hovertemplate: '%{x}<br>Value: $%{y:,.2f}<extra></extra>',
    },
  ]
  
  const layout: Partial<Plotly.Layout> = {
    title: props.title ? {
      text: props.title,
      font: { color: CHART_COLORS.text, size: 14 },
    } : undefined,
    paper_bgcolor: 'transparent',
    plot_bgcolor: 'transparent',
    margin: { l: 60, r: 20, t: props.title ? 40 : 20, b: 40 },
    xaxis: {
      showgrid: true,
      gridcolor: CHART_COLORS.grid,
      tickfont: { color: CHART_COLORS.text, size: 10 },
      linecolor: CHART_COLORS.grid,
    },
    yaxis: {
      showgrid: true,
      gridcolor: CHART_COLORS.grid,
      tickfont: { color: CHART_COLORS.text, size: 10 },
      linecolor: CHART_COLORS.grid,
      tickprefix: '$',
      hoverformat: ',.2f',
    },
    showlegend: false,
    hovermode: 'x unified',
  }
  
  const config: Partial<Plotly.Config> = {
    responsive: true,
    displayModeBar: false,
  }
  
  Plotly.react(chartRef.value, traces, layout, config)
}

watch(() => props.data, renderChart, { deep: true })

onMounted(() => {
  renderChart()
  window.addEventListener('resize', renderChart)
})

onUnmounted(() => {
  window.removeEventListener('resize', renderChart)
  if (chartRef.value) {
    Plotly.purge(chartRef.value)
  }
})
</script>

<template>
  <div ref="chartRef" class="w-full h-full min-h-[300px]"></div>
</template>
