<div class="container-fluid py-4" x-data="{ previewContent: @entangle('content') }">
    <x-title :breadcrumbs="[
        ['link' => route('templates.index'), 'title' => 'Templates'],
        ['link' => '', 'title' => $template ? 'Edit' : 'Create'],
    ]">
        {{ $template ? 'Edit' : 'Create' }} Template
        <x-slot:buttons>
            <button wire:click="save" class="btn btn-success px-4">Save Template</button>
        </x-slot:buttons>
    </x-title>

    <div class="row">
        <div class="col-md-6">
            <div class="card shadow-sm">
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Title</label>
                        <input type="text" wire:model="title" class="form-control">
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Category</label>
                            <select wire:model="category_id" class="form-select">
                                <option value="">Select...</option>
                                @foreach($categories as $cat)
                                    <option value="{{ $cat->id }}">{{ $cat->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Type</label>
                            <select wire:model.live="type" class="form-select">
                                <option value="email">Email</option>
                                <option value="sms">SMS</option>
                            </select>
                        </div>
                    </div>

                    @if($type === 'email')
                        <div class="mb-3">
                            <label class="form-label fw-bold">Subject Line</label>
                            <input type="text" wire:model="subject" class="form-control">
                        </div>
                    @endif

                    <div class="mb-3">
                        <label class="form-label fw-bold">Content</label>
                        <div
                                x-data="wysiwygEditor"
                                x-init="initEditor()"
                                wire:ignore
                                class="bg-white"
                        >
                            <div x-ref="editor" style="min-height: 300px;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card shadow-sm h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span class="fw-bold">Live Preview</span>
                    <span class="badge bg-secondary">Visual</span>
                </div>
                <div class="card-body p-0 bg-light" style="min-height: 500px;">
                    <iframe
                            class="w-100 h-100 border-0"
                            x-effect="
                            const doc = $el.contentDocument || $el.contentWindow.document;
                            doc.open();
                            doc.write('<html><head><link href=\'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css\' rel=\'stylesheet\'><link href=\'https://cdn.quilljs.com/1.3.6/quill.snow.css\' rel=\'stylesheet\'></head><body class=\'p-4 ql-editor\'>' + previewContent + '</body></html>');
                            doc.close();
                        "
                    ></iframe>
                </div>
            </div>
        </div>
    </div>

    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>

    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('wysiwygEditor', () => ({
                editor: null,
                initEditor() {
                    this.editor = new Quill(this.$refs.editor, {
                        theme: 'snow',
                        modules: {
                            toolbar: [
                                ['bold', 'italic', 'underline'],
                                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                                [{ 'header': [1, 2, 3, false] }],
                                ['link', 'clean']
                            ]
                        }
                    });

                    // Set initial content from Livewire/Alpine
                    this.editor.root.innerHTML = this.previewContent;

                    // Update Alpine/Livewire on change
                    this.editor.on('text-change', () => {
                        this.previewContent = this.editor.root.innerHTML;
                    });

                    // Sync if Livewire updates content from the outside (e.g. reset or template load)
                    this.$watch('previewContent', (newValue) => {
                        if (newValue !== this.editor.root.innerHTML) {
                            this.editor.root.innerHTML = newValue;
                        }
                    });
                }
            }))
        })
    </script>
</div>