// Basic shared interactions for prototype
(function(){
  function qs(sel, ctx=document){ return ctx.querySelector(sel); }
  function qsa(sel, ctx=document){ return Array.from(ctx.querySelectorAll(sel)); }

  // Overflow menus (three dots) - open/close logic
  document.addEventListener('click', e => {
    const btn = e.target.closest('[data-menu]');
    if(btn){
      const id = btn.getAttribute('data-menu');
      const menu = qs('#menu-' + id);
      if(menu){
        menu.classList.toggle('open');
        // close others
        qsa('.overflow-menu').forEach(m => { if(m !== menu) m.classList.remove('open'); });
      }
    } else if(!e.target.closest('.overflow-menu')) {
      qsa('.overflow-menu').forEach(m => m.classList.remove('open'));
    }
  });

  // Tabs
  function initTabs(container){
    if(!container) return;
    const tabs = qsa('.tab', container);
    const panelRoot = qs('#tabPanels') || container.parentElement;
    tabs.forEach(tab => {
      tab.addEventListener('click', () => {
        const target = tab.getAttribute('data-tab');
        tabs.forEach(t => t.classList.remove('active'));
        tab.classList.add('active');
        qsa('[data-panel]', panelRoot).forEach(p => {
          p.style.display = p.getAttribute('data-panel') === target ? '' : 'none';
        });
      });
    });
  }
  initTabs(qs('#modelTabs'));

  // API Key mask toggle
  qsa('[data-toggle-mask]').forEach(btn => {
    btn.addEventListener('click', () => {
      const input = btn.parentElement.querySelector('[data-mask-target]');
      if(!input) return;
      if(input.type === 'password'){
        input.type = 'text';
        btn.textContent = 'Hide';
      } else {
        input.type = 'password';
        btn.textContent = 'Show';
      }
    });
  });

  // Stepper logic (pipeline configuration)
  const stepper = qs('#pipelineStepper');
  if(stepper){
    stepper.addEventListener('click', e => {
      const stepEl = e.target.closest('.step');
      if(!stepEl) return;
      const targetStep = stepEl.getAttribute('data-step');
      qsa('.step', stepper).forEach(s => {
        const sStep = s.getAttribute('data-step');
        s.classList.remove('active');
        if(Number(sStep) < Number(targetStep)) s.classList.add('completed'); else s.classList.remove('completed');
      });
      stepEl.classList.add('active');
      // toggle panels
      qsa('[data-step-panel]').forEach(p => {
        p.style.display = p.getAttribute('data-step-panel') === targetStep ? '' : 'none';
      });
    });
  }

  // Simple persistence of active nav via location
  const path = location.pathname.split('/').pop();
  qsa('.sidebar .nav a').forEach(a => {
    if(a.getAttribute('href') === path){
      a.classList.add('active');
    } else {
      a.classList.remove('active');
    }
  });

  // ---- Retrieval Configuration Page Enhancements ----
  (function initRetrievalConfig(){
    const slider = qs('#hybridSlider');
    if(!slider) return; // not on this page
    const vW = qs('#vectorWeight');
    const kW = qs('#keywordWeight');
    const ruleBuilder = qs('#ruleBuilder');
    const addRuleBtn = qs('#addRuleBtn');
    const saveBtn = qs('#saveConfigBtn');
    const saveStatus = qs('#saveStatus');

    function markDirty(){ if(saveStatus){ saveStatus.textContent = 'Unsaved changes...'; saveStatus.style.color = 'var(--color-brand)'; } }
    function markSaved(){ if(saveStatus){ saveStatus.textContent = 'Configuration saved (simulated)'; saveStatus.style.color = 'var(--color-text-secondary)'; } }

    slider.addEventListener('input', () => {
      const v = Number(slider.value); const k = 100 - v;
      if(vW) vW.textContent = v + '%';
      if(kW) kW.textContent = k + '%';
      markDirty();
    });

    if(addRuleBtn && ruleBuilder){
      addRuleBtn.addEventListener('click', () => {
        const row = document.createElement('div');
        row.className = 'rule-row'; row.setAttribute('data-rule','');
        row.innerHTML = `\n          <select data-field>\n            <option value="document_type">document_type</option>\n            <option value="source_type">source_type</option>\n            <option value="date">date</option>\n            <option value="language">language</option>\n          </select>\n          <select data-operator>\n            <option value="==">==</option>\n            <option value=">=">>=</option>\n            <option value=">">></option>\n            <option value="<="><=</option>\n            <option value="<"><</option>\n            <option value="contains">contains</option>\n          </select>\n          <input data-value placeholder="value" />\n          <button type="button" class="remove-rule" title="Remove rule">×</button>`;
        ruleBuilder.appendChild(row); markDirty();
      });

      ruleBuilder.addEventListener('click', e => {
        if(e.target.classList.contains('remove-rule')){
          const r = e.target.closest('[data-rule]');
          if(r){ r.remove(); markDirty(); }
        }
      });
      ['change','input'].forEach(evt => ruleBuilder.addEventListener(evt, markDirty));
    }

    ['mmToggle','rerankToggle','postRerankN','rerankerModel'].forEach(id => {
      const el = qs('#'+id); if(el){ el.addEventListener('change', markDirty); el.addEventListener('input', markDirty); }
    });

    if(saveBtn){
      saveBtn.addEventListener('click', () => {
        saveBtn.disabled = true; const orig = saveBtn.textContent; saveBtn.textContent = 'Saving...';
        setTimeout(()=>{ saveBtn.textContent = orig; saveBtn.disabled = false; markSaved(); }, 900);
      });
    }
  })();

  // ---- Knowledge Base Detail Page Enhancements ----
  (function initKbDetail(){
    const uploadZone = qs('#uploadZone');
    if(!uploadZone) return; // not on detail page
    const fileInput = qs('#fileInput');
    const browseTrigger = qs('#browseTrigger');
    const ingestQueue = qs('#ingestQueue');
    const queueCount = qs('#queueCount');
    const docTable = qs('#docTable');
    const reindexBtn = qs('#reindexBtn');
    const syncBtn = qs('#syncNowBtn');
    const syncStatus = qs('#syncStatus');
    const estimateBtn = qs('#estimateBtn');
    const versionList = qs('#versionList');
    const versionStatus = qs('#versionStatus');
    const aclTable = qs('#aclTable');
    const addAclBtn = qs('#addAclBtn');
    const aclPrincipal = qs('#aclPrincipal');
    const aclRole = qs('#aclRole');
    const aclScope = qs('#aclScope');

    function addDocs(files){
      if(!files.length) return;
      if(ingestQueue) ingestQueue.style.display = 'block';
      if(queueCount){ queueCount.textContent = (Number(queueCount.textContent) + files.length).toString(); }
      Array.from(files).forEach(file => {
        const row = document.createElement('tr');
        const ext = (file.name.split('.').pop()||'txt');
        row.innerHTML = `<td>${file.name}</td><td>${ext}</td><td>—</td><td><span class="status-pill">pending</span></td>`;
        if(docTable) docTable.appendChild(row);
        setTimeout(()=>{
          const status = row.querySelector('.status-pill');
          if(status){ status.textContent='ready'; status.classList.add('status-success'); }
          row.children[2].textContent = Math.floor(Math.random()*120)+10;
        }, 1300 + Math.random()*1200);
      });
    }

    if(browseTrigger && fileInput){ browseTrigger.addEventListener('click', () => fileInput.click()); }
    if(fileInput){ fileInput.addEventListener('change', e => addDocs(e.target.files)); }
    if(uploadZone){
      uploadZone.addEventListener('dragover', e => { e.preventDefault(); uploadZone.classList.add('drag-over'); });
      uploadZone.addEventListener('dragleave', () => uploadZone.classList.remove('drag-over'));
      uploadZone.addEventListener('drop', e => { e.preventDefault(); uploadZone.classList.remove('drag-over'); addDocs(e.dataTransfer.files); });
    }
    if(reindexBtn){
      reindexBtn.addEventListener('click', () => {
        reindexBtn.disabled = true; const orig = reindexBtn.textContent; reindexBtn.textContent = 'Reindexing...';
        setTimeout(()=>{ reindexBtn.textContent = orig; reindexBtn.disabled = false; alert('Reindex simulation completed.'); }, 1800);
      });
    }
    if(syncBtn && syncStatus){
      syncBtn.addEventListener('click', () => {
        syncStatus.textContent = 'Sync in progress...'; syncStatus.style.color = 'var(--color-brand)';
        setTimeout(()=>{ syncStatus.textContent = 'Last sync: just now (simulated)'; syncStatus.style.color = 'var(--color-text-secondary)'; }, 1400);
      });
    }
    if(estimateBtn){
      estimateBtn.addEventListener('click', () => {
        estimateBtn.disabled = true; const orig = estimateBtn.textContent; estimateBtn.textContent='Calculating...';
        setTimeout(()=>{ const cost = 150 + Math.floor(Math.random()*60); const mc = qs('#monthlyCost'); if(mc) mc.textContent = '$'+cost; estimateBtn.textContent=orig; estimateBtn.disabled=false; }, 1000);
      });
    }
    if(versionList){
      versionList.addEventListener('click', e => {
        const btn = e.target.closest('.rollback-btn'); if(!btn) return;
        const v = btn.getAttribute('data-target');
        if(confirm('Simulate rollback to version '+v+'?')){
          if(versionStatus){ versionStatus.textContent = 'Rolling back to v'+v+' ...'; versionStatus.style.color = 'var(--color-brand)'; }
          setTimeout(()=>{ if(versionStatus){ versionStatus.textContent = 'Current active version: v'+v+' (simulated rollback)'; versionStatus.style.color = 'var(--color-text-secondary)'; } }, 1300);
        }
      });
    }
    if(addAclBtn && aclTable){
      addAclBtn.addEventListener('click', () => {
        const p = (aclPrincipal && aclPrincipal.value.trim()) || ''; if(!p) return;
        const role = (aclRole && aclRole.value) || 'reader'; const scope = (aclScope && aclScope.value.trim()) || 'all';
        const row = document.createElement('tr');
        row.innerHTML = `<td>${p}</td><td>${role}</td><td>${scope}</td><td><button class="remove-acl" title="Remove">×</button></td>`;
        const body = aclTable.querySelector('tbody'); if(body) body.appendChild(row);
        if(aclPrincipal) aclPrincipal.value=''; if(aclScope) aclScope.value='';
      });
      aclTable.addEventListener('click', e => { if(e.target.classList.contains('remove-acl')) e.target.closest('tr').remove(); });
    }
  })();
})();