// public/assets/js/app.js

(function(){
  var input = document.getElementById('sidebarMenuSearch');
  var list = document.getElementById('sidebarMenuList');
  if(!input || !list) return;
  var empty = document.createElement('div');
  empty.className = 'sidebar-empty d-none';
  empty.textContent = 'لا توجد نتائج مطابقة';
  list.parentNode.insertBefore(empty, list.nextSibling);

  function norm(v){ return (v||'').toLowerCase().trim(); }
  function run(){
    var q = norm(input.value);
    var links = list.querySelectorAll('a.nav-link[data-search]');
    var visibleCount = 0;
    links.forEach(function(a){
      var match = !q || norm(a.dataset.search).indexOf(q) !== -1 || norm(a.textContent).indexOf(q) !== -1;
      var item = a.closest('.nav-item');
      if(item){ item.style.display = match ? '' : 'none'; }
      if(match){
        visibleCount++;
        var collapse = a.closest('.collapse');
        if(collapse && q){ collapse.classList.add('show'); collapse.previousElementSibling?.setAttribute('aria-expanded','true'); }
      }
    });
    list.querySelectorAll('.nav-header').forEach(function(h){
      var next = h.nextElementSibling;
      var anyVisible = false;
      while(next && !next.classList.contains('nav-header')){
        if(next.style.display !== 'none'){ anyVisible = true; break; }
        next = next.nextElementSibling;
      }
      h.style.display = anyVisible || !q ? '' : 'none';
    });
    empty.classList.toggle('d-none', visibleCount !== 0 || !q);
  }
  input.addEventListener('input', run);
  document.querySelector('[data-sidebar-search-shortcut]')?.addEventListener('click', function(){ input.focus(); });
  document.addEventListener('keydown', function(e){
    var target = e.target;
    var typing = target && /input|textarea|select/i.test(target.tagName);
    if((e.key === '/' || (e.ctrlKey && e.key.toLowerCase()==='k')) && !typing){
      e.preventDefault(); input.focus(); input.select();
    }
    if(e.key === 'F4'){
      var printBtn = document.querySelector('[data-shortcut="print"], a[target="_blank"][href*="print_"], .btn-print');
      if(printBtn){ e.preventDefault(); printBtn.click(); }
    }
    if(e.key === 'F2'){
      var postBtn = document.querySelector('[data-shortcut="post"], .btn-post, button[name="post"], button[value="post"], [data-shortcut="save-post"]');
      if(postBtn){ e.preventDefault(); postBtn.click(); }
    }
    if(e.key === 'F7'){
      var saveBtn = document.querySelector('[data-shortcut="save"], button[type="submit"], .btn-save');
      if(saveBtn && !typing){ e.preventDefault(); saveBtn.click(); }
    }
    if(e.key === 'F3'){
      var addLineBtn = document.querySelector('[data-shortcut="add-line"], #addLine');
      if(addLineBtn && !typing){ e.preventDefault(); addLineBtn.click(); }
    }
    if(e.key === 'Escape'){
      var backBtn = document.querySelector('[data-shortcut="back"], .btn-back, a[href]:not([target="_blank"])');
      if(backBtn && !typing){ backBtn.click(); }
    }
  });
})();


(function(){
  function norm(v){ return (v||'').toString().toLowerCase().trim(); }

  function setupSearchableSelect(select){
    if(!select || select.dataset.searchableReady==='1') return;
    select.dataset.searchableReady='1';
    var options = Array.from(select.options || []).map(function(opt){
      return {value: opt.value, text: (opt.textContent||'').trim(), disabled: !!opt.disabled};
    });
    var wrapper = document.createElement('div');
    wrapper.className = 'app-searchable-select';
    var input = document.createElement('input');
    input.type = 'text';
    input.className = 'form-control app-searchable-select__input';
    input.placeholder = select.getAttribute('data-search-placeholder') || 'اكتب أول حرفين للبحث...';
    input.autocomplete = 'off';
    var box = document.createElement('div');
    box.className = 'app-searchable-select__results d-none';
    select.parentNode.insertBefore(wrapper, select);
    wrapper.appendChild(input);
    wrapper.appendChild(box);
    wrapper.appendChild(select);
    select.classList.add('app-searchable-select__native');

    function selectedText(){
      var opt = select.options[select.selectedIndex];
      return opt ? (opt.textContent||'').trim() : '';
    }
    function render(term){
      var q = norm(term);
      var rows = options.filter(function(opt){
        if(!opt.value || opt.disabled) return false;
        return !q || norm(opt.text).indexOf(q) !== -1;
      }).slice(0, 12);
      if(!q){ box.classList.add('d-none'); box.innerHTML=''; return; }
      if(!rows.length){
        box.innerHTML = '<button type="button" class="app-searchable-select__item is-empty" disabled>لا توجد نتائج مطابقة</button>';
        box.classList.remove('d-none'); return;
      }
      box.innerHTML = rows.map(function(row){
        return '<button type="button" class="app-searchable-select__item" data-value="'+ String(row.value).replace(/"/g,'&quot;') +'">'+ row.text.replace(/</g,'&lt;') +'</button>';
      }).join('');
      box.classList.remove('d-none');
    }
    function syncInput(){
      input.value = selectedText();
    }
    syncInput();
    input.addEventListener('focus', function(){ if(input.value.trim()!==''){ render(input.value); input.select(); } });
    input.addEventListener('input', function(){ render(input.value); });
    input.addEventListener('keydown', function(e){ if(e.key==='Escape'){ box.classList.add('d-none'); } });
    box.addEventListener('click', function(e){
      var btn = e.target.closest('.app-searchable-select__item[data-value]');
      if(!btn) return;
      select.value = btn.getAttribute('data-value') || '';
      select.dispatchEvent(new Event('change', {bubbles:true}));
      syncInput();
      box.classList.add('d-none');
    });
    select.addEventListener('change', syncInput);
    document.addEventListener('click', function(e){ if(!wrapper.contains(e.target)){ box.classList.add('d-none'); } });
  }

  document.querySelectorAll('select[data-searchable-select]').forEach(setupSearchableSelect);
})();
