// PRE — Workflows Panel
// Extracted from app.js: openWorkflowPanel(), renderWorkflowPanel(), window.Workflows
(() => {
  async function openWorkflowPanel() {
    const content = PRE.openPanel('Workflows');
    try {
      const res = await fetch('/api/workflows');
      const workflows = await res.json();
      renderWorkflowPanel(content, workflows);
    } catch {
      content.innerHTML = '<p style="color:var(--danger)">Failed to load workflows</p>';
    }
  }

  function renderWorkflowPanel(container, workflows) {
    let html = '<div class="settings-section">';
    html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">';
    html += '<div class="settings-section-title" style="margin:0">Saved Workflows</div>';
    html += '</div>';

    if (workflows.length === 0) {
      html += '<p style="color:var(--text-muted);font-size:0.85rem">No saved workflows yet. Record a workflow by asking PRE to start recording, then performing Computer Use actions.</p>';
    } else {
      for (const wf of workflows) {
        const dur = wf.duration ? `${(wf.duration / 1000).toFixed(0)}s` : '?';
        const created = wf.created ? new Date(wf.created).toLocaleDateString() : '?';
        html += `<div class="connection-card" style="margin-bottom:10px">
          <div class="connection-card-header" style="padding:12px 14px">
            <div style="flex:1;min-width:0">
              <div style="font-weight:600;font-size:0.9rem">${PRE.escapeHtml(wf.name)}</div>
              ${wf.description ? `<div style="font-size:0.78rem;color:var(--text-muted);margin-top:2px">${PRE.escapeHtml(wf.description)}</div>` : ''}
              <div style="font-size:0.73rem;color:var(--text-muted);margin-top:2px">${wf.stepCount} steps &middot; ${dur} duration &middot; ${created}</div>
            </div>
            <div style="display:flex;gap:4px;flex-shrink:0">
              <button class="btn btn-ghost btn-sm" onclick="window.Workflows.view('${PRE.escapeHtml(wf.name)}')" title="View steps">View</button>
              <button class="btn btn-ghost btn-sm" onclick="window.Workflows.replay('${PRE.escapeHtml(wf.name)}')" title="Replay workflow">Replay</button>
              <button class="btn btn-ghost btn-sm" onclick="window.Workflows.del('${PRE.escapeHtml(wf.name)}')" style="color:var(--danger)" title="Delete">&times;</button>
            </div>
          </div>
        </div>`;
      }
    }

    html += '<div id="workflow-detail" style="margin-top:12px"></div>';
    html += '</div>';
    container.innerHTML = html;
  }

  // Bind sidebar button
  const btn = document.getElementById('workflow-btn');
  if (btn) btn.addEventListener('click', openWorkflowPanel);

  window.Workflows = {
    async view(name) {
      const detailEl = document.getElementById('workflow-detail');
      if (!detailEl) return;
      detailEl.innerHTML = '<span style="color:var(--text-muted);font-size:0.82rem">Loading...</span>';
      try {
        const res = await fetch(`/api/workflows/${encodeURIComponent(name)}`);
        const data = await res.json();
        detailEl.innerHTML = `<div style="white-space:pre-wrap;font-size:0.82rem;padding:10px;background:var(--surface-2, var(--surface));border-radius:6px;border:1px solid var(--border);max-height:400px;overflow-y:auto">${PRE.escapeHtml(data.text)}</div>`;
      } catch {
        detailEl.innerHTML = '<span style="color:var(--danger);font-size:0.82rem">Failed to load workflow</span>';
      }
    },
    async replay(name) {
      if (!confirm(`Replay workflow "${name}"? This will execute desktop actions.`)) return;
      const detailEl = document.getElementById('workflow-detail');
      if (detailEl) detailEl.innerHTML = '<span style="color:var(--primary);font-size:0.82rem">Replaying...</span>';
      try {
        const res = await fetch(`/api/workflows/${encodeURIComponent(name)}/replay`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ speed: 1.0 }),
        });
        const data = await res.json();
        if (detailEl) detailEl.innerHTML = `<div style="white-space:pre-wrap;font-size:0.82rem;padding:10px;background:var(--surface-2, var(--surface));border-radius:6px;border:1px solid var(--border)">${PRE.escapeHtml(data.text)}</div>`;
      } catch (e) {
        if (detailEl) detailEl.innerHTML = `<span style="color:var(--danger);font-size:0.82rem">Replay failed: ${e.message}</span>`;
      }
    },
    async del(name) {
      if (!confirm(`Delete workflow "${name}"?`)) return;
      await fetch(`/api/workflows/${encodeURIComponent(name)}`, { method: 'DELETE' });
      openWorkflowPanel();
    },
  };
})();
