<?php

namespace WPSN\Modules\Breadcrumbs;

use WPSN\Core\AbstractModule;
use WPSN\SEO\BreadcrumbsBuilder;
use WPSN\SEO\DocumentResolver;

defined('ABSPATH') || exit;

/**
 * Breadcrumbs (frontend UI).
 *
 * Provides:
 *  - Shortcode: [wpsn_breadcrumbs]
 *  - Optional auto-insert into the_content (disabled by default)
 */
final class BreadcrumbsModule extends AbstractModule
{
    public function id(): string
    {
        return 'breadcrumbs';
    }

    public function name(): string
    {
        return __('Breadcrumbs', 'wp-seo-next');
    }

    public function description(): string
    {
        return __('Shortcode + optional auto-insert breadcrumbs navigation.', 'wp-seo-next');
    }

    public function defaultEnabled(): bool
    {
        // Safe: it does not output anything unless shortcode/auto-insert is used.
        return true;
    }

    public function register(): void
    {
        add_shortcode('wpsn_breadcrumbs', [$this, 'shortcode']);

        // Optional auto-insert.
        add_filter('the_content', [$this, 'maybeAutoInsert'], 5);
    }

    /**
     * @param array<string, mixed> $atts
     */
    public function shortcode($atts = []): string
    {
        if (!(bool) $this->settings->get('breadcrumbs.ui_enabled', true)) {
            return '';
        }

        if (is_admin() && !wp_doing_ajax()) {
            return '';
        }

        $atts = shortcode_atts([
            'separator'    => '',
            'show_current' => '',
            'class'        => '',
        ], is_array($atts) ? $atts : [], 'wpsn_breadcrumbs');

        $sep = trim((string) ($atts['separator'] ?? ''));
        if ($sep === '') {
            $sep = (string) $this->settings->get('breadcrumbs.separator', '›');
        }

        $showCurrent = (string) ($atts['show_current'] ?? '');
        if ($showCurrent === '') {
            $showCurrentBool = (bool) $this->settings->get('breadcrumbs.show_current', true);
        } else {
            $showCurrentBool = in_array(strtolower($showCurrent), ['1', 'true', 'yes', 'on'], true);
        }

        $extraClass = trim((string) ($atts['class'] ?? ''));

        /** @var DocumentResolver $resolver */
        $resolver = $this->container->get('document_resolver');

        /** @var BreadcrumbsBuilder $builder */
        $builder = $this->container->get('breadcrumbs_builder');

        $ctx = $resolver->resolve();
        $items = $builder->build($ctx);

        if (!$showCurrentBool && count($items) > 1) {
            array_pop($items);
        }

        if (count($items) < 2) {
            return '';
        }

        $class = 'wpsn-breadcrumbs';
        if ($extraClass !== '') {
            $class .= ' ' . sanitize_html_class($extraClass);
        }

        $trailPrefix = trim((string) $this->settings->get('breadcrumbs.trail_prefix', ''));

        $html = '<nav class="' . esc_attr($class) . '" aria-label="' . esc_attr__('Breadcrumbs', 'wp-seo-next') . '">';
        if ($trailPrefix !== '') {
            $html .= '<div class="wpsn-breadcrumbs__prefix">' . esc_html($trailPrefix) . '</div>';
        }
        $html .= '<ol class="wpsn-breadcrumbs__list">';

        $lastIndex = count($items) - 1;
        foreach ($items as $i => $it) {
            $name = isset($it['name']) ? (string) $it['name'] : '';
            $url  = isset($it['url']) ? (string) $it['url'] : '';

            if ($name === '') {
                continue;
            }

            $isLast = ($i === $lastIndex);

            $html .= '<li class="wpsn-breadcrumbs__item">';

            if ($isLast) {
                // Current: do not link.
                $html .= '<span class="wpsn-breadcrumbs__current">' . esc_html($name) . '</span>';
            } else {
                $html .= '<a class="wpsn-breadcrumbs__link" href="' . esc_url($url) . '">' . esc_html($name) . '</a>';
            }
            $html .= '</li>';

            if (!$isLast) {
                $html .= '<li class="wpsn-breadcrumbs__sep" aria-hidden="true">' . esc_html($sep) . '</li>';
            }
        }

        $html .= '</ol>';
        $html .= '</nav>';

        /**
         * Filter the final breadcrumbs HTML.
         */
        $html = apply_filters('wpsn/breadcrumbs/html', $html, $items, $ctx);

        return is_string($html) ? $html : '';
    }

    public function maybeAutoInsert(string $content): string
    {
        if (!(bool) $this->settings->get('breadcrumbs.ui_enabled', true)) {
            return $content;
        }

        if (is_admin() || wp_doing_ajax() || (defined('REST_REQUEST') && REST_REQUEST)) {
            return $content;
        }

        if (is_feed() || is_preview()) {
            return $content;
        }

        $enabled = (bool) $this->settings->get('breadcrumbs.auto_insert', false);
        if (!$enabled) {
            return $content;
        }

        $singularOnly = (bool) $this->settings->get('breadcrumbs.singular_only', true);
        if ($singularOnly && !is_singular()) {
            return $content;
        }

        $pos = (string) $this->settings->get('breadcrumbs.position', 'before');
        $pos = in_array($pos, ['before', 'after'], true) ? $pos : 'before';

        $crumbs = $this->shortcode();
        if ($crumbs === '') {
            return $content;
        }

        if ($pos === 'after') {
            return $content . $crumbs;
        }

        return $crumbs . $content;
    }
}
