<?php

declare(strict_types=1);

namespace App\Filament\Support;

use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\HtmlString;

final class DberpFormSaveSubheading
{
    private const string SUBHEADING_BODY_CLASSES = 'text-sm text-gray-600 dark:text-gray-400';

    private const string BUSINESS_HINT_OPENING = '<p class="text-sm text-gray-600 dark:text-gray-400">';

    public static function append(string|Htmlable|null $existing): string|Htmlable|null
    {
        $hint = e((string) __('dberp.ui.save_keyboard_hint'));

        if ($existing === null || $existing === '') {
            return new HtmlString('<p class="'.self::SUBHEADING_BODY_CLASSES.'">'.$hint.'</p>');
        }

        if ($existing instanceof Htmlable) {
            $html = $existing->toHtml();
            $opening = self::BUSINESS_HINT_OPENING;
            $pos = strpos($html, $opening);
            if ($pos !== false) {
                $contentStart = $pos + strlen($opening);
                $closePos = strpos($html, '</p>', $contentStart);
                if ($closePos !== false) {
                    $merged = substr($html, 0, $closePos).' '.$hint.substr($html, $closePos);

                    return new HtmlString($merged);
                }
            }

            return new HtmlString($html.' <span class="'.self::SUBHEADING_BODY_CLASSES.'">'.$hint.'</span>');
        }

        return new HtmlString('<p class="'.self::SUBHEADING_BODY_CLASSES.'">'.e($existing).' '.$hint.'</p>');
    }
}
