'use client';
import { useState } from 'react';

export function EnginePingButton({ engineId, model }) {
  const [state, setState] = useState(null); // null | 'loading' | { ok, ms, output, error }

  async function ping() {
    setState('loading');
    try {
      const res = await fetch('/api/runs/engine-ping', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ engine: engineId, model: model || '' }),
      });
      const data = await res.json();
      setState(data);
    } catch (err) {
      setState({ ok: false, error: err.message });
    }
  }

  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
      <button
        onClick={ping}
        disabled={state === 'loading'}
        style={{
          fontSize: 11, padding: '2px 10px', borderRadius: 6, border: '1px solid rgba(17,19,24,.14)',
          background: 'rgba(17,19,24,.05)', cursor: state === 'loading' ? 'wait' : 'pointer',
          fontFamily: 'ui-monospace,monospace', color: '#374151',
        }}
      >
        {state === 'loading' ? 'pinging…' : 'ping'}
      </button>
      {state && state !== 'loading' && (
        <small style={{ fontFamily: 'ui-monospace,monospace', fontSize: 11, color: state.ok ? '#16a34a' : '#dc2626' }}>
          {state.ok ? `ok · ${state.ms}ms · "${state.output}"` : `fail · ${state.error}`}
        </small>
      )}
    </span>
  );
}
