// @ts-check
import Config from './settings/Config'
import Utils from '../utils/Utils'
import CoreUtils from './CoreUtils'
import { Environment } from '../utils/Environment.js'

/**
 * ApexCharts Responsive Class to override options for different screen sizes.
 *
 * @module Responsive
 **/

export default class Responsive {
  /**
   * @param {import('../types/internal').ChartStateW} w
   */
  constructor(w) {
    this.w = w
  }

  // the opts parameter if not null has to be set overriding everything
  // as the opts is set by user externally
  /**
   * @param {object} opts
   */
  checkResponsiveConfig(opts) {
    const w = this.w
    const cnf = w.config

    // check if responsive config exists
    if (cnf.responsive.length === 0) return

    const res = cnf.responsive.slice()
    res
      .sort(
        (
          /** @type {{ breakpoint: number }} */ a,
          /** @type {{ breakpoint: number }} */ b,
        ) =>
          a.breakpoint > b.breakpoint
            ? 1
            : b.breakpoint > a.breakpoint
              ? -1
              : 0,
      )
      .reverse()

    const config = new Config({})

    const iterateResponsiveOptions = (newOptions = {}) => {
      const largestBreakpoint = res[0].breakpoint
      const width = Environment.isBrowser()
        ? window.innerWidth > 0
          ? window.innerWidth
          : screen.width
        : 0

      if (width > largestBreakpoint) {
        const initialConfig = Utils.clone(w.globals.initialConfig)
        // Retain state of series in case any have been collapsed
        // (indicated by series.data === [], these series' will be zeroed later
        // enabling stacking to work correctly)
        initialConfig.series = Utils.clone(w.config.series)
        const options = CoreUtils.extendArrayProps(config, initialConfig, w)
        newOptions = Utils.extend(options, newOptions)
        newOptions = Utils.extend(w.config, newOptions)
        this.overrideResponsiveOptions(newOptions)
      } else {
        for (let i = 0; i < res.length; i++) {
          if (width < res[i].breakpoint) {
            newOptions = CoreUtils.extendArrayProps(config, res[i].options, w)
            newOptions = Utils.extend(w.config, newOptions)
            this.overrideResponsiveOptions(newOptions)
          }
        }
      }
    }

    if (opts) {
      let options = CoreUtils.extendArrayProps(config, opts, w)
      options = Utils.extend(w.config, options)
      options = Utils.extend(options, opts)
      iterateResponsiveOptions(options)
    } else {
      iterateResponsiveOptions({})
    }
  }

  /**
   * @param {Record<string, any>} newOptions
   */
  overrideResponsiveOptions(newOptions) {
    const newConfig = new Config(newOptions).init({ responsiveOverride: true })
    this.w.config = /** @type {any} */ (newConfig)
  }
}
