/**
 * Admin > System > Broadcast
 */
const { html } = window;
const { useState } = hooks;

export default function BroadcastSection() {
    const [title, setTitle] = useState('');
    const [message, setMessage] = useState('');
    const [level, setLevel] = useState('info');
    const [sending, setSending] = useState(false);

    async function send() {
        if (!title.trim() || !message.trim()) return sw.toast('Title and message are required', 'error');
        setSending(true);
        try {
            const result = await sw.api.admin.notifications.broadcast({ title: title.trim(), message: message.trim(), level });
            sw.toast(`Broadcast sent to ${result.count || '?'} users`, 'success');
            setTitle('');
            setMessage('');
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setSending(false); }
    }

    return html`
        <div>
            <p class="text-muted" style="font-size:12px;margin-bottom:12px;">Send a system announcement to all active users.</p>
            <div class="form-group"><label>Title</label>
                <input value=${title} onInput=${e => setTitle(e.target.value)} placeholder="Scheduled Maintenance" />
            </div>
            <div class="form-group"><label>Message</label>
                <textarea rows="4" value=${message} onInput=${e => setMessage(e.target.value)} placeholder="Servers will be down from 2-4 AM EST."></textarea>
            </div>
            <div class="form-group"><label>Level</label>
                <select value=${level} onChange=${e => setLevel(e.target.value)}>
                    <option value="info">Info</option>
                    <option value="warning">Warning</option>
                    <option value="critical">Critical</option>
                </select>
            </div>
            <button class="btn-md btn-primary" onClick=${send} disabled=${sending}>${sending ? 'Sending\u2026' : 'Send Broadcast'}</button>
        </div>
    `;
}
