(function(){
  const ctx = window.BOL_DOC_EDITOR || {};
  const canvas = document.getElementById('document-canvas');
  const fields = Array.from(document.querySelectorAll('.doc-field'));
  const jump = document.getElementById('jumpField');

  const insTitle = document.getElementById('insTitle');
  const insMeta = document.getElementById('insMeta');
  const insBody = document.getElementById('insBody');
  const insLabel = document.getElementById('insLabel');

  const presetBlock = document.getElementById('presetBlock');
  const presetSelect = document.getElementById('presetSelect');

  const simpleInputBlock = document.getElementById('simpleInputBlock');
  const simpleInput = document.getElementById('simpleInput');
  const simpleInputLabel = document.getElementById('simpleInputLabel');

  const checkboxBlock = document.getElementById('checkboxBlock');
  const checkboxInput = document.getElementById('checkboxInput');

  const richBlock = document.getElementById('richBlock');
  const richEditor = document.getElementById('richEditor');
  const richToolbar = document.getElementById('richToolbar');

  const btnApply = document.getElementById('btnApply');
  const btnSave = document.getElementById('btnSave');
  const form = document.getElementById('docForm');

  let selected = null;

  function setSelected(el){
    if (selected) selected.classList.remove('selected');
    selected = el;
    if (!selected) {
      insTitle.textContent = 'Field';
      insMeta.textContent = 'Select a field on the document.';
      insBody.style.display = 'none';
      return;
    }
    selected.classList.add('selected');
    const id = selected.dataset.id;
    const code = selected.dataset.code;
    const label = selected.dataset.label;
    const type = selected.dataset.type;
    const isMultiline = selected.dataset.multiline === '1';

    insTitle.textContent = 'Field Inspector';
    insMeta.textContent = `code: ${code} • type: ${type}`;
    insBody.style.display = '';

    insLabel.value = `${label} (${code})`;

    // populate inputs from hidden field value
    const hidden = document.getElementById(`fieldInput${id}`);
    const raw = hidden ? hidden.value : '';

    // hide all blocks
    presetBlock.style.display = 'none';
    simpleInputBlock.style.display = 'none';
    checkboxBlock.style.display = 'none';
    richBlock.style.display = 'none';

    if (type === 'preset') {
      presetBlock.style.display = '';
      presetSelect.value = raw || '';
    } else if (type === 'checkbox') {
      checkboxBlock.style.display = '';
      checkboxInput.checked = (raw === '1');
    } else if (type === 'date' || type === 'number') {
      simpleInputBlock.style.display = '';
      simpleInput.type = type;
      simpleInputLabel.textContent = 'Value';
      simpleInput.value = raw || '';
    } else {
      // text / multiline / others => rich editor
      richBlock.style.display = '';
      // raw may include HTML; show it as HTML
      richEditor.innerHTML = raw || '';
      // focus editor
      setTimeout(()=>richEditor.focus(), 0);
    }
  }

  function applyToDocument(){
    if (!selected) return;
    const id = selected.dataset.id;
    const type = selected.dataset.type;

    let value = '';

    if (type === 'preset') {
      value = presetSelect.value || '';
    } else if (type === 'checkbox') {
      value = checkboxInput.checked ? '1' : '';
    } else if (type === 'date' || type === 'number') {
      value = simpleInput.value || '';
    } else {
      value = richEditor.innerHTML || '';
    }

    // update hidden input
    const hidden = document.getElementById(`fieldInput${id}`);
    if (hidden) hidden.value = value;

    // update canvas render
    const valueDiv = selected.querySelector('.value');
    if (valueDiv) {
      if (type === 'preset') {
        const opt = presetSelect.options[presetSelect.selectedIndex];
        valueDiv.textContent = opt && opt.value ? opt.text : '';
      } else if (type === 'checkbox') {
        valueDiv.textContent = (value === '1') ? 'X' : '';
      } else {
        // render HTML for rich, plain for simple
        if (type === 'date' || type === 'number') valueDiv.textContent = value;
        else valueDiv.innerHTML = value;
      }
    }
  }

  // click select on canvas
  fields.forEach(el=>{
    el.addEventListener('click', (e)=>{
      e.preventDefault();
      e.stopPropagation();
      setSelected(el);
      if (jump) jump.value = el.dataset.id;
    });
  });

  // click outside to deselect
  if (canvas) {
    canvas.addEventListener('click', (e)=>{
      if (e.target === canvas || e.target.id === 'document-bg') {
        setSelected(null);
        if (jump) jump.value = '';
      }
    });
  }

  // jump dropdown
  if (jump) {
    jump.addEventListener('change', ()=>{
      const id = jump.value;
      const el = fields.find(x => x.dataset.id === id);
      if (el) {
        setSelected(el);
        // scroll into view if canvas scrollable (not by default)
      }
    });
  }

  // rich toolbar via execCommand
  if (richToolbar) {
    richToolbar.addEventListener('click', (e)=>{
      const btn = e.target.closest('button');
      if (!btn) return;
      const cmd = btn.dataset.cmd;
      const action = btn.dataset.action;
      e.preventDefault();
      if (!selected) return;
      if (action === 'clear') {
        richEditor.innerHTML = '';
        richEditor.focus();
        return;
      }
      if (cmd) {
        richEditor.focus();
        try {
          document.execCommand(cmd, false, null);
        } catch (err) {
          // ignore
        }
      }
    });
  }

  // preset select: add new preset
  if (presetSelect) {
    presetSelect.addEventListener('change', async ()=>{
      if (presetSelect.value !== '__add_new__') return;
      const name = prompt('New preset name:');
      if (!name) {
        presetSelect.value = '';
        return;
      }
      try {
        const createRes = await fetch('/smproduce/pages/bol_presets_api.php?action=create', { credentials:'same-origin' });
        const createJson = await createRes.json();
        if (!createJson.ok) throw new Error(createJson.error || 'Create failed');
        const id = createJson.id;

        const saveRes = await fetch('/smproduce/pages/bol_presets_api.php?action=save', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials:'same-origin',
          body: JSON.stringify({ id, name, description:'', values_json_pretty:'{}' })
        });
        const saveJson = await saveRes.json();
        if (!saveJson.ok) throw new Error(saveJson.error || 'Save failed');

        // insert option before add_new
        const opt = document.createElement('option');
        opt.value = String(id);
        opt.textContent = name;

        const addOpt = Array.from(presetSelect.options).find(o=>o.value==='__add_new__');
        presetSelect.insertBefore(opt, addOpt);
        presetSelect.value = String(id);

        alert('Preset created. To fill its values, open Presets management.');
      } catch (err) {
        alert('Could not create preset: ' + (err && err.message ? err.message : err));
        presetSelect.value = '';
      }
    });
  }

  btnApply?.addEventListener('click', ()=>{
    applyToDocument();
  });

  btnSave?.addEventListener('click', ()=>{
    // apply current before save
    applyToDocument();
    form.submit();
  });

  // initial render for preset/checkbox fields based on stored hidden values
  fields.forEach(el=>{
    const id = el.dataset.id;
    const type = el.dataset.type;
    const hidden = document.getElementById(`fieldInput${id}`);
    const raw = hidden ? hidden.value : '';
    const valueDiv = el.querySelector('.value');
    if (!valueDiv) return;

    if (type === 'preset') {
      const opt = presetSelect ? null : null; // handled below
      // create a temporary mapping from ctx.presets
      const p = (ctx.presets || []).find(x => String(x.id) === String(raw));
      valueDiv.textContent = p ? p.name : '';
    } else if (type === 'checkbox') {
      valueDiv.textContent = (raw === '1') ? 'X' : '';
    } else {
      // if looks like HTML, render; else text
      if (raw && /<\/?[a-z][\s\S]*>/i.test(raw)) valueDiv.innerHTML = raw;
      else valueDiv.textContent = raw || '';
    }
  });

})();

