<script lang="ts">
  import { onMount, onDestroy } from 'svelte'

  interface Props {
    history: number[]   // 체결강도 히스토리 (오래된→최신)
    height?: number
  }

  let { history, height = 48 }: Props = $props()
  let canvas: HTMLCanvasElement
  let ro: ResizeObserver

  function draw() {
    if (!canvas || history.length < 2) return
    const rect = canvas.getBoundingClientRect()
    const dpr = window.devicePixelRatio || 1
    const w = Math.floor(rect.width * dpr)
    const h = Math.floor(rect.height * dpr)
    if (w === 0 || h === 0) return
    if (canvas.width !== w || canvas.height !== h) {
      canvas.width = w
      canvas.height = h
    }

    const ctx = canvas.getContext('2d')!
    const pad = 3 * dpr
    const drawH = h - pad * 2
    ctx.clearRect(0, 0, w, h)

    const min = Math.min(...history)
    const max = Math.max(...history)
    const range = max - min || 1
    const step = w / (history.length - 1)
    const getY = (val: number) => h - pad - ((val - min) / range) * drawH

    // 그라디언트 채우기
    const lastX = (history.length - 1) * step
    const grad = ctx.createLinearGradient(0, pad, 0, h)
    grad.addColorStop(0, 'rgba(249,115,22,0.35)')
    grad.addColorStop(1, 'rgba(249,115,22,0)')
    ctx.beginPath()
    history.forEach((val, i) => {
      i === 0 ? ctx.moveTo(i * step, getY(val)) : ctx.lineTo(i * step, getY(val))
    })
    ctx.lineTo(lastX, h)
    ctx.lineTo(0, h)
    ctx.closePath()
    ctx.fillStyle = grad
    ctx.fill()

    // 라인
    ctx.beginPath()
    history.forEach((val, i) => {
      i === 0 ? ctx.moveTo(i * step, getY(val)) : ctx.lineTo(i * step, getY(val))
    })
    ctx.strokeStyle = '#f97316'
    ctx.lineWidth = 1.5 * dpr
    ctx.lineJoin = 'round'
    ctx.stroke()

    // 마지막 점 강조
    const lastVal = history[history.length - 1]
    ctx.beginPath()
    ctx.arc(lastX, getY(lastVal), 2.5 * dpr, 0, Math.PI * 2)
    ctx.fillStyle = '#f97316'
    ctx.fill()
  }

  onMount(() => {
    ro = new ResizeObserver(() => draw())
    ro.observe(canvas)
    draw()
    return () => ro.disconnect()
  })

  // history 변경 시 재그리기
  $effect(() => {
    history
    draw()
  })
</script>

<canvas bind:this={canvas} style="width:100%;height:{height}px;display:block;" class="rounded-sm"></canvas>
