<?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
    {
        // DEBUG: Log that filter is being called
        error_log('YoutubeFacade: filter() called, content length: ' . strlen($content));

        // Check if content has YouTube embeds at all (quick check)
        if (strpos($content, 'youtube.com/embed/') === false && strpos($content, 'youtube-nocookie.com/embed/') === false) {
            error_log('YoutubeFacade: No YouTube embeds found in quick check');
            return $content;
        }

        error_log('YoutubeFacade: YouTube embed detected, applying regex');

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

        $matchCount = 0;
        $result = preg_replace_callback($pattern, function ($matches) use (&$matchCount) {
            $matchCount++;
            $videoId = $matches[1];
            error_log('YoutubeFacade: Matched video ID: ' . $videoId);
            return $this->renderer->render($videoId);
        }, $content);

        error_log('YoutubeFacade: Regex replaced ' . $matchCount . ' iframes');

        // Return original content if regex failed
        if ($result === null) {
            error_log('YoutubeFacade: preg_replace_callback returned null (regex error)');
            return $content;
        }

        return $result;
    }
}
