<?php
declare(strict_types=1);

namespace WP_AUX\Entities\AuxFramework\Partials;

use WHOOP\Entities\Elements\Comment;
use WHOOP\Entities\Elements\Div;
use WHOOP\Entities\Elements\Ul;

class LinkListEntity
{
  protected Div $container;
  protected Ul $ul;
  /**
   * @var LinkListItemEntity[]
   */
  protected $linkListItems = [];
  protected int $columns = 1;
  protected bool $isNested = false;
  protected ?string $heading = null;
  protected int $headingLevel = 2;

  public function __construct() {
    $this->container = Div::create();
    $this->container->addClass('link-list link-list--leading');

    $this->ul = Ul::create();

    $this->container->appendElement($this->ul);
  }

  public function setHeading(?string $heading): self
  {
    $this->heading = $heading;
    return $this;
  }

  public function setHeadingLevel(int $headingLevel): self
  {
    $this->headingLevel = $headingLevel;
    return $this;
  }

  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 setIsNested(bool $isNested): static
  {
    $this->isNested = $isNested;
    return $this;
  }

  public function setColumns(int|string $columns): static
  {
    if (is_string($columns)) {
      $columns = intval($columns);
    }

    if (empty($columns)) {
      $columns = 1;
    }

    if ($this->columns) {
      $this->container->removeClass('link-list--' . self::getColumnsString($this->columns) . '-col');
    }

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

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

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

    return $this;
  }

  public function addLink(string|array|null $link): ?LinkListItemEntity
  {
    // Catch invalid/incomplete link and add an HTML comment in its place
    if (!is_array($link)) {
      $node = Comment::create('Invalid/incomplete link');
      $this->ul->appendElement($node);

      return null;
    }

    $link = LinkListItemEntity::create($link);

    return $this->ul->appendElement($link);
  }

  public function __toString(): string
  {
    if ($this->isNested) {
      return (string) $this->ul;
    } else {
      $render = clone $this->container;

      if ($this->heading) {
        $heading = sprintf('<h%s>%s</h%s>', $this->headingLevel, $this->heading, $this->headingLevel);
        $render->prepend($heading);
      }

      return (string) $render;
    }
  }

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