<?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\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\ComponentToolsTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent('announcement:Modal', template: '@components/announcement/Modal.html.twig')]
final class Modal
{
    use ComponentToolsTrait;
    use DefaultActionTrait;

    public ?string $id = 'announcement-modal';
    public bool $open = false;
    public string $announcementIds = '';

    /**
     * @var list<array{key: string, title: string, subtitle: string, urlTitle: string, text: string, url: string, imagePath: ?string, videoPath: ?string}>
     */
    public array $announcements = [];

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

    public function mount(): void
    {
        $this->announcements = $this->loadAnnouncements();
        $this->announcementIds = implode(',', array_column($this->announcements, 'key'));
        $this->open = [] !== $this->announcements;
    }

    #[LiveAction]
    public function close(): void
    {
        $this->open = false;
    }

    /**
     * @return list<array{key: string, title: string, subtitle: string, urlTitle: string, text: string, url: string, imagePath: ?string, videoPath: ?string}>
     */
    private function loadAnnouncements(): array
    {
        $items = array_filter(
            $this->popupRepository->findAllActiveByMode(true),
            fn (Popup $announcement): bool => $this->hasDisplayableContent($announcement),
        );

        return array_values(array_map(
            fn (Popup $announcement): array => [
                'key' => $announcement->getId()->toString(),
                'title' => trim((string) $announcement->getTitle()),
                'subtitle' => trim((string) $announcement->getSubtitle()),
                'urlTitle' => trim((string) $announcement->getUrlTitle()),
                'text' => trim((string) $announcement->getText()),
                'url' => trim((string) $announcement->getUrl()),
                'imagePath' => $announcement->getImage()?->getPath(),
                'videoPath' => $announcement->getVideo()?->getPath(),
            ],
            $items,
        ));
    }

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