<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import type { QueryResult, ChartConfig } from '../../types'

const props = defineProps<{ results: QueryResult; config: ChartConfig }>()
const chartContainer = ref<HTMLElement | null>(null)

async function renderChart() {
  if (!chartContainer.value || !props.results.rows.length) return

  const Plotly = await import('plotly.js-dist-min')

  const x = props.results.rows.map(r => r[props.config.x_column])
  const y = props.results.rows.map(r => r[props.config.y_column])

  const traceMap: Record<string, any> = {
    bar: { x, y, type: 'bar' },
    line: { x, y, type: 'scatter', mode: 'lines+markers' },
    pie: { labels: x, values: y, type: 'pie' },
    scatter: { x, y, type: 'scatter', mode: 'markers' },
  }

  const trace = traceMap[props.config.chart_type] || traceMap.bar
  const layout = {
    title: { text: props.config.title, font: { color: '#e2e8f0', size: 14 } },
    paper_bgcolor: 'transparent',
    plot_bgcolor: 'transparent',
    font: { color: '#94a3b8' },
    xaxis: { gridcolor: '#334155' },
    yaxis: { gridcolor: '#334155' },
    margin: { t: 40, b: 40, l: 60, r: 20 },
  }

  Plotly.newPlot(chartContainer.value, [trace], layout, { responsive: true, displayModeBar: false })
}

onMounted(renderChart)
watch(() => props.config, renderChart)
</script>

<template>
  <div ref="chartContainer" class="w-full h-80" />
</template>
