/**
 * command-bar.js — Fixed "Run Goal" command bar in the header.
 * ⌘⏎ posts to /api/orchestrate (queued-run path from c4).
 * ⌘K reserved for future palette.
 * Consolidates all "Run Goal" call sites from the monolith.
 */

import { post } from '../api.js';
import { bus }  from '../state.js';

let _running = false;

/** Attach the command bar handlers. Call once on DOMContentLoaded. */
export function init() {
    const input = document.getElementById('cmd-input');
    const btn   = document.getElementById('cmd-run-btn');
    if (!input) return;

    input.addEventListener('keydown', e => {
        if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
            e.preventDefault();
            _submit(input.value);
        }
        if (e.key === 'k' && (e.ctrlKey || e.metaKey)) {
            e.preventDefault();
            bus.emit('palette:open', null); // reserved for future palette
        }
    });

    btn?.addEventListener('click', () => _submit(input.value));
}

async function _submit(raw) {
    const goal = (raw || '').trim();
    if (!goal || _running) return;

    const input = document.getElementById('cmd-input');
    const btn   = document.getElementById('cmd-run-btn');

    _running = true;
    if (btn)   { btn.disabled = true; btn.textContent = 'Running…'; }
    if (input) { input.disabled = true; }

    bus.emit('goal:started', goal);

    const result = await post('/api/orchestrate', { goal, source: 'dashboard' });

    if (!result.ok) {
        bus.emit('toast', { msg: `Goal failed: ${result.error || 'unknown error'}`, kind: 'bad' });
    } else {
        if (input) input.value = '';
        bus.emit('goal:queued', result.data);
    }

    _running = false;
    if (btn)   { btn.disabled = false; btn.textContent = 'Run'; }
    if (input) { input.disabled = false; input.focus(); }
}
