// PRE — Quick Actions Bar
(() => {
  const qaBar = document.getElementById('quick-actions-bar');

  async function loadQuickActions() {
    try {
      const res = await fetch('/api/quick-actions');
      if (!res.ok) return;
      const actions = await res.json();
      renderQuickActions(actions.filter(a => a.enabled));
    } catch { /* server may not support this endpoint yet */ }
  }

  function renderQuickActions(actions) {
    if (!qaBar) return;
    qaBar.innerHTML = '';
    for (const action of actions) {
      const btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'quick-action-btn';
      btn.title = action.prompt;
      btn.innerHTML = `<span class="qa-icon">${PRE.escapeHtml(action.icon)}</span>${PRE.escapeHtml(action.label)}`;
      btn.addEventListener('click', () => {
        const chatInput = document.getElementById('chat-input');
        const chatForm = document.getElementById('chat-form');
        if (chatInput && chatForm) {
          chatInput.value = action.prompt;
          chatForm.dispatchEvent(new Event('submit', { cancelable: true }));
        }
      });
      qaBar.appendChild(btn);
    }
    // Edit button
    if (actions.length > 0) {
      const editBtn = document.createElement('button');
      editBtn.type = 'button';
      editBtn.className = 'quick-action-edit-btn';
      editBtn.title = 'Edit quick actions';
      editBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>';
      editBtn.addEventListener('click', openQuickActionsEditor);
      qaBar.appendChild(editBtn);
    }
  }

  async function openQuickActionsEditor() {
    const content = PRE.openPanel('Quick Actions');

    let actions = [];
    try {
      const res = await fetch('/api/quick-actions');
      actions = await res.json();
    } catch { return; }

    let html = '<div style="padding:16px">';
    html += '<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px">';
    html += '<h3 style="margin:0;font-size:1rem">Quick Actions</h3>';
    html += '<div style="display:flex;gap:6px">';
    html += '<button class="btn btn-sm" onclick="QuickActions.add()" style="font-size:0.75rem;padding:4px 10px;border:1px solid var(--border);border-radius:6px;background:var(--surface-hover);color:var(--text);cursor:pointer">+ Add</button>';
    html += '<button class="btn btn-sm" onclick="QuickActions.reset()" style="font-size:0.75rem;padding:4px 10px;border:1px solid var(--border);border-radius:6px;background:var(--surface-hover);color:var(--text-muted);cursor:pointer">Reset Defaults</button>';
    html += '</div></div>';

    for (const action of actions) {
      const bg = action.enabled ? 'var(--surface-hover)' : 'transparent';
      const opacity = action.enabled ? '1' : '0.5';
      html += `<div class="connection-card" style="background:${bg};opacity:${opacity};margin-bottom:8px;padding:10px 12px;border-radius:8px;border:1px solid var(--border)">`;
      html += `<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:6px">`;
      html += `<div style="display:flex;align-items:center;gap:6px">`;
      html += `<span style="font-size:1rem">${PRE.escapeHtml(action.icon)}</span>`;
      html += `<strong style="font-size:0.85rem">${PRE.escapeHtml(action.label)}</strong>`;
      html += `</div>`;
      html += `<div style="display:flex;align-items:center;gap:6px">`;
      html += `<label style="font-size:0.7rem;color:var(--text-muted);cursor:pointer;display:flex;align-items:center;gap:4px">`;
      html += `<input type="checkbox" ${action.enabled ? 'checked' : ''} onchange="QuickActions.toggle('${action.id}', this.checked)"> On</label>`;
      html += `<button onclick="QuickActions.edit('${action.id}')" style="font-size:0.7rem;padding:2px 6px;border:1px solid var(--border);border-radius:4px;background:transparent;color:var(--text-muted);cursor:pointer">Edit</button>`;
      html += `<button onclick="QuickActions.del('${action.id}')" style="font-size:0.7rem;padding:2px 6px;border:1px solid var(--border);border-radius:4px;background:transparent;color:var(--danger, #e55);cursor:pointer">Del</button>`;
      html += `</div></div>`;
      html += `<div style="font-size:0.75rem;color:var(--text-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${PRE.escapeHtml(action.prompt)}</div>`;
      html += `</div>`;
    }

    if (actions.length === 0) {
      html += '<div style="text-align:center;color:var(--text-muted);padding:24px;font-size:0.85rem">No quick actions yet. Click "+ Add" to create one.</div>';
    }

    html += '<div id="qa-edit-form" style="display:none;margin-top:12px"></div>';
    html += '</div>';

    content.innerHTML = html;
  }

  function showQaForm(existing) {
    const formEl = document.getElementById('qa-edit-form');
    if (!formEl) return;
    const isEdit = !!existing;
    const label = existing ? existing.label : '';
    const icon = existing ? existing.icon : '\u26A1';
    const prompt = existing ? existing.prompt : '';
    const id = existing ? existing.id : '';

    formEl.style.display = 'block';
    formEl.innerHTML = `
      <div style="border:1px solid var(--primary);border-radius:8px;padding:12px;background:var(--surface)">
        <div style="font-size:0.85rem;font-weight:600;margin-bottom:8px">${isEdit ? 'Edit' : 'New'} Quick Action</div>
        <div style="display:flex;gap:8px;margin-bottom:8px">
          <input id="qa-icon" type="text" value="${PRE.escapeHtml(icon)}" maxlength="4" placeholder="Icon" style="width:48px;text-align:center;padding:6px;border:1px solid var(--border);border-radius:6px;background:var(--surface-hover);color:var(--text);font-size:1rem">
          <input id="qa-label" type="text" value="${PRE.escapeHtml(label)}" placeholder="Label (e.g. Morning Briefing)" style="flex:1;padding:6px 10px;border:1px solid var(--border);border-radius:6px;background:var(--surface-hover);color:var(--text);font-size:0.82rem">
        </div>
        <textarea id="qa-prompt" placeholder="Prompt to send when clicked..." style="width:100%;min-height:60px;padding:8px 10px;border:1px solid var(--border);border-radius:6px;background:var(--surface-hover);color:var(--text);font-size:0.82rem;resize:vertical;box-sizing:border-box;font-family:inherit">${PRE.escapeHtml(prompt)}</textarea>
        <div style="display:flex;gap:6px;margin-top:8px;justify-content:flex-end">
          <button onclick="document.getElementById('qa-edit-form').style.display='none'" style="padding:5px 12px;border:1px solid var(--border);border-radius:6px;background:transparent;color:var(--text-muted);cursor:pointer;font-size:0.78rem">Cancel</button>
          <button onclick="QuickActions.save('${id}')" style="padding:5px 12px;border:1px solid var(--primary);border-radius:6px;background:var(--primary);color:#fff;cursor:pointer;font-size:0.78rem">${isEdit ? 'Save' : 'Add'}</button>
        </div>
      </div>`;
    formEl.scrollIntoView({ behavior: 'smooth' });
  }

  window.QuickActions = {
    async toggle(id, enabled) {
      await fetch(`/api/quick-actions/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ enabled }),
      });
      openQuickActionsEditor();
      loadQuickActions();
    },
    async del(id) {
      await fetch(`/api/quick-actions/${id}`, { method: 'DELETE' });
      openQuickActionsEditor();
      loadQuickActions();
    },
    add() {
      showQaForm(null);
    },
    async edit(id) {
      try {
        const res = await fetch('/api/quick-actions');
        const actions = await res.json();
        const action = actions.find(a => a.id === id);
        if (action) showQaForm(action);
      } catch {}
    },
    async save(id) {
      const label = document.getElementById('qa-label')?.value?.trim();
      const icon = document.getElementById('qa-icon')?.value?.trim() || '\u26A1';
      const prompt = document.getElementById('qa-prompt')?.value?.trim();
      if (!prompt) return;
      if (id) {
        await fetch(`/api/quick-actions/${id}`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ label: label || 'Action', icon, prompt }),
        });
      } else {
        await fetch('/api/quick-actions', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ label: label || 'Action', icon, prompt }),
        });
      }
      openQuickActionsEditor();
      loadQuickActions();
    },
    async reset() {
      await fetch('/api/quick-actions/reset', { method: 'POST' });
      openQuickActionsEditor();
      loadQuickActions();
    },
  };

  // Load on startup
  loadQuickActions();
})();
