<?php

declare(strict_types=1);

namespace Autogedal\Reduceri\Plugin;

use Autogedal\Reduceri\Model\ReduceriState;
use Magento\Catalog\Helper\Data as CatalogHelper;

class CatalogBreadcrumbsPlugin
{
    public function __construct(
        private readonly ReduceriState $reduceriState
    ) {}

    /**
     * On reduceri pages: inject "Reduceri" between the parent categories and the current
     * category so the breadcrumb order is: Home > Accesorii auto > Reduceri > Covorase auto.
     *
     * getBreadcrumbPath() returns an ordered associative array; the native
     * Magento\Catalog\Block\Breadcrumbs iterates and adds each entry to the breadcrumbs
     * block in insertion order, so we return the full corrected path here.
     */
    public function afterGetBreadcrumbPath(CatalogHelper $subject, array $result): array
    {
        if (!$this->reduceriState->isCategoryView() || empty($result)) {
            return $result;
        }

        // Pull off the current category crumb (last item, no link)
        $currentCrumb = array_pop($result);

        // Add Reduceri after parent categories
        $result['reduceri'] = [
            'label' => __('Reduceri'),
            'title' => __('Reduceri'),
            'link'  => '/reduceri',
        ];

        // Re-add current category linking to base reduceri URL (no active filters),
        // so clicking it resets any applied filters.
        $category = $this->reduceriState->getCategory();
        $currentCrumb['link'] = $category ? '/reduceri/' . $category->getUrlKey() : null;
        $result['category'] = $currentCrumb;

        return $result;
    }
}
