// ToolCard — individual tool card with model selector, capabilities, environment info.

const CATEGORY_LABELS = {
  ide: "IDE",
  agent_cli: "CLI Agent",
  browser: "Browser",
  custom: "Custom",
  human: "Human",
};

const CATEGORY_COLORS = {
  ide: "bg-blue-100 text-blue-700",
  agent_cli: "bg-purple-100 text-purple-700",
  browser: "bg-amber-100 text-amber-700",
  custom: "bg-gray-100 text-gray-600",
  human: "bg-gray-100 text-gray-600",
};

// Direct model IDs from the registry — no aliases
const REGISTRY_MODELS = [
  { id: "google/gemini-3-flash-preview", label: "Gemini 3 Flash Preview ($0.5/$3)" },
  { id: "anthropic/haiku-4.5", label: "Haiku 4.5 ($1/$5)" },
  { id: "anthropic/opus-4.6", label: "Opus 4.6 ($5/$25)" },
  { id: "openai/gpt-4.1", label: "GPT-4.1 ($2/$8)" },
  { id: "openai/gpt-5.4", label: "GPT-5.4 ($2.5/$15)" },
  { id: "google/gemini-2.5-pro", label: "Gemini 2.5 Pro (free)" },
  { id: "google/gemini-2.5-flash", label: "Gemini 2.5 Flash (free)" },
  { id: "deepseek/v3", label: "DeepSeek V3 ($0.27/$1.1)" },
  { id: "deepseek/r1", label: "DeepSeek R1 ($0.55/$2.2)" },
  { id: "mistral/codestral-2501", label: "Codestral ($0.3/$0.9)" },
  { id: "cerebras/llama-3.3-70b", label: "Llama 70B Cerebras ($0.6)" },
  { id: "groq/llama-3.3-70b", label: "Llama 70B Groq ($0.6)" },
  { id: "openrouter/kimi-k2.5", label: "Kimi K2.5 ($1/$4)" },
  { id: "openrouter/swe-1.5", label: "SWE-1.5 ($0.8)" },
  { id: "openrouter/step-3.5-flash:free", label: "Step 3.5 Flash (free)" },
  { id: "openrouter/nemotron-3-nano-30b-a3b:free", label: "Nemotron 3 Nano 30B (free)" },
  { id: "openrouter/gpt-oss-120b", label: "GPT-OSS 120B ($0.04/$0.19)" },
  { id: "openrouter/qwen3-235b-a22b-2507", label: "Qwen3 235B ($0.07/$0.10)" },
  { id: "ollama/qwen2.5-coder-7b", label: "Qwen 7B (local, free)" },
  { id: "ollama/qwen2.5-coder-3b", label: "Qwen 3B (local, free)" },
];
const REGISTRY_MODEL_IDS = REGISTRY_MODELS.map(m => m.id);

function ToolCard({ tool, isSelected, onSelect, onRefresh }) {
  const catClass = CATEGORY_COLORS[tool.category] || CATEGORY_COLORS.custom;
  
  const handleCardClick = () => {
    onSelect(tool.name);
  };

  const handleModelChange = async (e) => {
    e.stopPropagation();
    const newModel = e.target.value;
    await put(`/dashboard/tools/${tool.name}`, { default_model: newModel });
    if (onRefresh) onRefresh();
  };

  return (
    <div
      onClick={handleCardClick}
      className={`bg-white border rounded-lg p-4 hover:shadow-sm transition-shadow text-left w-full cursor-pointer ${
        isSelected ? 'border-blue-400 bg-blue-50' : 'border-gray-200'
      }`}
      role="button"
      tabIndex={0}
      aria-pressed={isSelected}
      aria-label={`Tool ${tool.name}${isSelected ? ' (selected)' : ''}: ${tool.description}`}
    >
      <div className="flex items-center justify-between mb-2">
        <div className="flex items-center gap-2">
          <span className="font-semibold text-gray-900">{tool.name}</span>
          <span className={`text-xs px-2 py-0.5 rounded-full ${catClass}`}>
            {CATEGORY_LABELS[tool.category] || tool.category}
          </span>
        </div>
        <StatusBadge ok={tool.available} label={tool.available ? "Available" : "Not found"} />
      </div>
      <p className="text-sm text-gray-500 mb-2">{tool.description}</p>
      <div className="flex flex-wrap gap-1">
        {tool.capabilities?.map(cap => (
          <span key={cap} className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded">
            {cap.replaceAll("_", " ")}
          </span>
        ))}
      </div>
      {tool.modes?.length > 0 && (
        <div className="mt-2 flex gap-1">
          <span className="text-xs text-gray-400">Modes:</span>
          {tool.modes.map(m => (
            <span key={m} className="text-xs bg-indigo-50 text-indigo-600 px-1.5 py-0.5 rounded">{m}</span>
          ))}
        </div>
      )}
      {tool.name !== "human" && (
        <div className="mt-2 flex items-center gap-2">
          <span className="text-xs text-gray-400">LLM:</span>
          <select
            value={tool.default_model || ""}
            onChange={handleModelChange}
            onClick={(e) => e.stopPropagation()}
            className="text-xs px-1.5 py-0.5 rounded border border-orange-200 bg-orange-50 text-orange-700 cursor-pointer"
            title="Default LLM model alias for this tool"
          >
            <option value="">— none —</option>
            {REGISTRY_MODELS.map(m => (
              <option key={m.id} value={m.id}>{m.label}</option>
            ))}
          </select>
          {tool.default_model && !REGISTRY_MODEL_IDS.includes(tool.default_model) && (
            <span className="text-[10px] text-orange-500 truncate max-w-[120px]" title={tool.default_model}>
              {tool.default_model}
            </span>
          )}
        </div>
      )}
      {tool.environment && (
        <div className="mt-2 space-y-1">
          <div className="flex flex-wrap gap-1">
            <span className="text-xs bg-emerald-50 text-emerald-700 px-2 py-0.5 rounded border border-emerald-100">
              env: {tool.environment.name}
            </span>
            <span className="text-xs bg-emerald-50 text-emerald-600 px-2 py-0.5 rounded border border-emerald-100">
              {tool.environment.kind?.replace("_", " ")}
            </span>
          </div>
          {tool.environment.target && (
            <div className="text-[11px] text-emerald-600 truncate" title={tool.environment.target}>
              {tool.environment.target}
            </div>
          )}
          {(tool.environment.tool_instance_name || tool.environment.tool_instance) && (
            <div className="flex flex-wrap gap-1">
              <span className="text-xs bg-blue-50 text-blue-700 px-2 py-0.5 rounded border border-blue-100">
                instance: {tool.environment.tool_instance_name || tool.environment.tool_instance?.name || "—"}
              </span>
              {tool.environment.tool_instance?.kind && (
                <span className="text-xs bg-blue-50 text-blue-600 px-2 py-0.5 rounded border border-blue-100">
                  {tool.environment.tool_instance.kind}
                </span>
              )}
            </div>
          )}
        </div>
      )}
      {tool.binary && (
        <div className="mt-1 text-xs text-gray-400">binary: <code className="bg-gray-50 px-1 rounded">{tool.binary}</code></div>
      )}
    </div>
  );
}
