<?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\EventListener;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig\Components\Shop\Catalog;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig\Components\Shop\CatalogMobileBar;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\UX\TwigComponent\Event\PreRenderEvent;

#[AsEventListener(event: PreRenderEvent::class, priority: 100)]
final class ShopCountryComponentListener
{
    public function __invoke(PreRenderEvent $event): void
    {
        $component = $event->getComponent();

        $template = match (true) {
            $component instanceof Catalog && $component->isShopBlocked() => '@components/shop/CatalogBlocked.html.twig',
            $component instanceof CatalogMobileBar && $component->isShopBlocked() => '@components/shop/CatalogMobileBarBlocked.html.twig',
            default => null,
        };

        if (null === $template) {
            return;
        }

        $variables = $event->getVariables();
        unset($variables['template']);
        $variables[ComponentTemplateOverrideListener::OVERRIDE_APPLIED_VARIABLE] = true;

        $event->setTemplate($template, $event->getTemplateIndex());
        $event->setVariables($variables);
    }
}
