@csrf

<div class="form-grid two-columns">
    <label>
        <span>Name</span>
        <input name="name" value="{{ old('name', $template->name) }}" required>
    </label>

    <label>
        <span>Slug</span>
        <input name="slug" value="{{ old('slug', $template->slug) }}" placeholder="auto-generated">
    </label>
</div>

<label>
    <span>Subject</span>
    <input name="subject" value="{{ old('subject', $template->subject) }}" required>
</label>

<label>
    <span>Preheader</span>
    <input name="preheader" value="{{ old('preheader', $template->preheader) }}" placeholder="Short preview text shown in inbox">
</label>

<label>
    <span>Email Body HTML</span>
    <div class="editor-toolbar" data-editor-toolbar="email-body-html">
        <button type="button" data-insert="<h2>Heading</h2>">Heading</button>
        <button type="button" data-insert="<p>Paragraph text.</p>">Paragraph</button>
        <button type="button" data-insert="<a href='https://example.com' class='email-button'>Shop now</a>">Button</button>
    </div>
    <textarea id="email-body-html" name="body_html" rows="12" required>{{ old('body_html', $template->body_html) }}</textarea>
</label>

<label class="checkbox-label">
    <input name="is_active" type="checkbox" value="1" @checked(old('is_active', $template->is_active ?? true))>
    <span>Active</span>
</label>

@if ($errors->any())
    <p class="form-error">{{ $errors->first() }}</p>
@endif

@push('scripts')
    <script>
        document.querySelectorAll('[data-editor-toolbar]').forEach((toolbar) => {
            const textarea = document.getElementById(toolbar.dataset.editorToolbar);

            toolbar.addEventListener('click', (event) => {
                const button = event.target.closest('button');

                if (!button || !textarea) {
                    return;
                }

                textarea.setRangeText(button.dataset.insert, textarea.selectionStart, textarea.selectionEnd, 'end');
                textarea.focus();
            });
        });
    </script>
@endpush
