@php
    $cancellationReason = '';
    if ($reasonDropdown) {
        $cancellationReason = $reasonLabels[$reasonDropdown] ?? $reasonDropdown;
    }
    if ($additionalComments) {
        $cancellationReason .= ($cancellationReason ? "\n\n" : '').$additionalComments;
    }

    $emailHtml = '';
    if ($cancellationReason) {
        $mailable = new \App\Mail\CancellationEmail($application, $cancellationReason);
        $fullHtml = $mailable->render();

        // Extract just the content-cell body from the rendered email
        if (preg_match('/<td class="content-cell"[^>]*>(.*?)<\/td>\s*<\/tr>\s*<\/table>\s*<\/td>\s*<\/tr>\s*<tr>\s*<td[^>]*>\s*<table class="footer"/s', $fullHtml, $matches)) {
            $emailHtml = trim($matches[1]);
            // Remove Livewire conditional comments
            $emailHtml = preg_replace('/<!--\[if BLOCK\]><!\[endif\]-->/', '', $emailHtml);
            $emailHtml = preg_replace('/<!--\[if ENDBLOCK\]><!\[endif\]-->/', '', $emailHtml);
        }
    }
@endphp

<div class="rounded-lg border border-gray-300 bg-gray-50 p-4 dark:border-gray-600 dark:bg-gray-800">
    <div class="mb-2 text-sm font-semibold text-gray-700 dark:text-gray-300">Email Preview</div>

    @if ($cancellationReason && $emailHtml)
        <div class="overflow-x-auto rounded border border-gray-200 bg-white p-4 text-sm break-words text-gray-700 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300">
            <div class="[&_pre]:whitespace-pre-wrap [&_pre]:wrap-break-word [&_code]:whitespace-pre-wrap [&_code]:wrap-break-word [&_blockquote]:p-3 [&_blockquote]:bg-gray-100 [&_blockquote]:dark:bg-gray-700 [&_blockquote]:border-l-4 [&_blockquote]:border-gray-400 [&_blockquote]:my-3 [&_blockquote]:mx-0 [&_ul]:list-disc [&_ul]:pl-5 [&_ul]:my-3 [&_li]:font-inherit [&_li]:text-inherit [&_h1]:mb-4 [&_h2]:mt-4 [&_h2]:mb-2 [&_h3]:mt-3 [&_h3]:mb-2 [&_p]:mb-3 [&_strong]:font-semibold max-w-full **:max-w-full">
                {!! $emailHtml !!}
            </div>
        </div>
    @elseif ($cancellationReason)
        <div class="overflow-hidden rounded bg-white">
            <iframe
                srcdoc="{!! htmlspecialchars($fullHtml ?? '', ENT_QUOTES, 'UTF-8') !!}"
                class="w-full border-0"
                style="min-height: 500px"
                sandbox="allow-same-origin"
            ></iframe>
        </div>
    @else
        <div class="rounded border border-gray-200 bg-white p-4 text-sm dark:border-gray-700 dark:bg-gray-900">
            <div class="border-l-4 border-gray-400 bg-gray-100 p-3 text-gray-500 italic dark:bg-gray-700 dark:text-gray-400">
                No cancellation reason provided yet. Select a reason or add comments above to see the email preview.
            </div>
        </div>
    @endif
</div>
