"use client";
import { useCallback, useMemo, useState } from 'react';

const MODEL_GROUPS = [
  { key: 'claude-code', label: 'Local CLI' },
  { key: 'codex',       label: 'Local CLI' },
  { key: 'ollama',      label: 'Ollama' },
  { key: 'anthropic',   label: 'Anthropic' },
];
const groupOrder = ['claude-code', 'codex', 'ollama', 'anthropic'];

export function useModelPicker() {
  const [selectedModel, setSelectedModel] = useState('');
  const [models, setModels] = useState([]);
  const [modelOpen, setModelOpen] = useState(false);

  const grouped = useMemo(() => groupOrder.reduce((acc, engine) => {
    const items = models.filter(m => m.engine === engine);
    if (items.length) acc.push({ engine, label: MODEL_GROUPS.find(g => g.key === engine)?.label ?? engine, items });
    return acc;
  }, []), [models]);

  const pickModel = useCallback(async (id) => {
    setSelectedModel(id);
    setModelOpen(false);
    await fetch('/api/config', {
      method: 'PUT',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ model: id }),
    });
  }, [setSelectedModel, setModelOpen]);

  return {
    selectedModel,
    setSelectedModel,
    models,
    setModels,
    modelOpen,
    setModelOpen,
    grouped,
    pickModel,
  };
}
