// PRE — Triggers Panel
(() => {
  const escapeHtml = PRE.escapeHtml;

  async function openTriggersPanel() {
    const content = PRE.openPanel('Triggers', null);

    try {
      const res = await fetch('/api/triggers');
      const triggers = await res.json();
      renderTriggersPanel(content, triggers);
    } catch {
      content.innerHTML = '<p style="color:var(--danger)">Failed to load triggers</p>';
    }
  }

  function renderTriggersPanel(container, triggers) {
    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">Triggers</div>';
    html += '<button class="btn btn-primary btn-sm" onclick="window.Triggers.showAdd()">+ New Trigger</button>';
    html += '</div>';

    if (triggers.length === 0) {
      html += '<p style="color:var(--text-muted);font-size:0.85rem">No triggers yet. Create a file watcher or webhook to fire prompts automatically.</p>';
    } else {
      for (const t of triggers) {
        const statusDot = t.enabled
          ? '<span style="color:var(--success)">&#9679;</span>'
          : '<span style="color:var(--text-muted)">&#9679;</span>';
        const typeLabel = t.type === 'file_watch' ? 'File Watch' : 'Webhook';
        const typeBadge = `<span style="font-size:0.7rem;padding:1px 6px;border-radius:4px;background:var(--surface-hover);color:var(--text-secondary)">${typeLabel}</span>`;
        const lastFired = t.last_fired_at ? PRE.timeAgo(t.last_fired_at) : 'Never';
        const created = t.created_at ? new Date(t.created_at).toLocaleDateString() : '';

        // Watcher/webhook status indicator
        let liveStatus = '';
        if (t.type === 'file_watch') {
          if (t.enabled && t.watching) {
            liveStatus = '<span style="font-size:0.7rem;padding:1px 6px;border-radius:4px;background:rgba(74,222,128,0.15);color:var(--success)">Watching</span>';
          } else if (t.enabled) {
            liveStatus = '<span style="font-size:0.7rem;padding:1px 6px;border-radius:4px;background:rgba(251,191,36,0.15);color:var(--warning)">Not watching</span>';
          }
        } else if (t.type === 'webhook') {
          if (t.enabled) {
            liveStatus = '<span style="font-size:0.7rem;padding:1px 6px;border-radius:4px;background:rgba(74,222,128,0.15);color:var(--success)">Listening</span>';
          }
        }

        // Build detail lines based on trigger type
        let detail = '';
        if (t.type === 'file_watch' && t.config?.path) {
          detail += `<div style="font-size:0.75rem;color:var(--text-muted);margin-top:3px">`;
          detail += `Path: <code style="font-family:'SF Mono',monospace;font-size:0.7rem">${escapeHtml(t.config.path)}</code>`;
          if (t.config.glob) detail += ` &middot; Filter: <code style="font-family:'SF Mono',monospace;font-size:0.7rem">${escapeHtml(t.config.glob)}</code>`;
          detail += `</div>`;
          detail += `<div style="font-size:0.73rem;color:var(--text-muted);margin-top:1px">`;
          detail += `Recursive: ${t.config.recursive !== false ? 'Yes' : 'No'}`;
          detail += ` &middot; Debounce: ${((t.config.debounce || 3000) / 1000).toFixed(0)}s`;
          detail += ` &middot; Fires on: file create/modify/delete`;
          detail += `</div>`;
        } else if (t.type === 'webhook') {
          detail += `<div style="font-size:0.75rem;color:var(--text-muted);margin-top:3px">`;
          detail += `Endpoint: <code style="font-family:'SF Mono',monospace;font-size:0.7rem">POST /api/triggers/webhook/${escapeHtml(t.id)}</code>`;
          if (t.config?.secret) detail += ` &middot; Secret: configured`;
          detail += `</div>`;
        }

        html += `<div class="connection-card" style="margin-bottom:10px">
          <div class="connection-card-header" style="padding:12px 14px">
            <div style="display:flex;align-items:center;gap:8px;flex:1;min-width:0">
              ${statusDot}
              <div style="flex:1;min-width:0">
                <div style="font-weight:600;font-size:0.9rem;display:flex;align-items:center;gap:8px">${escapeHtml(t.name)} ${typeBadge} ${liveStatus}</div>
                ${detail}
                <div style="font-size:0.73rem;color:var(--text-muted);margin-top:2px">Fires: ${t.fire_count || 0} &middot; Last fired: ${lastFired}${created ? ` &middot; Created: ${created}` : ''}</div>
              </div>
            </div>
            <div style="display:flex;gap:4px;flex-shrink:0">
              ${t.type === 'file_watch' && t.enabled && !t.watching ? `<button class="btn btn-primary btn-sm" onclick="window.Triggers.restart('${t.id}')">Start</button>` : ''}
              <button class="btn btn-ghost btn-sm" onclick="window.Triggers.toggle('${t.id}', ${!t.enabled})">${t.enabled ? 'Disable' : 'Enable'}</button>
              <button class="btn btn-ghost btn-sm" onclick="window.Triggers.del('${t.id}')" style="color:var(--danger)" title="Delete">&times;</button>
            </div>
          </div>
          <div style="padding:8px 14px;font-size:0.8rem;color:var(--text-secondary);border-top:1px solid var(--border)">${escapeHtml(t.prompt.length > 200 ? t.prompt.slice(0, 200) + '...' : t.prompt)}</div>
        </div>`;
      }
    }

    // Add trigger form
    html += `<div id="trigger-add-form" style="display:none;margin-top:16px">
      <div class="settings-section-title">New Trigger</div>
      <div style="display:flex;flex-direction:column;gap:10px">
        <div>
          <label style="font-size:0.75rem;color:var(--text-muted);display:block;margin-bottom:4px">Type</label>
          <select id="trigger-type" onchange="window.Triggers.typeChanged()" style="width:100%;padding:7px 10px;background:var(--surface);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:0.85rem">
            <option value="file_watch">File Watcher</option>
            <option value="webhook">Webhook</option>
          </select>
        </div>
        <div>
          <label style="font-size:0.75rem;color:var(--text-muted);display:block;margin-bottom:4px">Name (optional)</label>
          <input id="trigger-name" type="text" placeholder="My trigger" style="width:100%;padding:7px 10px;background:var(--surface);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:0.85rem">
        </div>
        <div id="trigger-path-group">
          <label style="font-size:0.75rem;color:var(--text-muted);display:block;margin-bottom:4px">Watch path</label>
          <input id="trigger-path" type="text" placeholder="/Users/you/Documents" style="width:100%;padding:7px 10px;background:var(--surface);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:0.85rem">
        </div>
        <div id="trigger-glob-group">
          <label style="font-size:0.75rem;color:var(--text-muted);display:block;margin-bottom:4px">Glob filter (optional)</label>
          <input id="trigger-glob" type="text" placeholder="*.pdf" style="width:100%;padding:7px 10px;background:var(--surface);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:0.85rem">
        </div>
        <div id="trigger-secret-group" style="display:none">
          <label style="font-size:0.75rem;color:var(--text-muted);display:block;margin-bottom:4px">Webhook secret (optional)</label>
          <input id="trigger-secret" type="text" placeholder="shared-secret" style="width:100%;padding:7px 10px;background:var(--surface);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:0.85rem">
        </div>
        <div>
          <label style="font-size:0.75rem;color:var(--text-muted);display:block;margin-bottom:4px">Prompt (executed when triggered)</label>
          <textarea id="trigger-prompt" rows="3" placeholder="Summarize the new files in {path}" style="width:100%;padding:7px 10px;background:var(--surface);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:0.85rem;font-family:inherit;resize:vertical"></textarea>
          <div style="font-size:0.7rem;color:var(--text-muted);margin-top:2px">Variables: <code>{file}</code>, <code>{event}</code>, <code>{path}</code> (file watch) &middot; <code>{payload}</code>, <code>{headers}</code> (webhook)</div>
        </div>
        <div style="display:flex;gap:8px">
          <button class="btn btn-primary btn-sm" onclick="window.Triggers.save()">Create Trigger</button>
          <button class="btn btn-ghost btn-sm" onclick="window.Triggers.hideAdd()">Cancel</button>
        </div>
      </div>
    </div>`;

    html += '</div>';
    container.innerHTML = html;
  }

  // ── Button binding ──
  const btn = document.getElementById('triggers-btn');
  if (btn) btn.addEventListener('click', openTriggersPanel);

  // ── Public API ──
  window.Triggers = {
    showAdd() {
      const form = document.getElementById('trigger-add-form');
      if (form) form.style.display = 'block';
    },
    hideAdd() {
      const form = document.getElementById('trigger-add-form');
      if (form) form.style.display = 'none';
    },
    typeChanged() {
      const type = document.getElementById('trigger-type')?.value;
      const pathGroup = document.getElementById('trigger-path-group');
      const globGroup = document.getElementById('trigger-glob-group');
      const secretGroup = document.getElementById('trigger-secret-group');
      if (type === 'webhook') {
        if (pathGroup) pathGroup.style.display = 'none';
        if (globGroup) globGroup.style.display = 'none';
        if (secretGroup) secretGroup.style.display = 'block';
      } else {
        if (pathGroup) pathGroup.style.display = 'block';
        if (globGroup) globGroup.style.display = 'block';
        if (secretGroup) secretGroup.style.display = 'none';
      }
    },
    async save() {
      const type = document.getElementById('trigger-type')?.value;
      const name = document.getElementById('trigger-name')?.value.trim();
      const prompt = document.getElementById('trigger-prompt')?.value.trim();
      if (!prompt) return alert('Prompt is required.');
      const body = { type, prompt };
      if (name) body.name = name;
      if (type === 'file_watch') {
        const path = document.getElementById('trigger-path')?.value.trim();
        if (!path) return alert('Watch path is required for file watchers.');
        body.path = path;
        const glob = document.getElementById('trigger-glob')?.value.trim();
        if (glob) body.glob = glob;
      }
      if (type === 'webhook') {
        const secret = document.getElementById('trigger-secret')?.value.trim();
        if (secret) body.secret = secret;
      }
      try {
        const res = await fetch('/api/triggers', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(body),
        });
        if (!res.ok) {
          const err = await res.json();
          return alert(err.error || 'Failed to create trigger');
        }
        openTriggersPanel();
      } catch (e) { alert('Error: ' + e.message); }
    },
    async toggle(id, enabled) {
      await fetch(`/api/triggers/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ enabled }),
      });
      openTriggersPanel();
    },
    async del(id) {
      if (!confirm('Delete this trigger?')) return;
      await fetch(`/api/triggers/${id}`, { method: 'DELETE' });
      openTriggersPanel();
    },
    async restart(id) {
      try {
        const res = await fetch(`/api/triggers/${id}/restart`, { method: 'POST' });
        const data = await res.json();
        if (data.error) alert(data.error);
      } catch {}
      openTriggersPanel();
    },
  };
})();
