{{-- resources/views/components/tiptap-editor.blade.php --}}
<div class="mb-6">
    <div class="flex flex-wrap gap-2 mb-2 p-2 bg-gray-100 rounded-lg">
        <button type="button" class="toolbar-btn" data-command="bold">B</button>
        <button type="button" class="toolbar-btn" data-command="italic">I</button>
        <button type="button" class="toolbar-btn" data-command="heading" data-level="1">H1</button>
        <button type="button" class="toolbar-btn" data-command="image">Image</button>
    </div>

    <div class="tiptap-editor min-h-[300px] border p-4 rounded-lg bg-white"
         data-content="{{ $content ?? '' }}"></div>

    <textarea name="content" class="hidden">{{ $content ?? '' }}</textarea>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('.toolbar-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const command = this.dataset.command;
                const level = this.dataset.level;
                const editorEl = this.closest('.mb-6').querySelector('.tiptap-editor');

                if (!editorEl || !editorEl._tiptapEditor) return;

                const editor = editorEl._tiptapEditor;

                if (command === 'bold') {
                    editor.chain().focus().toggleBold().run();
                } else if (command === 'italic') {
                    editor.chain().focus().toggleItalic().run();
                } else if (command === 'heading') {
                    editor.chain().focus().toggleHeading({ level: parseInt(level) }).run();
                } else if (command === 'image') {
                    const input = document.createElement('input');
                    input.type = 'file';
                    input.accept = 'image/*';

                    input.onchange = async (e) => {
                        const file = e.target.files[0];
                        if (!file) return;

                        const reader = new FileReader();
                        reader.onload = (event) => {
                            editor.chain().focus().setImage({ src: event.target.result }).run();
                        };
                        reader.readAsDataURL(file);
                    };

                    input.click();
                }
            });
        });
    });
</script>
