// Agent Detail + Create Modal components

function CreateAgentModal({ theme, machines, onClose, onCreated }) {
  const t = theme;
  const [name, setName] = useState('');
  const [machineId, setMachineId] = useState(machines.find(m => m.status === 'online')?.id || machines[0]?.id || '');
  const [prompt, setPrompt] = useState('');
  const [scheduleType, setScheduleType] = useState('manual');
  const [interval, setInterval_] = useState(300);
  const [cron, setCron] = useState('0 * * * *');
  const [error, setError] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async () => {
    if (!name.trim()) { setError('Name is required'); return; }
    if (!machineId) { setError('Select a machine'); return; }
    if (!prompt.trim()) { setError('Prompt/instructions required'); return; }
    setSubmitting(true); setError('');
    try {
      const res = await fetch('/api/agents', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: name.trim(), machine_id: machineId, prompt: prompt.trim(),
          schedule_type: scheduleType,
          schedule_interval: scheduleType === 'interval' ? parseInt(interval) : null,
          schedule_cron: scheduleType === 'cron' ? cron : null,
        }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.error || 'Failed to create'); setSubmitting(false); return; }
      onCreated();
    } catch (e) { setError(e.message); setSubmitting(false); }
  };

  const inputStyle = { width: "100%", padding: "9px 12px", background: t.panel2, border: `1px solid ${t.line2}`, borderRadius: t.radius, color: t.fg, fontFamily: t.fontSans, fontSize: 13, outline: "none", boxSizing: "border-box" };
  const labelStyle = { fontSize: 11, fontFamily: t.fontMono, color: t.fg2, marginBottom: 4, display: "block", textTransform: "uppercase", letterSpacing: 0.6 };

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.5)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 200 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 520, maxWidth: "90vw", maxHeight: "85vh", overflowY: "auto", background: t.panel, border: `1px solid ${t.line2}`, borderRadius: t.radius + 4, padding: 24, fontFamily: t.fontSans, color: t.fg, animation: "ac-fade 0.2s" }}>
        <div style={{ fontFamily: t.fontDisplay, fontWeight: t.weightHeading, fontSize: 18, marginBottom: 20 }}>Create Autonomous Agent</div>

        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div>
            <label style={labelStyle}>Name</label>
            <input value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Trading Bot, Inbox Monitor" style={inputStyle} />
          </div>

          <div>
            <label style={labelStyle}>Machine</label>
            <select value={machineId} onChange={e => setMachineId(e.target.value)} style={{ ...inputStyle, cursor: "pointer" }}>
              {machines.map(m => <option key={m.id} value={m.id}>{m.name} ({m.status})</option>)}
            </select>
          </div>

          <div>
            <label style={labelStyle}>Prompt / Instructions</label>
            <textarea value={prompt} onChange={e => setPrompt(e.target.value)} rows={6}
              placeholder="Describe what this agent should do. Be specific about the task, constraints, and expected output."
              style={{ ...inputStyle, fontFamily: t.fontMono, fontSize: 12, resize: "vertical", lineHeight: 1.5 }} />
            <div style={{ fontSize: 10, color: t.fg3, marginTop: 4 }}>{prompt.length}/10000 characters</div>
          </div>

          <div>
            <label style={labelStyle}>Schedule</label>
            <div style={{ display: "flex", gap: 8 }}>
              {['manual', 'interval', 'cron'].map(st => (
                <button key={st} onClick={() => setScheduleType(st)} style={{
                  padding: "6px 12px", background: scheduleType === st ? t.accent + '20' : "transparent",
                  border: `1px solid ${scheduleType === st ? t.accent : t.line2}`, borderRadius: t.radius,
                  color: scheduleType === st ? t.accent : t.fg2, fontSize: 11, fontFamily: t.fontMono, cursor: "pointer", textTransform: "capitalize",
                }}>{st}</button>
              ))}
            </div>
            {scheduleType === 'interval' && (
              <div style={{ marginTop: 8, display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ fontSize: 11, color: t.fg2 }}>Run every</span>
                <input type="number" min="60" value={interval} onChange={e => setInterval_(e.target.value)}
                  style={{ ...inputStyle, width: 80 }} />
                <span style={{ fontSize: 11, color: t.fg2 }}>seconds (min 60)</span>
              </div>
            )}
            {scheduleType === 'cron' && (
              <div style={{ marginTop: 8 }}>
                <input value={cron} onChange={e => setCron(e.target.value)} placeholder="0 * * * *" style={inputStyle} />
                <div style={{ fontSize: 10, color: t.fg3, marginTop: 4 }}>Standard cron expression (coming soon - for now use manual or interval)</div>
              </div>
            )}
          </div>
        </div>

        {error && <div style={{ marginTop: 12, padding: "8px 12px", background: `${t.err}15`, border: `1px solid ${t.err}40`, borderRadius: t.radius, fontSize: 12, color: t.err }}>{error}</div>}

        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 20 }}>
          <button onClick={onClose} style={{ padding: "8px 16px", background: "transparent", border: `1px solid ${t.line2}`, borderRadius: t.radius, color: t.fg2, cursor: "pointer", fontSize: 13 }}>Cancel</button>
          <button onClick={handleSubmit} disabled={submitting} style={{ padding: "8px 16px", background: t.accent, color: t.bg, border: "none", borderRadius: t.radius, cursor: "pointer", fontSize: 13, fontWeight: 600, opacity: submitting ? 0.6 : 1 }}>
            {submitting ? 'Creating...' : 'Create Agent'}
          </button>
        </div>
      </div>
    </div>
  );
}

