<?php

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig\Components\Announcement;

use CpCreation\VitiCore\Popup\Model\Popup;
use CpCreation\VitiCore\Popup\Repository\PopupRepository;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent('announcement:Banner', template: '@components/announcement/Banner.html.twig')]
final class Banner
{
    /**
     * @var list<array{key: string, title: string, text: string, url: string, urlTitle: string}>
     */
    private ?array $announcements = null;

    public function __construct(
        private readonly PopupRepository $popupRepository,
    ) {
    }

    public function hasAnnouncements(): bool
    {
        return [] !== $this->getAnnouncements();
    }

    /**
     * @return list<array{key: string, title: string, text: string, url: string, urlTitle: string}>
     */
    public function getAnnouncements(): array
    {
        if (null !== $this->announcements) {
            return $this->announcements;
        }

        $items = array_filter(
            $this->popupRepository->findAllActiveByMode(false),
            fn (Popup $announcement): bool => $this->hasDisplayableContent($announcement),
        );

        return $this->announcements = array_values(array_map(
            fn (Popup $announcement): array => [
                'key' => $announcement->getId()->toString(),
                'title' => $announcement->isShowTitleInBanner()
                    ? trim((string) $announcement->getTitle())
                    : '',
                'text' => trim((string) $announcement->getText()),
                'url' => trim((string) $announcement->getUrl()),
                'urlTitle' => trim((string) $announcement->getUrlTitle()),
            ],
            $items,
        ));
    }

    private function hasDisplayableContent(Popup $announcement): bool
    {
        return ($announcement->isShowTitleInBanner() && '' !== trim((string) $announcement->getTitle()))
            || '' !== trim((string) $announcement->getText());
    }
}
