"use client";
import { SpinnerIcon, CheckIcon, StepXIcon, ElapsedTime } from './icons';
import { toolStepSublabel } from './tool-steps';
import { useDashboard } from './dashboard-context';

export default function RuntimePopover() {
  const { mainAgent, runtimeActions, runtimeSignalCount, pendingApprovals, heartbeatTasks, localProcesses, localActions } = useDashboard();

  const runtimeOpen = runtimeActions.runtimeOpen;
  const setRuntimeOpen = runtimeActions.setRuntimeOpen;
  const busy = mainAgent.busy;
  const hasBgActivity = mainAgent.hasBgActivity;
  const bgAgentList = mainAgent.bgAgentList;
  const busyStartTime = mainAgent.busyStartTime;
  const agentPhase = mainAgent.agentPhase;
  const liveSteps = mainAgent.liveSteps;
  const decideGenericApproval = runtimeActions.decideGenericApproval;
  const approvalBusyId = runtimeActions.approvalBusyId;
  const ensureOpsAgentAction = runtimeActions.ensureOpsAgentAction;
  const processHeartbeatOnceAction = runtimeActions.processHeartbeatOnceAction;
  const runtimeActionBusy = runtimeActions.runtimeActionBusy;

  return (
    <div className="runtime-menu-wrap">
      <button
        className={'runtime-menu-btn' + (runtimeOpen ? ' on' : '') + ((busy || hasBgActivity) ? ' runtime-menu-btn--busy' : '')}
        onClick={() => setRuntimeOpen(open => !open)}
        title={
          busy
            ? 'Main agent is working — click to see live activity'
            : hasBgActivity
              ? `${bgAgentList.filter(a => a.status === 'running').length} background agent(s) working`
              : 'Runtime activity'
        }
        aria-label="Runtime activity"
        aria-expanded={runtimeOpen}
      >
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M4 12h4l2-7 4 14 2-7h4"/>
        </svg>
        {(busy || hasBgActivity) && <span className="runtime-busy-dot" aria-hidden="true" />}
        {!busy && !hasBgActivity && runtimeSignalCount > 0 && <span>{runtimeSignalCount}</span>}
      </button>
      {runtimeOpen && (
        <div className="runtime-popover">
          <div className="runtime-popover-head">
            <b>Operator Command Center</b>
            <small>Approvals, running work, failed runs, and task queues</small>
            <div className="runtime-quick-links" aria-label="Operator quick links">
              <a href="/approvals">Approvals</a>
              <a href="/tasks">Tasks</a>
              <a href="/activity">Activity</a>
              <a href="/runtime">Runtime</a>
            </div>
          </div>
          {/* Live agent — always visible when busy */}
          {busy && (
            <div className="runtime-live-section">
              <div className="runtime-live-header">
                <div className="runtime-live-title-row">
                  <span className="runtime-section-title">Main Agent</span>
                  <span className="runtime-live-phase">
                    {agentPhase === 'thinking' && 'thinking'}
                    {agentPhase === 'responding' && 'responding'}
                    {agentPhase === 'tool' && 'using tools'}
                    {agentPhase === 'synthesis' && 'synthesizing'}
                  </span>
                </div>
                <div className="runtime-live-meta">
                  {busyStartTime && (
                    <span className="runtime-live-elapsed">
                      <ElapsedTime startTime={busyStartTime} />
                    </span>
                  )}
                  <span className="runtime-live-badge">
                    <span className="runtime-live-badge-dot" aria-hidden="true" />
                    Live
                  </span>
                </div>
              </div>
              {liveSteps.length > 0 ? (
                <div className="runtime-live-steps">
                  {liveSteps.map(step => (
                    <div key={step.id} className={`runtime-live-step runtime-live-step--${step.status}`}>
                      <span className="runtime-live-step-icon" aria-hidden="true">
                        {step.status === 'running' && <SpinnerIcon />}
                        {step.status === 'done' && <CheckIcon />}
                        {step.status === 'error' && <StepXIcon />}
                      </span>
                      <code className="runtime-live-step-name">{step.name.replace(/_/g, ' ')}</code>
                      {toolStepSublabel(step.name, step.input) && (
                        <span className="runtime-live-step-sub">{toolStepSublabel(step.name, step.input)}</span>
                      )}
                    </div>
                  ))}
                </div>
              ) : (
                <div className="runtime-live-thinking">
                  <span className="runtime-live-thinking-icon"><SpinnerIcon /></span>
                  <span>
                    {agentPhase === 'thinking' && 'Waiting for first response…'}
                    {agentPhase === 'responding' && 'Streaming response…'}
                    {agentPhase === 'synthesis' && 'Synthesizing results…'}
                    {agentPhase === 'idle' && 'Processing…'}
                  </span>
                </div>
              )}
            </div>
          )}

          {/* Background agents — visible when sub-agents are doing work */}
          {bgAgentList.length > 0 && (
            <div className="runtime-section">
              <span className="runtime-section-title">
                Background agents
                {hasBgActivity && <span className="runtime-live-badge" style={{ marginLeft: 8 }}>
                  <span className="runtime-live-badge-dot" aria-hidden="true" />
                  Live
                </span>}
              </span>
              <div className="runtime-live-steps">
                {bgAgentList.map(a => (
                  <div key={a.agent_id} className={`runtime-live-step runtime-live-step--${a.status === 'running' ? 'running' : a.status === 'failed' ? 'error' : 'done'}`}>
                    <span className="runtime-live-step-icon" aria-hidden="true">
                      {a.status === 'running' && <SpinnerIcon />}
                      {a.status === 'complete' && <CheckIcon />}
                      {a.status === 'failed' && <StepXIcon />}
                    </span>
                    <code className="runtime-live-step-name">{a.agent_name}</code>
                    <span className="runtime-live-step-sub">
                      {a.current_tool
                        ? `${a.current_tool.replace(/_/g, ' ')}${toolStepSublabel(a.current_tool, a.current_input) ? ` ${toolStepSublabel(a.current_tool, a.current_input)}` : ''}`
                        : a.status === 'running'
                          ? (a.triggered_by ? `${a.triggered_by} tick` : 'starting…')
                          : a.status === 'complete'
                            ? 'done'
                            : 'failed'}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Queues — compact stats */}
          <div className="runtime-compact-stats">
            {[
              ['Approvals', pendingApprovals.length],
              ['Heartbeat', heartbeatTasks.length],
              ['Processes', localProcesses.length],
              ['Audit', localActions.length],
            ].map(([label, value]) => (
              <div key={label} className={'runtime-compact-stat' + (value > 0 ? ' has-value' : '')}>
                <b>{value}</b>
                <span>{label}</span>
              </div>
            ))}
          </div>

          {/* Approvals — only when pending */}
          {pendingApprovals.length > 0 && (
            <div className="runtime-section">
              <span className="runtime-section-title">Pending approvals</span>
              {pendingApprovals.slice(0, 3).map(item => (
                <div key={item.id} className="runtime-approval">
                  <span>{item.summary}</span>
                  <div>
                    <button onClick={() => decideGenericApproval(item.id, 'approved')} disabled={approvalBusyId === item.id}>Approve</button>
                    <button className="secondary" onClick={() => decideGenericApproval(item.id, 'denied')} disabled={approvalBusyId === item.id}>Deny</button>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Recent activity — only when non-empty */}
          {(heartbeatTasks.length > 0 || localProcesses.length > 0 || localActions.length > 0) && (
            <div className="runtime-section">
              <span className="runtime-section-title">Recent activity</span>
              {heartbeatTasks.slice(0, 2).map(item => (
                <div key={item.id} className="runtime-row"><span>{item.type}</span><b>{item.status}</b></div>
              ))}
              {localProcesses.slice(0, 2).map(item => (
                <div key={item.id} className="runtime-row"><span>{item.command}</span><b>{item.status}</b></div>
              ))}
              {localActions.slice(0, 3).map(item => (
                <div key={item.id} className="runtime-row"><span>{item.summary || item.type}</span><b>{item.status}</b></div>
              ))}
            </div>
          )}

          {/* Empty state — only when idle */}
          {!busy && runtimeSignalCount === 0 && bgAgentList.length === 0 && (
            <div className="runtime-empty">No active tasks right now.</div>
          )}

          {/* Developer tools — compact footer */}
          <div className="runtime-dev-tools">
            <span className="runtime-section-title">System tools</span>
            <div className="runtime-dev-row">
              <button onClick={ensureOpsAgentAction} disabled={runtimeActionBusy === 'ops'} className="runtime-dev-btn">
                {runtimeActionBusy === 'ops' ? 'Creating…' : 'Caretaker'}
              </button>
              <button onClick={processHeartbeatOnceAction} disabled={runtimeActionBusy === 'worker'} className="runtime-dev-btn">
                {runtimeActionBusy === 'worker' ? 'Processing…' : 'Heartbeat once'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
