<?php
declare(strict_types=1);

namespace Autogedal\Manufacturers\Block\Widget;

use Autogedal\Manufacturers\Model\Config\Source\Manufacturers;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Widget\Block\BlockInterface;

class Hero extends Template implements BlockInterface
{
    private const BREAKPOINT_DESKTOP = '(min-width: 768px)';
    private const DEFAULT_HEIGHT = 800;
    private const MIN_HEIGHT = 200;
    private const MAX_HEIGHT = 2000;

    protected $_template = 'Autogedal_Manufacturers::widget/hero.phtml';

    public function __construct(
        Context $context,
        private readonly Manufacturers $manufacturersSource,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }

    public function getBackgroundImage()
    {
        return $this->prepareImageUrl($this->getData('background_image'));
    }

    public function getBackgroundImageMobile()
    {
        return $this->prepareImageUrl($this->getData('background_image_mobile'))
            ?: $this->getBackgroundImage();
    }

    public function getBackgroundSources(): array
    {
        $desktopImage = $this->getBackgroundImage();
        if (!$desktopImage || $desktopImage === $this->getBackgroundImageMobile()) {
            return [];
        }

        return [self::BREAKPOINT_DESKTOP => $desktopImage];
    }

    public function getBrandTitle()
    {
        $optionId = $this->getData('attribute_value');
        foreach ($this->manufacturersSource->toOptionArray() as $option) {
            if ($option['value'] == $optionId) {
                return $option['label'];
            }
        }

        return '';
    }

    public function getMotto()
    {
        return $this->getData('motto');
    }

    public function getHeight(): int
    {
        $height = (int)$this->getData('height');

        return max(self::MIN_HEIGHT, min(self::MAX_HEIGHT, $height > 0 ? $height : self::DEFAULT_HEIGHT));
    }

    public function getLogo()
    {
        return $this->prepareImageUrl($this->getData('logo'));
    }

    private function prepareImageUrl($image)
    {
        if ($image && !str_starts_with($image, 'http')) {
            return $this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA) . $image;
        }

        return $image;
    }
}
