import { ref } from 'vue';

const actions = ref([]);

function register(action) {
  if (!action.id || !action.execute) {
    console.warn('[ActionRegistry] Action missing id or execute:', action);
    return;
  }

  const existingIndex = actions.value.findIndex(a => a.id === action.id);
  if (existingIndex !== -1) {
    actions.value[existingIndex] = action;
  } else {
    actions.value.push(action);
  }
}

function unregister(id) {
  actions.value = actions.value.filter(a => a.id !== id);
}

function search(query) {
  if (!query || query.trim() === '') return [];

  const q = query.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();
  if (q === '') return [];

  return actions.value.filter(action => {
    if (typeof action.isActive === 'function' && !action.isActive()) {
      return false;
    }
    const label = (action.label || '').normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
    const description = (action.description || '').normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
    return label.includes(q) || description.includes(q);
  }).sort((a, b) => {
    const aLabel = (a.label || '').toLowerCase();
    const bLabel = (b.label || '').toLowerCase();
    const qLower = q;
    const aStarts = aLabel.startsWith(qLower) ? 0 : 1;
    const bStarts = bLabel.startsWith(qLower) ? 0 : 1;
    return aStarts - bStarts || aLabel.localeCompare(bLabel);
  });
}

function execute(id, params = {}) {
  const action = actions.value.find(a => a.id === id);
  if (action && action.execute) {
    action.execute(params);
  }
}

export { register, unregister, search, execute };
export default { register, unregister, search, execute };
