<script lang="ts">
  import * as Plot from '@observablehq/plot';
  import { onMount } from 'svelte';
  import type { MmpCurve } from '../lib/types';

  export let mmp: MmpCurve;
  export let ftp_w: number | null = null;

  let chartEl: HTMLElement;

  function formatDuration(s: number): string {
    if (s < 60)   return `${s}s`;
    if (s < 3600) return `${Math.round(s / 60)}min`;
    return `${s / 3600}h`;
  }

  function render() {
    if (!chartEl || !mmp.length) return;
    chartEl.innerHTML = '';

    const axisColor = document.documentElement.getAttribute('data-theme') === 'light'
      ? '#52525b' : '#a1a1aa';

    const data = mmp.map(([d, w]) => ({ d, w }));

    const chart = Plot.plot({
      width: chartEl.clientWidth || 600,
      height: 220,
      marginLeft: 52,
      marginBottom: 36,
      style: { background: 'transparent', color: axisColor },
      x: {
        type: 'log',
        label: 'Duration',
        tickFormat: (d: number) => formatDuration(d),
        grid: true,
        domain: [data[0].d, Math.max(7200, data[data.length - 1].d)],
      },
      y: { label: 'Avg power (W)', grid: true, zero: true },
      marks: [
        Plot.line(data, {
          x: 'd', y: 'w',
          stroke: '#f97316',
          strokeWidth: 2,
          curve: 'monotone-x',
        }),
        Plot.dot(data, {
          x: 'd', y: 'w',
          fill: '#f97316',
          r: 3,
          tip: true,
          title: (d: any) => `${formatDuration(d.d)}: ${d.w} W`,
        }),
        ...(ftp_w ? [
          Plot.ruleY([ftp_w], { stroke: '#71717a', strokeDasharray: '4 3' }),
          Plot.text([{ x: data[data.length - 1].d, y: ftp_w }], {
            x: 'x', y: 'y',
            text: () => `FTP ${ftp_w} W`,
            fill: '#71717a',
            fontSize: 11,
            dy: -6,
            textAnchor: 'end',
          }),
        ] : []),
      ],
    });

    chartEl.appendChild(chart);
  }

  onMount(() => {
    render();
    const ro = new ResizeObserver(render);
    ro.observe(chartEl);
    const mo = new MutationObserver(render);
    mo.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
    return () => { ro.disconnect(); mo.disconnect(); };
  });
</script>

<style>
  :global(.plot-tip text) { fill: #18181b !important; }
</style>

<div bind:this={chartEl} class="w-full min-h-[220px]"></div>
