import { useState, useEffect } from 'react' import { Brain, Trash2, ChevronDown, ChevronUp } from 'lucide-react' import { api } from '../utils/api' import { useAuth } from '../context/AuthContext' import Markdown from '../utils/Markdown' import UsageBadge from '../components/UsageBadge' import dayjs from 'dayjs' import 'dayjs/locale/de' dayjs.locale('de') // Legacy fallback labels (display_name takes precedence) const SLUG_LABELS = { pipeline: '🔬 Mehrstufige Gesamtanalyse' } function InsightCard({ ins, onDelete, defaultOpen=false, prompts=[] }) { const [open, setOpen] = useState(defaultOpen) // Find matching prompt to get display_name const prompt = prompts.find(p => p.slug === ins.scope) const displayName = prompt?.display_name || SLUG_LABELS[ins.scope] || ins.scope return (
setOpen(o=>!o)}>
{displayName}
{dayjs(ins.created).format('DD. MMMM YYYY, HH:mm')}
{open ? : }
{open && }
) } export default function Analysis() { const { canUseAI } = useAuth() const [prompts, setPrompts] = useState([]) const [allInsights, setAllInsights] = useState([]) const [loading, setLoading] = useState(null) const [error, setError] = useState(null) const [tab, setTab] = useState('run') const [newResult, setNewResult] = useState(null) const [aiUsage, setAiUsage] = useState(null) const loadAll = async () => { const [p, i] = await Promise.all([ api.listPrompts(), api.listInsights() ]) setPrompts(Array.isArray(p)?p:[]) setAllInsights(Array.isArray(i)?i:[]) } useEffect(()=>{ loadAll() // Load feature usage for badges api.getFeatureUsage().then(features => { const aiFeature = features.find(f => f.feature_id === 'ai_calls') setAiUsage(aiFeature) }).catch(err => console.error('Failed to load usage:', err)) },[]) const runPrompt = async (slug) => { setLoading(slug); setError(null); setNewResult(null) try { // Use new unified executor with save=true const result = await api.executeUnifiedPrompt(slug, null, null, false, true) // Transform result to match old format for InsightCard let content = '' if (result.type === 'pipeline') { // For pipeline, extract final output const finalOutput = result.output || {} if (typeof finalOutput === 'object' && Object.keys(finalOutput).length === 1) { content = Object.values(finalOutput)[0] } else { content = JSON.stringify(finalOutput, null, 2) } } else { // For base prompts, use output directly content = typeof result.output === 'string' ? result.output : JSON.stringify(result.output, null, 2) } setNewResult({ scope: slug, content }) await loadAll() setTab('run') } catch(e) { setError('Fehler: ' + e.message) } finally { setLoading(null) } } const deleteInsight = async (id) => { if (!confirm('Analyse löschen?')) return const pid = localStorage.getItem('bodytrack_active_profile')||'' await fetch(`/api/insights/${id}`, { method:'DELETE', headers: pid ? {'X-Profile-Id':pid} : {} }) if (newResult?.id === id) setNewResult(null) await loadAll() } // Group insights by scope for history view const grouped = {} allInsights.forEach(ins => { const key = ins.scope || 'sonstige' grouped[key] = grouped[key] || [] grouped[key].push(ins) }) // Show only active pipeline-type prompts const pipelinePrompts = prompts.filter(p => p.active && p.type === 'pipeline') return (

KI-Analyse

{error && (
{error.includes('nicht aktiviert') || error.includes('Limit') ? <>🔒 KI-Zugang eingeschränkt
Dein Profil hat keinen Zugang zu KI-Analysen oder das Tageslimit wurde erreicht. Bitte den Admin kontaktieren. : error}
)} {/* ── Analysen starten ── */} {tab==='run' && (
{/* Fresh result shown immediately */} {newResult && (
✅ Neue Analyse erstellt:
)} {!canUseAI && (
🔒 KI-Analysen nicht freigeschaltet
Dein Profil hat keinen Zugang zu KI-Analysen. Bitte den Admin bitten, KI für dein Profil zu aktivieren (Einstellungen → Admin → Profil bearbeiten).
)} {canUseAI && pipelinePrompts.length > 0 && (

Wähle eine mehrstufige KI-Analyse:

)} {pipelinePrompts.map(p => { const existing = allInsights.find(i=>i.scope===p.slug) return (
{p.display_name || SLUG_LABELS[p.slug] || p.name} {aiUsage && }
{p.description && (
{p.description}
)} {existing && (
Letzte Analyse: {dayjs(existing.created).format('DD.MM.YYYY, HH:mm')}
)}
{/* Show existing result collapsed */} {existing && newResult?.id !== existing.id && (
)}
) })} {canUseAI && pipelinePrompts.length === 0 && (

Keine aktiven Pipeline-Prompts verfügbar.

Erstelle Pipeline-Prompts im Admin-Bereich (Einstellungen → Admin → KI-Prompts).

)}
)} {/* ── Verlauf gruppiert ── */} {tab==='history' && (
{allInsights.length===0 ?

Noch keine Analysen

: Object.entries(grouped).map(([scope, ins]) => (
{prompts.find(p => p.slug === scope)?.display_name || SLUG_LABELS[scope] || scope} ({ins.length})
{ins.map(i => )}
)) }
)}
) }