import { BadgesMap } from '../../../page/body/badges-map.js';

class ResultCard {
  constructor (data) {
    this._title = data.title;
    this._url = data.url;
    this._desc = data.excerpt ?? data.summary;
    this._cover = data.cover || '/static/img/placeholder.16x9.png';
    this._section = data.section;
    this._badge = data.badge || [];
  }

  getTags () {
    if (!this._section) return '';
    return `<div class="fr-card__start">
      <ul class="fr-tags-group">
        <li>
          <p class="fr-tag">${this._section}</p>
        </li>
      </ul>
    </div>`;
  }

  getBadges () {
    if (!this._badge?.length) return '';

    const badges = Array.isArray(this._badge) ? this._badge : this._badge.split(',').map(b => b.trim());
    const badgeItems = badges
      .map(badge => {
        const badgeData = BadgesMap.get(badge);
        if (!badgeData) return null;

        const badgeLabel = window.resource?.badge?.[badge] || badge;
        let iconClass = '';
        if (badgeData.icon === false) {
          iconClass = ' fr-badge--no-icon';
        } else {
          iconClass = ` fr-badge--icon-${badgeData.icon}`;
        }
        return `<li><span class="fr-badge fr-badge--${badgeData.type} fr-badge--${badgeData.size}${iconClass}">${badgeLabel}</span></li>`;
      })
      .filter(Boolean)
      .join('');

    return `<ul class="fr-badges-group fr-mb-2v">${badgeItems}</ul>`;
  }

  getCover () {
    if (!this._cover) return '';
    return `<div class="fr-card__header">
      <div class="fr-card__img">
        <img src="${this._cover}" alt="" class="fr-responsive-img">
      </div>
      ${this.getBadges()}
    </div>`;
  }

  render () {
    return `<div class="fr-card fr-enlarge-link fr-card--horizontal fr-mb-8v">
      <div class="fr-card__body">
        <div class="fr-card__content">
          <h3 class="fr-card__title">
            <a href="${this._url}">${this._title}</a>
          </h3>
          ${this._desc ? `<p class="fr-card__desc">${this._desc}</p>` : ''}
          ${this.getTags()}
        </div>
      </div>
      ${this.getCover()}
    </div>`;
  }
}

export { ResultCard };
