<script lang="ts">
  import { onMount, onDestroy } from 'svelte'
  import { createChart, ColorType, CrosshairMode, CandlestickSeries } from 'lightweight-charts'
  import type { IChartApi, ISeriesApi, CandlestickSeriesOptions, Time } from 'lightweight-charts'
  import type { CandleData, StockPrice } from '$lib/api/types'

  interface Props {
    data: CandleData[]
    height?: number
    // 실시간 현재가 (WebSocket에서 수신) — 일봉 모드에서만 의미 있음
    livePrice?: StockPrice | null
    chartType?: 'D' | 'W' | 'M'
  }

  let { data, height = 320, livePrice = null, chartType = 'D' }: Props = $props()

  let container: HTMLElement
  let chart: IChartApi | null = null
  let series: ISeriesApi<'Candlestick'> | null = null

  // 다크 테마 색상
  const chartColors = {
    bg: '#111827',
    grid: '#1f2937',
    text: '#9ca3af',
    up: '#ef4444',
    down: '#3b82f6',
  }

  function toChartData(d: CandleData) {
    return {
      time: d.time as unknown as Time,
      open: d.open,
      high: d.high,
      low: d.low,
      close: d.close,
    }
  }

  // 오늘 날짜를 YYYY-MM-DD 형식의 Time으로 변환
  function todayTime(): Time {
    const now = new Date()
    const y = now.getFullYear()
    const m = String(now.getMonth() + 1).padStart(2, '0')
    const d = String(now.getDate()).padStart(2, '0')
    return `${y}-${m}-${d}` as unknown as Time
  }

  onMount(() => {
    chart = createChart(container, {
      width: container.clientWidth,
      height,
      layout: {
        background: { type: ColorType.Solid, color: chartColors.bg },
        textColor: chartColors.text,
      },
      grid: {
        vertLines: { color: chartColors.grid },
        horzLines: { color: chartColors.grid },
      },
      crosshair: {
        mode: CrosshairMode.Normal,
      },
      rightPriceScale: {
        borderColor: chartColors.grid,
        scaleMargins: { top: 0.1, bottom: 0.15 },
      },
      timeScale: {
        borderColor: chartColors.grid,
        timeVisible: true,
        secondsVisible: false,
      },
    })

    series = chart.addSeries(CandlestickSeries, {
      upColor: chartColors.up,
      downColor: chartColors.down,
      borderUpColor: chartColors.up,
      borderDownColor: chartColors.down,
      wickUpColor: chartColors.up,
      wickDownColor: chartColors.down,
    } as CandlestickSeriesOptions)

    if (data.length > 0) {
      series.setData(data.map(toChartData))
      chart.timeScale().fitContent()
    }

    // 리사이즈 대응
    const ro = new ResizeObserver(() => {
      chart?.applyOptions({ width: container.clientWidth })
    })
    ro.observe(container)

    return () => ro.disconnect()
  })

  // 과거 데이터 변경 시 전체 재설정
  $effect(() => {
    if (series && data.length > 0) {
      series.setData(data.map(toChartData))
      chart?.timeScale().fitContent()
    }
  })

  // 실시간 현재가로 현재 봉 업데이트 (일봉 모드에서만)
  $effect(() => {
    if (!series || !livePrice || chartType !== 'D') return

    const price = livePrice.currentPrice
    if (price <= 0) return

    // 마지막 봉 데이터 가져오기
    const lastBar = data.at(-1)
    if (!lastBar) return

    // 현재 봉의 고가/저가 반영
    series.update({
      time: todayTime(),
      open: lastBar.open,
      high: Math.max(lastBar.high, price),
      low: Math.min(lastBar.low, price),
      close: price,
    })
  })

  onDestroy(() => {
    chart?.remove()
    chart = null
    series = null
  })
</script>

<div bind:this={container} style="width:100%; height:{height}px;"></div>