function AgentDetail({ theme, agentId, onBack, onRun, onStop, onDelete }) {
  const t = theme;
  const store = useStore();
  const [agent, setAgent] = useState(null);
  const [runs, setRuns] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showRun, setShowRun] = useState(null);
  const [confirmDelete, setConfirmDelete] = useState(false);
  const [editing, setEditing] = useState(false);
  const [editPrompt, setEditPrompt] = useState('');

  const fetchAgent = useCallback(() => {
    fetch(`/api/agents/${agentId}`, { credentials: 'include' })
      .then(r => r.json())
      .then(data => { setAgent(data); setRuns(data.runs || []); setLoading(false); })
      .catch(() => setLoading(false));
  }, [agentId]);

  useEffect(() => { fetchAgent(); const iv = setInterval(fetchAgent, 5000); return () => clearInterval(iv); }, [fetchAgent]);

  // Auto-expand the running run
  useEffect(() => {
    if (!showRun && runs.length > 0) {
      const running = runs.find(r => r.status === 'running');
      if (running) setShowRun(running.id);
    }
  }, [runs]);

  const handleSavePrompt = async () => {
    await fetch(`/api/agents/${agentId}`, {
      method: 'PATCH', credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ prompt: editPrompt }),
    });
    setEditing(false); fetchAgent();
  };

  if (loading) return <div style={{ flex: 1, background: t.chatBg, padding: 32, color: t.fg3, fontFamily: t.fontSans }}>Loading...</div>;
  if (!agent) return <div style={{ flex: 1, background: t.chatBg, padding: 32, color: t.err, fontFamily: t.fontSans }}>Agent not found</div>;

  const statusColor = agent.status === 'running' ? t.accent : agent.status === 'error' ? t.err : t.fg3;

  return (
    <main style={{ flex: 1, background: t.chatBg, color: t.fg, fontFamily: t.fontSans, overflowY: "auto", minWidth: 0 }}>
      {/* Header */}
      <div style={{ padding: "20px 32px", borderBottom: `1px solid ${t.line}`, background: t.bg2, display: "flex", alignItems: "center", gap: 12 }}>
        <button onClick={onBack} style={{ ...iconBtn(t), width: 28, height: 28 }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
        </button>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: t.fontDisplay, fontWeight: t.weightHeading, fontSize: 18 }}>{agent.name}</div>
          <div style={{ fontSize: 11, fontFamily: t.fontMono, color: t.fg3, display: "flex", alignItems: "center", gap: 8 }}>
            <span>{agent.machine_name}</span><span style={{ opacity: 0.4 }}>-</span>
            <span style={{ color: statusColor }}>{agent.status}</span><span style={{ opacity: 0.4 }}>-</span>
            <span>{agent.total_runs || 0} runs total</span>
          </div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          {agent.status === 'running' ? (
            <button onClick={() => onStop(agentId)} style={{ padding: "6px 14px", background: `${t.err}18`, border: `1px solid ${t.err}`, borderRadius: t.radius, color: t.err, fontSize: 12, fontFamily: t.fontMono, cursor: "pointer" }}>Stop</button>
          ) : (
            <button onClick={() => onRun(agentId)} style={{ padding: "6px 14px", background: t.accent, border: "none", borderRadius: t.radius, color: t.bg, fontSize: 12, fontFamily: t.fontMono, cursor: "pointer", fontWeight: 600 }}
              disabled={agent.machine_status !== 'online'}>Run Now</button>
          )}
          <button onClick={() => setConfirmDelete(true)} style={{ padding: "6px 14px", background: "transparent", border: `1px solid ${t.err}40`, borderRadius: t.radius, color: t.err, fontSize: 12, fontFamily: t.fontMono, cursor: "pointer" }}>Delete</button>
        </div>
      </div>

      <div style={{ padding: "24px 32px", display: "flex", flexDirection: "column", gap: 24 }}>
        {/* Config */}
        <section>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
            <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontWeight: t.weightHeading, fontSize: 14 }}>Prompt</h3>
            <button onClick={() => { setEditing(!editing); setEditPrompt(agent.prompt); }} style={{ fontSize: 11, color: t.accent, background: "transparent", border: "none", cursor: "pointer", fontFamily: t.fontMono }}>
              {editing ? 'Cancel' : 'Edit'}
            </button>
          </div>
          {editing ? (
            <div>
              <textarea value={editPrompt} onChange={e => setEditPrompt(e.target.value)} rows={6}
                style={{ width: "100%", padding: 12, background: t.panel2, border: `1px solid ${t.line2}`, borderRadius: t.radius, color: t.fg, fontFamily: t.fontMono, fontSize: 12, resize: "vertical", lineHeight: 1.5, boxSizing: "border-box" }} />
              <button onClick={handleSavePrompt} style={{ marginTop: 8, padding: "6px 14px", background: t.accent, color: t.bg, border: "none", borderRadius: t.radius, fontSize: 12, fontWeight: 600, cursor: "pointer" }}>Save</button>
            </div>
          ) : (
            <div style={{ padding: 12, background: t.panel, border: `1px solid ${t.line}`, borderRadius: t.radius, fontFamily: t.fontMono, fontSize: 12, color: t.fg2, lineHeight: 1.6, whiteSpace: "pre-wrap", wordBreak: "break-word" }}>
              {agent.prompt}
            </div>
          )}
        </section>

        {/* Info strip */}
        <section style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 1, background: t.line, borderRadius: t.radius, overflow: "hidden" }}>
          <InfoCell t={t} label="Schedule" value={agent.schedule_type === 'interval' ? `Every ${formatInterval(agent.schedule_interval)}` : agent.schedule_type === 'cron' ? agent.schedule_cron : 'Manual'} />
          <InfoCell t={t} label="Last Run" value={agent.last_run_at ? timeAgo(agent.last_run_at) : 'Never'} />
          <InfoCell t={t} label="Total Runs" value={String(agent.total_runs || 0)} />
          <InfoCell t={t} label="Enabled" value={agent.enabled ? 'Yes' : 'No'} accent={agent.enabled} />
        </section>

        {/* Runs */}
        <section>
          <h3 style={{ margin: "0 0 12px", fontFamily: t.fontDisplay, fontWeight: t.weightHeading, fontSize: 14 }}>Run History</h3>
          {runs.length === 0 && <div style={{ fontSize: 12, color: t.fg3, fontStyle: "italic" }}>No runs yet. Click "Run Now" to start.</div>}
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {runs.map(run => (
              <RunRow key={run.id} run={run} theme={t} expanded={showRun === run.id}
                onToggle={() => setShowRun(showRun === run.id ? null : run.id)}
                liveEvents={store.agentRunStreams[run.id] || []} />
            ))}
          </div>
        </section>
      </div>

      {confirmDelete && (
        <div onClick={() => setConfirmDelete(false)} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.5)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 200 }}>
          <div onClick={e => e.stopPropagation()} style={{ width: 360, background: t.panel, border: `1px solid ${t.line2}`, borderRadius: t.radius + 4, padding: 24, animation: "ac-fade 0.15s" }}>
            <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 12 }}>Delete "{agent.name}"?</div>
            <div style={{ fontSize: 13, color: t.fg2, marginBottom: 20 }}>This will permanently delete this agent and all its run history.</div>
            <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
              <button onClick={() => setConfirmDelete(false)} style={{ padding: "8px 16px", background: "transparent", border: `1px solid ${t.line2}`, borderRadius: t.radius, color: t.fg2, cursor: "pointer", fontSize: 13 }}>Cancel</button>
              <button onClick={() => { onDelete(agentId); setConfirmDelete(false); }} style={{ padding: "8px 16px", background: t.err, color: "#fff", border: "none", borderRadius: t.radius, cursor: "pointer", fontSize: 13, fontWeight: 600 }}>Delete</button>
            </div>
          </div>
        </div>
      )}
    </main>
  );
}

