/**
 * Interactive chart base class with tooltip + legend + mouse event plumbing
 * @countermeasure/web-components/charts/interactive
 */

import { BaseChart } from './base'
import type { InteractiveChartConfig } from './types'
import { ChartLegend } from './legend'
import { ChartTooltip } from './tooltip'

export abstract class InteractiveChart extends BaseChart {
  protected tooltip: ChartTooltip | null
  protected legend: ChartLegend | null
  private readonly boundMouseMove: (e: MouseEvent) => void
  private readonly boundMouseLeave: () => void

  constructor(config: InteractiveChartConfig) {
    super(config)

    // Initialize tooltip
    if (config.tooltip?.enabled !== false) {
      this.tooltip = new ChartTooltip(this.container)
    } else {
      this.tooltip = null
    }

    // Initialize legend
    if (config.legend !== undefined) {
      this.legend = new ChartLegend(this.container, config.legend)
    } else {
      this.legend = null
    }

    // Bind mouse handlers
    this.boundMouseMove = (e: MouseEvent) => {
      this.handleMouseMove(e)
    }
    this.boundMouseLeave = () => {
      this.handleMouseLeave()
    }
    this.canvas.addEventListener('mousemove', this.boundMouseMove)
    this.canvas.addEventListener('mouseleave', this.boundMouseLeave)
  }

  protected abstract handleMouseMove(e: MouseEvent): void
  protected abstract handleMouseLeave(): void

  public override destroy(): void {
    this.canvas.removeEventListener('mousemove', this.boundMouseMove)
    this.canvas.removeEventListener('mouseleave', this.boundMouseLeave)
    if (this.legend !== null) {
      this.legend.destroy()
    }
    if (this.tooltip !== null) {
      this.tooltip.destroy()
    }
    super.destroy()
  }
}
