import { api } from '../../lib/api.mjs';
import './profile-form.mjs';
const PRIORITY_COLORS = { low: '#64748B', normal: '#0A7EA4', high: '#E07B39', urgent: '#C0392B' };
class ProfileList extends HTMLElement {
#items = [];
#loading = true;
#search = '';
connectedCallback() {
if (!this.shadowRoot) this.attachShadow({ mode: 'open' });
this.#load();
}
async #load() {
this.#loading = true;
this.#render();
try {
this.#items = await api.get(`/profiles?all=1${this.#search ? '&search=' + encodeURIComponent(this.#search) : ''}`) || [];
} catch { this.#items = []; }
this.#loading = false;
this.#render();
}
async #deactivate(id) {
try {
await api.delete(`/profiles/${id}`);
window.dispatchEvent(new CustomEvent('wo:toast', { detail: { message: 'Profile deactivated', type: 'success' } }));
await this.#load();
} catch (err) {
window.dispatchEvent(new CustomEvent('wo:toast', { detail: { message: err.message, type: 'error' } }));
}
}
#render() {
const s = this.shadowRoot;
s.innerHTML = `
${this.#loading ? '' :
this.#items.length === 0
? `
No profiles found
`
: `
${this.#items.map(p => `
${this.#esc(p.name)}
${p.category ? `${this.#esc(p.category)}` : ''}
${p.default_priority}
${p.step_count} step${p.step_count !== 1 ? 's' : ''}
${p.default_duration_hours ? `â± ${p.default_duration_hours}h` : ''}
${p.active ? 'Active' : 'Inactive'}
${p.active ? `` : ''}
`).join('')}
`}
`;
if (window.lucide) lucide.createIcons({ root: s });
const searchEl = s.querySelector('#search');
let debounce;
searchEl.addEventListener('input', () => {
clearTimeout(debounce);
debounce = setTimeout(() => { this.#search = searchEl.value; this.#load(); }, 350);
});
s.querySelector('#new-btn').addEventListener('click', () =>
s.querySelector('#profile-form').open(null, () => this.#load()));
s.querySelectorAll('[data-edit]').forEach(btn => {
btn.addEventListener('click', async () => {
const id = +btn.dataset.edit;
try {
const full = await api.get(`/profiles/${id}`);
s.querySelector('#profile-form').open(full, () => this.#load());
} catch (err) {
window.dispatchEvent(new CustomEvent('wo:toast', { detail: { message: err.message, type: 'error' } }));
}
});
});
s.querySelectorAll('[data-deactivate]').forEach(btn =>
btn.addEventListener('click', () => this.#deactivate(+btn.dataset.deactivate)));
}
#esc(s) { return (s || '').replace(/&/g, '&').replace(//g, '>'); }
}
customElements.define('profile-list', ProfileList);