<?php

declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Magento\Catalog\Block\Category\View;
use Magento\Catalog\ViewModel\Category\Output as CategoryOutput;
use Magento\Framework\Escaper;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Catalog\Model\CategoryFactory;

/** @var CategoryFactory $categoryFactory */
/** @var View $block */
/** @var Escaper $escaper */
/** @var ViewModelRegistry $viewModels */
/** @var StoreManagerInterface $storeManager */
/** @var CategoryOutput $categoryOutput */
$categoryOutput = $viewModels->require(CategoryOutput::class);
$categoryFactory = \Magento\Framework\App\ObjectManager::getInstance()->get(CategoryFactory::class);

$currentCategory = $block->getCurrentCategory();

// Initialize variables with default values
$subcategories = [];
$shopByCategoryTitle = '';

// Only proceed if we have a valid category
if ($currentCategory) {
    // Get children categories
    $subcategories = $currentCategory->getChildrenCategories();
    $shopByCategoryTitle = $currentCategory->getData('shop_by_category_section_title');
}

$visibleSubcategories = [];
foreach ($subcategories as $subcategory) {
    if ($subcategory->getIsActive()) {
        // Load full category data to get the image
        $fullCategory = $categoryFactory->create()->load($subcategory->getId());

        $imgUrl = $fullCategory->getImageUrl(); // This will now return the correct image
        $visibleSubcategories[] = [
            'name' => $subcategory->getName(),
            'url' => $subcategory->getUrl(),
            'image_url' => $imgUrl,
        ];
    }
}

// Show section only if there are visible subcategories
if (!empty($visibleSubcategories)):
    ?>
    <section class="shop_by bg-pagination">
        <div class="px-3 2xl:container 3xl:max-w-screen-2xl py-4 md:py-5">
            <h2 class="text-center text-xl lg:text-2xl font-bold font-sen mb-6"><?php echo $shopByCategoryTitle; ?></h2>
            <div>
                <ul class="list-none p-0 m-0 grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4 lg:gap-6">
                    <?php foreach ($visibleSubcategories as $subcategory): ?>
                        <?php
                        $name = trim(strtolower($subcategory['name']));
                        if ($name === 'best sellers' || $name === 'featured products') {
                            continue;
                        }
                        ?>
                        <li class="flex flex-col bg-white rounded-lg overflow-hidden shadow-md">
                            <a href="<?php echo $this->escapeUrl($subcategory['url']); ?>">
                                <?php if ($subcategory['image_url']): ?>
                                    <img src="<?php echo $this->escapeHtml($subcategory['image_url']); ?>"
                                         alt="<?php echo $this->escapeHtml($subcategory['name']); ?>">
                                <?php endif; ?>
                                <h2 class="flex-grow py-3 text-center">
                                    <span class="text-sm font-semibold font-sen"><?php echo $this->escapeHtml($subcategory['name']); ?></span>
                                </h2>
                            </a>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>

        </div>
    </section>
<?php endif; ?>
