@csrf

<label>
    <span>Title</span>
    <input name="title" value="{{ old('title', $announcement->title) }}" required>
</label>

<label>
    <span>Announcement Editor</span>
    <div class="editor-toolbar" data-editor-toolbar="announcement-body">
        <button type="button" data-prefix="- ">List</button>
        <button type="button" data-wrap="**">Bold</button>
        <button type="button" data-wrap="_">Italic</button>
    </div>
    <textarea id="announcement-body" name="body" rows="7" placeholder="Write announcement details, offer terms, or delivery updates.">{{ old('body', $announcement->body) }}</textarea>
</label>

<div class="form-grid two-columns">
    <label>
        <span>Button Text</span>
        <input name="button_text" value="{{ old('button_text', $announcement->button_text) }}" placeholder="Shop now">
    </label>

    <label>
        <span>Button URL</span>
        <input name="button_url" type="url" value="{{ old('button_url', $announcement->button_url) }}" placeholder="https://...">
    </label>
</div>

<div class="form-grid two-columns">
    <label>
        <span>Starts At</span>
        <input name="starts_at" type="datetime-local" value="{{ old('starts_at', $announcement->starts_at?->format('Y-m-d\TH:i')) }}">
    </label>

    <label>
        <span>Ends At</span>
        <input name="ends_at" type="datetime-local" value="{{ old('ends_at', $announcement->ends_at?->format('Y-m-d\TH:i')) }}">
    </label>
</div>

<label class="checkbox-label">
    <input name="is_active" type="checkbox" value="1" @checked(old('is_active', $announcement->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;
                }

                const start = textarea.selectionStart;
                const end = textarea.selectionEnd;
                const selected = textarea.value.slice(start, end) || 'text';
                const prefix = button.dataset.prefix || '';
                const wrap = button.dataset.wrap || '';
                const replacement = prefix ? `${prefix}${selected}` : `${wrap}${selected}${wrap}`;

                textarea.setRangeText(replacement, start, end, 'end');
                textarea.focus();
            });
        });
    </script>
@endpush
