<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig\Components\Behavior\HasTemplateOverride;
use CpCreation\VitiCore\Shop\Model\InformationBlock;
use CpCreation\VitiCore\Shop\Repository\InformationBlockRepository;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveArg;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\ComponentToolsTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;

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

    #[LiveProp]
    public string $zone = InformationBlock::ZONE_TOP;

    public function __construct(
        private readonly InformationBlockRepository $informationBlockRepository,
    ) {
    }

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

    /**
     * @return list<InformationBlock>
     */
    public function getBlocks(): array
    {
        return $this->informationBlockRepository->findActiveOrdered($this->zone);
    }

    #[LiveAction]
    public function showInformationModal(#[LiveArg('informationBlockId')] string $informationBlockId): void
    {
        $informationBlock = $this->findVisibleBlockById($informationBlockId);

        if (!$informationBlock instanceof InformationBlock || !$informationBlock->isModalAction() || !$informationBlock->hasModalContent()) {
            return;
        }

        $this->emit('shopInformationModal:open', [
            'informationBlockId' => $informationBlock->getId()->toString(),
        ], 'modal:ShopInformation');
    }

    private function findVisibleBlockById(string $informationBlockId): ?InformationBlock
    {
        foreach ($this->getBlocks() as $block) {
            if ($block->getId()->toString() === $informationBlockId) {
                return $block;
            }
        }

        return null;
    }
}
