<?php

namespace WHOOP\Entities;

class Classlist
{
  protected array $classes = [];

  public function __construct(array|string $classes = []) {
    if (is_string($classes)) {
      $classes = explode(" ", $classes);
    }

    if (!empty($classes)) {
      $this->classes = $classes;
    }
  }

  public function addClass(string $class): self
  {
    $classes = explode(" ", $class);

    $this->classes = array_unique(array_merge($this->classes, $classes));

    return $this;
  }

  public function removeClass(string $class): self
  {
    $index = array_search($class, $this->classes);

    if (false !== $index) {
      unset($this->classes[$index]);
    }

    return $this;
  }

  public function getClassesString(): string
  {
    return join(" ", $this->classes);
  }

  public function __toString(): string
  {
    $classesString = $this->getClassesString();

    return $classesString ? 'class="' . esc_attr($classesString) . '"' : '';
  }
}
