import { Component } from '../component.js';
import { formatLink } from '../../core/format-link.js';
import { log } from '@gouvfr/dsfr-forge';
import { BadgesMap } from '../../page/body/badges-map.js';

class Sidemenu extends Component {
  constructor (data, badgeLabels) {
    super(data, 'sidemenu');
    this.badgeLabels = badgeLabels;
  }
  get ejsPath () {
    return 'src/dsfr/component/sidemenu/template/ejs/sidemenu.ejs';
  }

  async format () {
    return {
      id: 'sidemenu',
      collapseId: this.uniqueId(),
      buttonLabel: this.data.buttonLabel,
      titleId: this.uniqueId(),
      title: this.data.titleLabel,
      modifier: 'sticky-full-height',
      items: this.data?.items?.map(item => this._formatItem(item)).filter(item => item)
    };
  }

  _formatItem (item) {
    switch (item.type) {
      case 'menu':
        return this._formatMenu(item);

      default:
        return this._formatLink(item);
    }
  }

  _formatLink (link) {
    const text = link.titleId ? `${link.text} (<span lang="en">${link.titleId}</span>)` : link.text;
    const badge = link.badge ? this._formatBadge(link.badge) : '';
    const label = `<span>${link.badge ? text + badge : text}</span>`;
    return {
      ...formatLink(link),
      active: link.isCurrent,
      type: 'link',
      label: label,
    };
  }

  _formatBadge (ids) {
    if (typeof ids === 'string') ids = ids.split(',');
    if (!Array.isArray(ids)) {
      log.error(`Badge must be a string or an array of strings, received: ${typeof ids}`);
      return '';
    }
    return ids.map(id => {
      const badgeData = BadgesMap.get(id);
      if (!badgeData) {
        log.error(`Unknown badge type: ${id}`);
        return '';
      }
      const classes = ['fr-badge', 'fr-ml-1v'];
      if (badgeData.size) {
        classes.push(`fr-badge--${badgeData.size}`);
      }
      if (badgeData.type) {
        classes.push(`fr-badge--${badgeData.type}`);
      }
      switch (true) {
        case badgeData.icon === true:
          break;
        case badgeData.icon === false:
          classes.push(`fr-badge--no-icon`);
          break;
        case typeof badgeData.icon === 'string':
          classes.push(`fr-icon-${badgeData.icon}`);
          break;
      }
      const badgeLabel = this.badgeLabels[id];
      return `&nbsp;<span class="${classes.join(' ')}">${badgeLabel}</span>`;
    }).join('');
  }

  _formatMenu (menu) {
    return {
      id: menu.id,
      isCollapsible: menu.isCollapsible,
      collapseId: this.uniqueId(),
      type: 'menu',
      label: menu.label ?? menu.text,
      href: menu.url,
      active: menu.isCurrent,
      isExpanded: menu.isCurrent,
      items: menu.items.map(item => this._formatItem(item))
    }
  }

  async render () {
    return await super.render();
  }
}

export { Sidemenu };
