'use client'

/**
 * AgentModuleTab — generischer Snapshot-Modul-Tab für einen Doc-Type-Agenten
 * (Impressum, DSE, …). Lädt `/snapshots/{id}/{docType}-check` beim Mounten
 * (kein Re-Crawl) und rendert den AgentOutput im geteilten AgentResultTab.
 * Wird nur gemountet, wenn der Tab aktiv ist → Analyse läuft on-demand.
 */

import React, { useEffect, useState } from 'react'

import { AgentResultTab } from './AgentResultTab'

export function AgentModuleTab(
  { snapshotId, docType, label }:
  { snapshotId: string; docType: string; label: string },
) {
  const [data, setData] = useState<any>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    setLoading(true)
    fetch(`/api/sdk/v1/agent/snapshots/${snapshotId}/${docType}-check`)
      .then(r => r.json())
      .then(d => { if (!cancelled) setData(d) })
      .catch(() => {
        if (!cancelled) setData({ error: `${label}-Analyse fehlgeschlagen`, findings: [] })
      })
      .finally(() => { if (!cancelled) setLoading(false) })
    return () => { cancelled = true }
  }, [snapshotId, docType, label])

  if (loading) return <div className="text-sm text-gray-500">{label}-Analyse läuft…</div>
  if (data?.error) return <div className="text-sm text-red-600">{data.error}</div>
  if (data && ((data.findings?.length ?? 0) > 0 || (data.mc_coverage?.length ?? 0) > 0)) {
    return <AgentResultTab topicLabel={label} output={data} />
  }
  return (
    <div className="text-sm text-gray-500">
      {data?.notes || `Keine ${label}-Auswertung verfügbar.`}
    </div>
  )
}