function InfoCell({ t, label, value, accent }) {
  return (
    <div style={{ padding: "12px 16px", background: t.panel }}>
      <div style={{ fontSize: 10, fontFamily: t.fontMono, color: t.fg3, letterSpacing: 0.6, textTransform: "uppercase", marginBottom: 4 }}>{label}</div>
      <div style={{ fontSize: 13, fontWeight: 500, color: accent ? t.accent : t.fg }}>{value}</div>
    </div>
  );
}

function RunRow({ run, theme, expanded, onToggle, liveEvents }) {
  const t = theme;
  const liveRef = useRef(null);
  const statusColor = run.status === 'completed' ? t.accent : run.status === 'error' ? t.err : run.status === 'running' ? t.warn : t.fg3;
  const duration = run.started_at && run.finished_at ? Math.round((new Date(run.finished_at) - new Date(run.started_at)) / 1000) : null;
  const isRunning = run.status === 'running';
  const events = liveEvents || [];

  // Auto-scroll live output
  useEffect(() => {
    if (liveRef.current && isRunning) liveRef.current.scrollTop = liveRef.current.scrollHeight;
  }, [events.length, isRunning]);

  return (
    <div style={{ background: t.panel, border: `1px solid ${isRunning ? t.accent + '60' : t.line}`, borderRadius: t.radius, overflow: "hidden" }}>
      <button onClick={onToggle} style={{
        width: "100%", display: "flex", alignItems: "center", gap: 10, padding: "10px 14px",
        background: "transparent", border: "none", cursor: "pointer", color: t.fg, fontFamily: t.fontSans, textAlign: "left",
      }}>
        <StatusDot status={run.status === 'completed' ? 'online' : run.status === 'running' ? 'running' : 'error'} theme={t} />
        <span style={{ fontSize: 12, fontWeight: 500, flex: 1 }}>{run.status}</span>
        {run.tokens_used > 0 && <span style={{ fontSize: 10, fontFamily: t.fontMono, color: t.fg3 }}>{run.tokens_used} tok</span>}
        {run.cost_usd > 0 && <span style={{ fontSize: 10, fontFamily: t.fontMono, color: t.fg3 }}>${run.cost_usd.toFixed(4)}</span>}
        {duration !== null && <span style={{ fontSize: 10, fontFamily: t.fontMono, color: t.fg3 }}>{duration}s</span>}
        <span style={{ fontSize: 10, fontFamily: t.fontMono, color: t.fg3 }}>{timeAgo(run.started_at)}</span>
        <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"
          style={{ transform: expanded ? "rotate(180deg)" : "rotate(0)", transition: "transform 0.2s" }}>
          <path d="M6 9l6 6 6-6"/>
        </svg>
      </button>
      {expanded && (
        <div style={{ borderTop: `1px solid ${t.line}`, padding: 16 }}>
          {/* Live streaming output for running agents */}
          {isRunning && events.length > 0 && (
            <div ref={liveRef} style={{ maxHeight: 500, overflowY: "auto", display: "flex", flexDirection: "column", gap: 6, marginBottom: 10 }}>
              {events.map((ev, i) => <LiveEventBlock key={i} event={ev} theme={t} />)}
            </div>
          )}
          {isRunning && events.length === 0 && (
            <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: t.fg3 }}>
              <span className="ac-pulse" style={{ width: 6, height: 6, borderRadius: 3, background: t.accent }} />
              Agent is running, waiting for output...
            </div>
          )}
          {!isRunning && run.output && (
            <div style={{ marginBottom: run.error ? 10 : 0 }}>
              <div style={{ fontSize: 11, fontFamily: t.fontMono, color: t.fg3, marginBottom: 6, textTransform: "uppercase", fontWeight: 600 }}>Output</div>
              <pre style={{ margin: 0, padding: 14, background: t.panel2, borderRadius: t.radius, fontSize: 13, fontFamily: t.fontMono, color: t.fg2, whiteSpace: "pre-wrap", wordBreak: "break-word", maxHeight: 500, overflowY: "auto", lineHeight: 1.6, minHeight: 40 }}>{run.output}</pre>
            </div>
          )}
          {run.error && (
            <div>
              <div style={{ fontSize: 11, fontFamily: t.fontMono, color: t.err, marginBottom: 6, textTransform: "uppercase", fontWeight: 600 }}>Error</div>
              <pre style={{ margin: 0, padding: 14, background: `${t.err}10`, borderRadius: t.radius, fontSize: 13, fontFamily: t.fontMono, color: t.err, whiteSpace: "pre-wrap", wordBreak: "break-word", maxHeight: 400, overflowY: "auto", lineHeight: 1.6, minHeight: 40 }}>{run.error}</pre>
            </div>
          )}
          {!isRunning && !run.output && !run.error && (
            <div style={{ fontSize: 12, color: t.fg3, fontStyle: "italic" }}>No output recorded</div>
          )}
        </div>
      )}
    </div>
  );
}