// Preset creation from document
const presetSelect = document.getElementById('presetSelect');
const addPresetBtn = document.getElementById('addPresetFromDoc');

if(addPresetBtn){
addPresetBtn.addEventListener('click', () => {
    fetch('/ajax/get_bol_template_fields.php?template=bill_of_lading')
        .then(r=>r.json())
        .then(fields=>{
            const c=document.getElementById('presetFieldsContainer');
            c.innerHTML='';
            fields.forEach(f=>{
                c.insertAdjacentHTML('beforeend',`
                    <div class="mb-2">
                      <label class="form-label">${f.label}</label>
                      <textarea class="form-control" data-field="${f.name}" rows="2"></textarea>
                    </div>`);
            });
            new bootstrap.Modal(document.getElementById('newPresetModal')).show();
        });
});
}

const saveBtn=document.getElementById('savePresetFromDoc');
if(saveBtn){
saveBtn.addEventListener('click',()=>{
    const client=document.getElementById('presetClient').value.trim();
    const preset=document.getElementById('presetName').value.trim();
    if(!client||!preset){alert('Cliente e nome preset obbligatori');return;}
    const values={};
    document.querySelectorAll('#presetFieldsContainer [data-field]').forEach(el=>{
        values[el.dataset.field]=el.value;
    });
    fetch('/ajax/save_bol_preset.php',{
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify({client,preset,values})
    }).then(()=>{
        const opt=new Option(preset,preset,true,true);
        if(presetSelect){presetSelect.add(opt);presetSelect.dispatchEvent(new Event('change'));}
        bootstrap.Modal.getInstance(document.getElementById('newPresetModal')).hide();
    });
});
}


// BOL table collapse filters
const bolCollapse = document.getElementById('bolTableCollapse');
const filters = document.getElementById('bolTableFilters');

if (bolCollapse && filters) {
    bolCollapse.addEventListener('shown.bs.collapse', () => {
        filters.classList.remove('d-none');
    });
    bolCollapse.addEventListener('hidden.bs.collapse', () => {
        filters.classList.add('d-none');
    });

    document.querySelectorAll('#bolTableFilters [data-filter]').forEach(input => {
        input.addEventListener('input', () => {
            const value = input.value.toLowerCase();
            const index = input.dataset.filter === 'id' ? 0 : 1;
            document.querySelectorAll('#bolTable tbody tr').forEach(row => {
                const cell = row.children[index]?.innerText.toLowerCase() || '';
                row.style.display = cell.includes(value) ? '' : 'none';
            });
        });
    });
}
