/**
 * Settings > Tasks — user's tasks with run/stop controls
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;

function fmtDate(d) {
    if (!d) return '\u2014';
    return new Date(d).toLocaleString(undefined, { dateStyle: 'short', timeStyle: 'short' });
}

export default function TasksSection() {
    const [tasks, setTasks] = useState([]);
    const [loading, setLoading] = useState(true);

    const load = useCallback(async () => {
        try {
            const data = await sw.api.tasks.list();
            setTasks(data || []);
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, []);

    useEffect(() => { load(); }, []);

    async function runTask(id) {
        try {
            await sw.api.tasks.start(id);
            sw.toast('Task started', 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function stopTask(id) {
        try {
            await sw.api.tasks.stop(id);
            sw.toast('Task stopped', 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    if (loading) return html`<div class="settings-placeholder">Loading\u2026</div>`;

    return html`
        <div>
            <div class="admin-list">
                ${tasks.length === 0 && html`<div class="empty-hint">No tasks.</div>`}
                ${tasks.map(t => html`
                    <div class="admin-surface-row" key=${t.id}>
                        <div style="flex:1;min-width:0;">
                            <strong>${t.name}</strong>
                            ${t.schedule && html`
                                <span class="badge" style="margin-left:6px;">${t.schedule}</span>
                            `}
                        </div>
                        <span class="text-muted" style="font-size:11px;">
                            last: ${fmtDate(t.last_run_at)} \u2022 next: ${fmtDate(t.next_run_at)}
                        </span>
                        <span class="badge ${t.is_active ? 'badge-active' : 'badge-inactive'}">
                            ${t.is_active ? 'running' : 'stopped'}
                        </span>
                        <div style="display:flex;gap:6px;">
                            <button class="btn-small btn-primary" onClick=${() => runTask(t.id)}>Run</button>
                            <button class="btn-small btn-ghost" onClick=${() => stopTask(t.id)}>Stop</button>
                        </div>
                    </div>
                `)}
            </div>
        </div>
    `;
}
