/**
 * Series chart base class with series management, visibility toggling, and legend updates
 * @countermeasure/web-components/charts/series
 */

import { InteractiveChart } from './interactive'
import type { ChartSeries, LegendItem, ResolvedSeries, SeriesChartConfig } from './types'
import { defaultColors } from './utils'

export abstract class SeriesChart extends InteractiveChart {
  protected series: ResolvedSeries[]
  protected hiddenSeries: Set<string>

  constructor(config: SeriesChartConfig) {
    // Series charts show legend by default unless explicitly disabled
    if (config.legend?.visible === false) {
      const { legend: _omit, ...rest } = config
      super(rest)
    } else {
      super({ ...config, legend: config.legend ?? { visible: true } })
    }

    this.hiddenSeries = new Set()
    this.series = this.resolveSeries(config.series)

    // Wire legend toggle to hidden series management
    if (this.legend !== null) {
      this.legend.onToggle((index: number, _active: boolean) => {
        const s = this.series[index]
        if (s === undefined) return
        if (this.hiddenSeries.has(s.name)) {
          this.hiddenSeries.delete(s.name)
        } else {
          this.hiddenSeries.add(s.name)
        }
        this.render()
      })
    }
  }

  protected resolveSeries(rawSeries: ChartSeries[]): ResolvedSeries[] {
    const colors = defaultColors()
    return rawSeries.map((s, i) => ({
      name: s.name,
      data: s.data,
      color: s.color ?? colors[i % colors.length] ?? '#3b82f6',
    }))
  }

  protected getVisibleSeries(): ResolvedSeries[] {
    return this.series.filter(s => !this.hiddenSeries.has(s.name))
  }

  protected updateSeriesLegend(): void {
    if (this.legend === null) return
    const items: LegendItem[] = this.series.map(s => ({
      label: s.name,
      color: s.color,
      active: !this.hiddenSeries.has(s.name),
    }))
    this.legend.update(items)
  }
}
