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

export default function EngineModelPicker({ engines, initialEngine = 'claude-code', initialModel = '' }) {
  const [engine, setEngine] = useState(initialEngine);
  const current = engines.find(e => e.id === engine);
  const models = current?.models || [];
  const initialIsValid = models.some(m => m.name === initialModel);
  const defaultModel = initialIsValid ? initialModel : (current?.default_model || '');

  return (
    <>
      <select name="engine" value={engine} onChange={(e) => setEngine(e.target.value)} aria-label="Engine">
        {engines.map(e => (
          <option key={e.id} value={e.id}>{e.label}{e.available ? '' : ' — unavailable'}</option>
        ))}
      </select>
      {models.length > 0 ? (
        <select key={engine} name="model" defaultValue={defaultModel} aria-label="Model">
          {models.map(m => <option key={m.name} value={m.name}>{m.name}</option>)}
        </select>
      ) : (
        <input
          key={engine}
          name="model"
          defaultValue={initialIsValid ? initialModel : ''}
          placeholder="model id (optional)"
          aria-label="Model"
        />
      )}
    </>
  );
}
