<?php
declare(strict_types=1);

namespace WP_AUX\Entities\AuxFramework\Partials;

use WHOOP\Entities\Elements\Ul;
use WP_AUX\Services\HtmlService;

class IconListEntity
{
  protected Ul $ul;
  protected int $columns = 1;

  public function __construct() {
    $this->ul = Ul::create();
    $this->ul->addClass('icon-list');
  }

  protected static function getColumnsString(string|int $columns): string
  {
    if (is_numeric($columns)) {
      try {
        $columns = match ((int) $columns) {
          1 => 'one',
          2 => 'two',
          3 => 'three',
        };
      } catch (\UnhandledMatchError) {
        $columns = '';
      }
    }

    return $columns;
  }

  public function setColumns(int $columns): static
  {
    if ($this->columns) {
      $this->ul->removeClass('icon-list--' . self::getColumnsString($this->columns) . '-col');
    }

    $columnsString = static::getColumnsString($columns);

    // Only set columns if valid
    if ($columnsString) {
      $this->columns = $columns;

      $this->ul->addClass('icon-list--' . self::getColumnsString($this->columns) . '-col');
    }

    return $this;
  }

  public function addItem(?string $icon, ?string $title, ?string $description = ''): static
  {
    $icon = IconEntity::create($icon, false);
    $description = HtmlService::formattedValue($description, '<span class="icon-list__description">%s</span>');
    $itemContent = HtmlService::formattedValue($icon . $title . $description, '<li>%s</li>');

    $this->ul->append($itemContent);

    return $this;
  }

  public function __toString(): string
  {
    return (string) $this->ul;
  }

  public static function create(): static
  {
    return new static();
  }
}
