<?php

declare(strict_types=1);

namespace App\Support;

use Illuminate\Support\Js;

/**
 * 生成在浏览器端复制文本的 Livewire $this->js() 脚本（execCommand，HTTP/HTTPS 均可用）。
 */
final class CopyTextToClipboardScript
{
    public static function forLivewire(string $text): string
    {
        return '(function () {
            const text = '.Js::from($text).';
            const textarea = document.createElement("textarea");
            textarea.value = text;
            textarea.setAttribute("readonly", "");
            textarea.style.position = "fixed";
            textarea.style.top = "0";
            textarea.style.left = "0";
            textarea.style.opacity = "0";
            document.body.appendChild(textarea);
            textarea.focus();
            textarea.select();
            textarea.setSelectionRange(0, textarea.value.length);

            try {
                return document.execCommand("copy");
            } catch (error) {
                return false;
            } finally {
                document.body.removeChild(textarea);
            }
        })()';
    }
}
