(function(){
  function $(sel, ctx){ return (ctx||document).querySelector(sel); }
  function $all(sel, ctx){ return Array.from((ctx||document).querySelectorAll(sel)); }

  function parseJSONFromElement(id){
    const el = document.getElementById(id);
    if(!el) return null;
    try { return JSON.parse(el.textContent); } catch(e){ console.warn('JSON invalide', e); return null; }
  }

  function renderInto(root, data){
    root.innerHTML = '';
    Object.keys(data).forEach(cat => {
      const items = data[cat] || [];
      if(!items.length) return;

      const details = document.createElement('details');
      details.className = 'lgp-cat';
      details.open = true;

      const summary = document.createElement('summary');
      summary.className = 'lgp-head';
      summary.innerHTML = '<span>'+cat+'</span><em class="lgp-count">('+items.length+')</em>';
      const btn = document.createElement('button'); btn.type='button'; btn.className='lgp-selectall'; btn.textContent='Tout cocher';
      summary.appendChild(btn);
      details.appendChild(summary);

      const ul = document.createElement('ul'); ul.className='lgp-list';
      items.forEach(t=>{
        const li = document.createElement('li'); li.className='lgp-item';
        const label = document.createElement('label');
        const cb = document.createElement('input'); cb.type='checkbox'; cb.className='lgp-checkbox';
        cb.setAttribute('data-cat', cat); cb.setAttribute('data-title', t);
        const span = document.createElement('span'); span.className='lgp-title'; span.textContent=t;
        label.appendChild(cb); label.appendChild(span); li.appendChild(label); ul.appendChild(li);
      });
      details.appendChild(ul);
      root.appendChild(details);

      btn.addEventListener('click', (e)=>{
        e.preventDefault();
        const cbs = $all('input.lgp-checkbox', details);
        const allChecked = cbs.every(x=>x.checked);
        cbs.forEach(x=>x.checked = !allChecked);
        btn.textContent = allChecked ? 'Tout cocher' : 'Tout décocher';
        collectSelected(root);
      });
    });

    const note = document.createElement('div');
    note.className='lgp-note';
    note.innerHTML="Astuce : modifiez titres/catégories dans le bloc <b>HTML</b> (JSON pur).";
    root.appendChild(note);
  }

  function collectSelected(root){
    const grouped = {};
    $all('.lgp-checkbox:checked', root).forEach(cb=>{
      const cat = cb.getAttribute('data-cat');
      const title = cb.getAttribute('data-title');
      (grouped[cat] ||= []).push(title);
    });
    const lines=[];
    Object.keys(grouped).sort().forEach(cat=>{
      lines.push('['+cat+']');
      grouped[cat].forEach(t=>lines.push('• '+t));
      lines.push('');
    });
    const text = lines.join('\n').trim();

    const formSel = root.getAttribute('data-form-selector') || '.elementor-form';
    const form = document.querySelector(formSel);
    if(!form) return;
    const hidden = form.querySelector('input[name="selected_articles"], textarea[name="selected_articles"]');
    if(hidden){ hidden.value = text; hidden.dispatchEvent(new Event('change')); }
  }

  document.addEventListener('change', (e)=>{
    if(e.target?.classList?.contains('lgp-checkbox')){
      const root = e.target.closest('.lgp-wrapper'); if(root) collectSelected(root);
    }
  });

  document.addEventListener('DOMContentLoaded', ()=>{
    $all('.lgp-wrapper').forEach(root=>{
      const dataId = root.getAttribute('data-data-element-id') || 'lg-proposals-data';
      let data = parseJSONFromElement(dataId);
      if(!data){ data = { "Réglementation & Obligations": ["Biodéchets 2025 : êtes-vous conforme ?"] }; }
      renderInto(root, data);
    });
  });
})();
