/**
 * Shared process picker — reusable UI for browsing running processes
 * and adding them to a textarea (one app per line).
 *
 * Usage:
 *   import { attachProcessPicker } from '../core/process-picker.js';
 *   attachProcessPicker(containerEl, textareaEl);
 *
 * The container must already contain:
 *   <button class="btn-browse-apps">Browse</button>
 *   <div class="process-picker" style="display:none">
 *       <input class="process-picker-search" placeholder="..." autocomplete="off">
 *       <div class="process-picker-list"></div>
 *   </div>
 */

import { fetchWithAuth } from './api.js';
import { t } from './i18n.js';
import { escapeHtml } from './api.js';

function renderList(picker, processes, existing) {
    const listEl = picker.querySelector('.process-picker-list');
    if (processes.length === 0) {
        listEl.innerHTML = `<div class="process-picker-loading">${t('automations.condition.application.no_processes')}</div>`;
        return;
    }
    listEl.innerHTML = processes.map(p => {
        const added = existing.has(p.toLowerCase());
        return `<div class="process-picker-item${added ? ' added' : ''}" data-process="${escapeHtml(p)}">${escapeHtml(p)}${added ? ' \u2713' : ''}</div>`;
    }).join('');

    listEl.querySelectorAll('.process-picker-item:not(.added)').forEach(item => {
        item.addEventListener('click', () => {
            const proc = item.dataset.process;
            const textarea = picker._textarea;
            const current = textarea.value.trim();
            textarea.value = current ? current + '\n' + proc : proc;
            item.classList.add('added');
            item.textContent = proc + ' \u2713';
            picker._existing.add(proc.toLowerCase());
        });
    });
}

async function toggle(picker) {
    if (picker.style.display !== 'none') {
        picker.style.display = 'none';
        return;
    }

    const listEl = picker.querySelector('.process-picker-list');
    const searchEl = picker.querySelector('.process-picker-search');
    searchEl.value = '';
    listEl.innerHTML = `<div class="process-picker-loading">${t('common.loading')}</div>`;
    picker.style.display = '';

    try {
        const resp = await fetchWithAuth('/system/processes');
        if (!resp.ok) throw new Error('Failed to fetch processes');
        const data = await resp.json();

        const existing = new Set(
            picker._textarea.value.split('\n').map(a => a.trim().toLowerCase()).filter(Boolean)
        );

        picker._processes = data.processes;
        picker._existing = existing;
        renderList(picker, data.processes, existing);
        searchEl.focus();
    } catch (e) {
        listEl.innerHTML = `<div class="process-picker-loading" style="color:var(--danger-color)">${e.message}</div>`;
    }
}

function filter(picker) {
    const query = picker.querySelector('.process-picker-search').value.toLowerCase();
    const filtered = (picker._processes || []).filter(p => p.includes(query));
    renderList(picker, filtered, picker._existing || new Set());
}

/**
 * Wire up a process picker inside `containerEl` to feed into `textareaEl`.
 * containerEl must contain .btn-browse-apps, .process-picker, .process-picker-search.
 */
export function attachProcessPicker(containerEl, textareaEl) {
    const browseBtn = containerEl.querySelector('.btn-browse-apps');
    const picker = containerEl.querySelector('.process-picker');
    if (!browseBtn || !picker) return;

    picker._textarea = textareaEl;
    browseBtn.addEventListener('click', () => toggle(picker));

    const searchInput = picker.querySelector('.process-picker-search');
    if (searchInput) {
        searchInput.addEventListener('input', () => filter(picker));
    }
}
