@props([
    'name' => 'body_html',
    'value' => '',
    'label' => null,
    'height' => '280px',
])

<div class="form-group rich-editor" x-data="richEditor(@js($value))">
    @if ($label)
        <label class="form-label" for="{{ $name }}">{{ $label }}</label>
    @endif
    <div class="rich-editor-toolbar" style="display:flex; gap:6px; flex-wrap:wrap; margin-bottom:8px;">
        <button type="button" class="btn btn-ghost btn-sm" @click.prevent="cmd('bold')"><strong>B</strong></button>
        <button type="button" class="btn btn-ghost btn-sm" @click.prevent="cmd('italic')"><em>I</em></button>
        <button type="button" class="btn btn-ghost btn-sm" @click.prevent="cmd('underline')"><u>U</u></button>
        <button type="button" class="btn btn-ghost btn-sm" @click.prevent="cmd('insertUnorderedList')">• List</button>
        <button type="button" class="btn btn-ghost btn-sm" @click.prevent="cmd('insertOrderedList')">1. List</button>
        <button type="button" class="btn btn-ghost btn-sm" @click.prevent="cmd('formatBlock', 'h2')">H2</button>
        <button type="button" class="btn btn-ghost btn-sm" @click.prevent="link()">Link</button>
    </div>
    <div
        class="input rich-editor-body"
        contenteditable="true"
        x-ref="editor"
        @input="sync"
        style="min-height: {{ $height }}; height: auto; padding: 12px; overflow-y: auto;"
    ></div>
    <textarea name="{{ $name }}" x-ref="input" class="sr-only" required>{{ $value }}</textarea>
</div>

@once
    @push('scripts')
        <script>
            document.addEventListener('alpine:init', () => {
                Alpine.data('richEditor', (initial) => ({
                    init() {
                        this.$refs.editor.innerHTML = initial || '';
                        this.sync();
                    },
                    cmd(command, value = null) {
                        document.execCommand(command, false, value);
                        this.$refs.editor.focus();
                        this.sync();
                    },
                    link() {
                        const url = prompt('Enter URL');
                        if (url) document.execCommand('createLink', false, url);
                        this.sync();
                    },
                    sync() {
                        this.$refs.input.value = this.$refs.editor.innerHTML;
                    },
                }));
            });
        </script>
    @endpush
@endonce
