<?php
declare(strict_types=1);

namespace Autogedal\BlackFriday\Block;

use Autogedal\BlackFriday\Model\Config;
use Autogedal\BlackFriday\Model\TeaserIdentity;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;

/**
 * Site-wide teasers towards /black-friday: the countdown capsule (bottom left) and the BF sticker by the logo.
 * Built in the browser (countdown / live from the dates), so the cached pages stay valid until the dates change.
 */
class Teaser extends Template implements IdentityInterface
{
    public function __construct(
        Context $context,
        private readonly Config $config,
        private readonly Json $json,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }

    public function isVisible(): bool
    {
        return $this->config->isEnabled() && !$this->config->isOver()
            && ($this->config->isCapsuleEnabled() || $this->config->isStickerEnabled());
    }

    public function getJsConfig(): string
    {
        return $this->json->serialize([
            'start' => $this->config->getStartIso(),
            'end' => $this->config->getEndIso(),
            'startDay' => $this->config->getStartDayLabel(),
            'capsule' => $this->config->isCapsuleEnabled(),
            'sticker' => $this->config->isStickerEnabled(),
            'test' => $this->config->isTestMode(),
            'url' => $this->getUrl('black-friday'),
        ]);
    }

    public function getIdentities(): array
    {
        return [TeaserIdentity::CACHE_TAG];
    }

    protected function _toHtml()
    {
        return $this->isVisible() ? parent::_toHtml() : '';
    }
}
