<?php

declare(strict_types=1);

namespace ROITheme\Public\YoutubeFacade\Infrastructure\Services;

use ROITheme\Public\YoutubeFacade\Infrastructure\Ui\YoutubeFacadeRenderer;

/**
 * Filters post content to replace YouTube iframes with facades
 *
 * Detects YouTube iframes (including those wrapped in .video-wrapper)
 * and replaces them with lightweight facade HTML.
 *
 * @package ROITheme\Public\YoutubeFacade
 * @since 1.0.6
 */
final class YoutubeFacadeContentFilter
{
    private YoutubeFacadeRenderer $renderer;

    public function __construct(YoutubeFacadeRenderer $renderer)
    {
        $this->renderer = $renderer;
    }

    /**
     * Filter content to replace YouTube iframes with facades
     *
     * @param string $content Post content
     * @return string Filtered content
     */
    public function filter(string $content): string
    {
        // Quick check: skip if no YouTube embeds
        if (strpos($content, 'youtube.com/embed/') === false && strpos($content, 'youtube-nocookie.com/embed/') === false) {
            return $content;
        }

        // Pattern to match YouTube iframes
        // Handles: youtube.com/embed/ and youtube-nocookie.com/embed/
        $pattern = '/<iframe\s+[^>]*src=["\']https?:\/\/(?:www\.)?(?:youtube\.com|youtube-nocookie\.com)\/embed\/([a-zA-Z0-9_-]+)[^"\']*["\'][^>]*>\s*<\/iframe>/is';

        $result = preg_replace_callback($pattern, function ($matches) {
            return $this->renderer->render($matches[1]);
        }, $content);

        return $result ?? $content;
    }
}
