"use client"; import { useEffect, useMemo, useState, useRef, useCallback } from "react"; import toast from "react-hot-toast"; import { SiOpenai, SiAnthropic, SiGooglegemini, SiPerplexity, SiX, SiOllama, SiNvidia } from "react-icons/si"; import { Zap, Users, Flame, Network, Brain, Layers, Monitor, Settings2, Cpu, Wind } from "lucide-react"; import type { ProviderPreset } from "@/lib/types"; export type ProviderSelection = { providerId: string; baseUrl: string; model: string; apiKey: string; }; type LoadedModelsState = | { status: "idle"; models: string[] } | { status: "loading"; models: string[] } | { status: "loaded"; models: string[] } | { status: "error"; models: string[]; message: string }; function uniqSorted(values: string[]) { return [...new Set(values.filter(Boolean))].sort((a, b) => a.localeCompare(b)); } function parseModelIds(json: any): string[] { const data = json?.data; if (Array.isArray(data)) { return uniqSorted( data .map((x) => (typeof x?.id === "string" ? x.id : typeof x?.name === "string" ? x.name : "")) .filter(Boolean) ); } if (Array.isArray(json?.models)) { return uniqSorted( json.models .map((x: any) => (typeof x?.id === "string" ? x.id : typeof x?.name === "string" ? x.name : "")) .filter(Boolean) ); } return []; } // Map provider IDs to React components const PROVIDER_ICONS: Record = { openai: SiOpenai, anthropic: SiAnthropic, gemini: SiGooglegemini, mistral: Wind, // Mistral = Wind groq: Zap, // Groq = Fast together: Users, // Together = Users/Handshake fireworks: Flame, openrouter: Network, perplexity: SiPerplexity, deepseek: Brain, cohere: Layers, // Cohere = Layers/Embeddings xai: SiX, ollama: SiOllama, lmstudio: Monitor, custom: Settings2 }; // Fallback icon if ID missing const DefaultIcon = Cpu; export function ProviderSelector({ presets, value, onChange }: { presets: ProviderPreset[]; value: ProviderSelection; onChange: (next: ProviderSelection) => void; }) { const preset = presets.find((p) => p.id === value.providerId) ?? presets[0]!; const isCustom = preset.id === "custom"; const modelsUrl = useMemo(() => { const base = value.baseUrl.trim(); if (!base) return ""; return `${base.replace(/\/$/, "")}/models`; }, [value.baseUrl]); const [loadedModels, setLoadedModels] = useState({ status: "idle", models: [] }); const [showModels, setShowModels] = useState(false); const scrollRef = useRef(null); const [isDragging, setIsDragging] = useState(false); const [startX, setStartX] = useState(0); const [scrollLeft, setScrollLeft] = useState(0); const autoScrollRef = useRef(null); // Edge hover auto-scroll const handleEdgeScroll = useCallback((e: React.MouseEvent) => { if (isDragging || !scrollRef.current) return; const container = scrollRef.current; const rect = container.getBoundingClientRect(); const mouseX = e.clientX - rect.left; const containerWidth = rect.width; const edgeZone = 80; // pixels from edge to trigger scroll // Clear any existing animation if (autoScrollRef.current) { cancelAnimationFrame(autoScrollRef.current); autoScrollRef.current = null; } let scrollSpeed = 0; if (mouseX < edgeZone) { // Left edge - scroll left, speed based on proximity scrollSpeed = -((edgeZone - mouseX) / edgeZone) * 8; } else if (mouseX > containerWidth - edgeZone) { // Right edge - scroll right, speed based on proximity scrollSpeed = ((mouseX - (containerWidth - edgeZone)) / edgeZone) * 8; } if (scrollSpeed !== 0) { const scroll = () => { if (scrollRef.current) { scrollRef.current.scrollLeft += scrollSpeed; autoScrollRef.current = requestAnimationFrame(scroll); } }; autoScrollRef.current = requestAnimationFrame(scroll); } }, [isDragging]); const handleMouseLeaveCarousel = useCallback(() => { if (autoScrollRef.current) { cancelAnimationFrame(autoScrollRef.current); autoScrollRef.current = null; } }, []); // Drag to scroll handlers const handleMouseDown = useCallback((e: React.MouseEvent) => { if (!scrollRef.current) return; handleMouseLeaveCarousel(); // Stop edge scrolling when dragging starts setIsDragging(true); setStartX(e.pageX - scrollRef.current.offsetLeft); setScrollLeft(scrollRef.current.scrollLeft); }, [handleMouseLeaveCarousel]); const handleMouseMove = useCallback((e: React.MouseEvent) => { if (isDragging && scrollRef.current) { e.preventDefault(); const x = e.pageX - scrollRef.current.offsetLeft; const walk = (x - startX) * 2; scrollRef.current.scrollLeft = scrollLeft - walk; } else { handleEdgeScroll(e); } }, [isDragging, startX, scrollLeft, handleEdgeScroll]); const handleMouseUp = useCallback(() => { setIsDragging(false); }, []); // Navigation arrows const scrollToDirection = useCallback((direction: "left" | "right") => { if (!scrollRef.current) return; const scrollAmount = 200; scrollRef.current.scrollBy({ left: direction === "left" ? -scrollAmount : scrollAmount, behavior: "smooth" }); }, []); async function loadModels({ silent }: { silent?: boolean } = {}) { if (!modelsUrl) return; setLoadedModels((s) => ({ status: "loading", models: s.models })); try { const headers: Record = {}; if (preset.apiKind === "anthropic-messages") { if (value.apiKey.trim()) headers["x-api-key"] = value.apiKey.trim(); headers["anthropic-version"] = "2023-06-01"; } else { if (value.apiKey.trim()) headers.Authorization = `Bearer ${value.apiKey.trim()}`; } const res = await fetch(modelsUrl, { headers, method: "GET" }); const text = await res.text(); if (!res.ok) throw new Error(text || `Model list failed (${res.status}).`); const json = JSON.parse(text) as any; const models = parseModelIds(json); if (models.length === 0) throw new Error("No models returned."); setLoadedModels({ status: "loaded", models }); if (!value.model.trim()) onChange({ ...value, model: models[0]! }); if (!silent) toast.success(`Loaded ${models.length} models.`); } catch (error) { const message = error instanceof Error ? error.message : "Failed to load models."; if (silent) { setLoadedModels((s) => ({ status: s.models.length ? "loaded" : "idle", models: s.models })); return; } setLoadedModels((s) => ({ status: "error", models: s.models, message })); toast.error(message); } } // Auto-load models when API key is provided useEffect(() => { if (isCustom) return; if (!modelsUrl) return; if (loadedModels.status === "loaded" && loadedModels.models.length) return; if (!value.apiKey.trim()) return; const id = setTimeout(() => { void loadModels({ silent: true }); }, 800); return () => clearTimeout(id); // eslint-disable-next-line react-hooks/exhaustive-deps }, [value.apiKey, value.providerId]); // Scroll to active provider on mount useEffect(() => { if (scrollRef.current) { const activeEl = scrollRef.current.querySelector('[data-active="true"]'); if (activeEl) { activeEl.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' }); } } }, []); const ActiveIcon = PROVIDER_ICONS[preset.id] || DefaultIcon; return (
{/* Header with navigation */}
Select Provider
{/* Horizontal Scrolling Provider Carousel */}
{ handleMouseUp(); handleMouseLeaveCarousel(); }} className={`flex gap-3 overflow-x-auto pb-2 scroll-smooth ${isDragging ? 'cursor-grabbing select-none' : 'cursor-grab'}`} style={{ scrollbarWidth: 'none', msOverflowStyle: 'none', WebkitOverflowScrolling: 'touch' }} > {presets.map((p) => { const isActive = p.id === value.providerId; const Icon = PROVIDER_ICONS[p.id] || DefaultIcon; return ( ); })}
{/* Configuration Panel */}
{preset.name}
{/* Top Row: API Key & Base URL */}
{/* API Key */}
onChange({ ...value, apiKey: e.target.value })} autoComplete="off" />
{/* Base URL */}
onChange({ ...value, baseUrl: e.target.value })} disabled={!isCustom && Boolean(preset.baseUrl)} placeholder="https://api.example.com/v1" />
{/* Model Selection Row */}
{modelsUrl && ( )}
onChange({ ...value, model: e.target.value })} onFocus={() => setShowModels(true)} onBlur={() => setTimeout(() => setShowModels(false), 200)} placeholder={preset.defaultModel || "Enter model name..."} /> {/* Dropdown for models */} {showModels && loadedModels.models.length > 0 && (
{loadedModels.models .filter(m => m.toLowerCase().includes(value.model.toLowerCase())) .slice(0, 12) .map((model) => ( ))}
)}

{preset.browserNotes}

); }