(function () {
  'use strict';
  if(window.__ICY_BILLING_BULK_ACTIONS_ATTACHED)return;
  window.__ICY_BILLING_BULK_ACTIONS_ATTACHED=true;
  const byId = id => document.getElementById(id);
  const value = id => byId(id)?.value || '';
  const config = {
    documents: { env:'documentsEnv', search:'documentsSearch', family:'documentsFamily', from:'documentsFrom', to:'documentsTo', reload:'reloadDocumentsBtn', selected:'.document-select:checked' },
    receivables: { env:'receivablesEnv', search:'receivablesSearch', status:'receivablesStatus', from:'receivablesFrom', to:'receivablesTo', reload:'reloadReceivablesBtn', selected:'.receivable-select:checked' },
    payables: { env:'payablesEnv', search:'payablesSearch', status:'payablesStatus', from:'payablesFrom', to:'payablesTo', reload:'reloadPayablesBtn', selected:'.payable-select:checked' },
    customer_aging: { env:'customerAgingEnv', search:'customerAgingSearch', bucket:'customerAgingBucket', center_id:'customerAgingCenter', reload:'reloadCustomerAgingBtn' },
    supplier_aging: { env:'agingEnv', search:'agingSearch', bucket:'agingBucket', center_id:'agingCenter', reload:'reloadAgingBtn' }
  };
  function params(scope) {
    const c=config[scope], p=new URLSearchParams({scope,environment:value(c.env)||'production'});
    ['search','family','status','from','to','bucket','center_id'].forEach(k=>{ if(c[k]&&value(c[k])) p.set(k,value(c[k])); });
    if(c.selected){ const ids=[...document.querySelectorAll(c.selected)].map(x=>x.dataset.documentId||x.dataset.receivableId||x.dataset.payableId).filter(Boolean); if(ids.length)p.set('ids',ids.join(',')); }
    return p;
  }
  async function refresh(scope, button) {
    const p=params(scope);
    if(!window.confirm('Se sincronizarán o recalcularán los estados visibles desde sus fuentes de verdad. ¿Continuar?')) return;
    button.disabled=true;
    try {
      const response=await fetch('/modules/billing/bulk_refresh_ajax.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'},body:p});
      const data=await response.json();
      if(!response.ok||!data.success) throw new Error(data.message||'No fue posible actualizar los estados.');
      window.alert(data.message);
      byId(config[scope].reload)?.click();
    } catch(error) { window.alert(error.message); }
    finally { button.disabled=false; }
  }
  document.addEventListener('click', function(event){
    const action=event.target.closest('[data-billing-bulk-action]');
    if(!action)return;
    const host=action.closest('[data-billing-actions-scope]'), scope=host?.dataset.billingActionsScope;
    if(!config[scope])return;
    event.preventDefault();
    host.removeAttribute('open');
    if(action.dataset.billingBulkAction==='xlsx') window.location.href='/modules/billing/bulk_export_xlsx.php?'+params(scope).toString();
    if(action.dataset.billingBulkAction==='refresh') refresh(scope,action);
  });
})();
