/**
 * Settings > Workflows — v0.37.15 rewrite
 *
 * Replaces read-only workflow list with MyAssignments (E4).
 * Shows the user's personal assignment queue across all teams.
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;

function _timeAgo(ts) {
    if (!ts) return '';
    const diff = Date.now() - new Date(ts).getTime();
    const mins = Math.floor(diff / 60000);
    if (mins < 1) return 'just now';
    if (mins < 60) return `${mins}m ago`;
    const hrs = Math.floor(mins / 60);
    if (hrs < 24) return `${hrs}h ago`;
    return `${Math.floor(hrs / 24)}d ago`;
}

export default function WorkflowsSection() {
    const [assignments, setAssignments] = useState([]);
    const [loading, setLoading] = useState(true);

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

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

    const userId = sw.auth?.user?.id;
    const mine = assignments.filter(a => a.status === 'claimed' && a.assigned_to === userId);
    const available = assignments.filter(a => a.status === 'unassigned');

    async function claim(id) {
        try {
            await sw.api.workflowAssignments.claim(id);
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function unclaim(id) {
        try {
            await sw.api.workflowAssignments.unclaim(id);
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function complete(id) {
        try {
            await sw.api.workflowAssignments.complete(id);
            sw.toast('Assignment completed', 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

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

    return html`
        <div>
            ${mine.length > 0 && html`
                <h4 style="margin:0 0 8px;">Claimed (${mine.length})</h4>
                <div class="admin-list">
                    ${mine.map(a => html`
                        <${AssignmentRow} key=${a.id} assignment=${a} onAction=${load} showTeam />
                    `)}
                </div>
            `}

            ${available.length > 0 && html`
                <h4 style="margin:${mine.length > 0 ? '16px' : '0'} 0 8px;">Available (${available.length})</h4>
                <div class="admin-list">
                    ${available.map(a => html`
                        <${AssignmentRow} key=${a.id} assignment=${a} onAction=${load} showTeam />
                    `)}
                </div>
            `}

            ${mine.length === 0 && available.length === 0 && html`
                <div class="empty-hint">No assignments</div>
            `}
        </div>
    `;
}

function AssignmentRow({ assignment: a, onAction, showTeam }) {
    const userId = sw.auth?.user?.id;
    const isMine = a.assigned_to === userId;

    async function claim() {
        try {
            await sw.api.workflowAssignments.claim(a.id);
            onAction();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function unclaim() {
        try {
            await sw.api.workflowAssignments.unclaim(a.id);
            onAction();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function complete() {
        try {
            await sw.api.workflowAssignments.complete(a.id);
            sw.toast('Assignment completed', 'success');
            onAction();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    return html`
        <div class="admin-surface-row" style="${isMine ? 'border-left:3px solid var(--accent-1);' : ''}">
            <div style="flex:1;min-width:0;">
                <strong>${a.workflow_name || 'Workflow'}</strong>
                ${showTeam && a.team_name && html`<span class="badge">${a.team_name}</span>`}
                <span class="badge">${a.stage_name || `Stage ${a.stage}`}</span>
                ${a.sla_breached && html`<span class="badge badge-danger">SLA</span>`}
                <span class="text-muted" style="font-size:11px;">${_timeAgo(a.created_at)}</span>
            </div>
            <div style="display:flex;gap:4px;">
                ${a.status === 'unassigned' && html`
                    <button class="btn-small btn-primary" onClick=${claim}>Claim</button>
                `}
                ${isMine && html`
                    <button class="btn-small" onClick=${unclaim}>Release</button>
                    <button class="btn-small btn-primary"
                        onClick=${() => { location.href = sw.base + '/w/' + a.channel_id; }}>Open</button>
                    <button class="btn-small btn-success" onClick=${complete}>Complete</button>
                `}
            </div>
        </div>
    `;
}