function LiveEventBlock({ event, theme }) {
  const t = theme;
  const ev = event;
  if (ev.event_type === 'text') {
    return (
      <div style={{ padding: "10px 14px", background: t.panel2, borderRadius: t.radius, fontSize: 13, fontFamily: t.fontMono, color: t.fg, whiteSpace: "pre-wrap", wordBreak: "break-word", lineHeight: 1.6 }}>
        {ev.text}
      </div>
    );
  }
  if (ev.event_type === 'tool_use') {
    const inputStr = typeof ev.input === 'string' ? ev.input : (ev.input ? JSON.stringify(ev.input, null, 2) : '');
    const short = inputStr.length > 200 ? inputStr.substring(0, 200) + '...' : inputStr;
    return (
      <div style={{ padding: "8px 14px", background: `${t.accent}10`, border: `1px solid ${t.accent}25`, borderRadius: t.radius, fontSize: 12, fontFamily: t.fontMono, color: t.accent, display: "flex", alignItems: "flex-start", gap: 8 }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ marginTop: 2, flexShrink: 0 }}><path d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z"/></svg>
        <span style={{ lineHeight: 1.5 }}>{ev.tool}{short ? ': ' + short : ''}</span>
      </div>
    );
  }
  if (ev.event_type === 'tool_result') {
    return (
      <div style={{ padding: "10px 14px", background: ev.is_error ? `${t.err}10` : t.panel2, borderRadius: t.radius, fontSize: 12, fontFamily: t.fontMono, color: ev.is_error ? t.err : t.fg3, whiteSpace: "pre-wrap", wordBreak: "break-word", maxHeight: 200, overflowY: "auto", lineHeight: 1.5 }}>
        {ev.output || '(no output)'}
      </div>
    );
  }
  return null;
}

window.CreateAgentModal = CreateAgentModal;
window.AgentDetail = AgentDetail;
