'use client'

/**
 * Snapshot-Detail — öffnet einen gespeicherten Check aus der Historie und
 * zeigt die Ergebnis-Views aus den Rohdaten (kein Re-Crawl). Aktuell:
 * Cookie-Auswertung. Impressum/AGB/… folgen als weitere Module hier.
 */

import React, { use as useUnwrap, useEffect, useState } from 'react'
import Link from 'next/link'

import { CookieLibraryPanel } from '../../_components/CookieLibraryPanel'
import { CookieResultView } from '../../_components/CookieResultView'

export default function SnapshotDetail(
  { params }: { params: Promise<{ snapshotId: string }> },
) {
  const { snapshotId } = useUnwrap(params)
  const [snap, setSnap] = useState<any>(null)
  const [check, setCheck] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    fetch(`/api/sdk/v1/agent/snapshots/${snapshotId}`)
      .then(r => r.json())
      .then(d => {
        if (cancelled) return
        if (d?.error) setError(d.error)
        else setSnap(d)
      })
      .catch(e => { if (!cancelled) setError(String(e)) })
      .finally(() => { if (!cancelled) setLoading(false) })
    return () => { cancelled = true }
  }, [snapshotId])

  // Library-Abgleich einmal laden (Findings + cookie_categories für beide Views).
  useEffect(() => {
    let cancelled = false
    fetch(`/api/sdk/v1/agent/snapshots/${snapshotId}/cookie-check`)
      .then(r => r.json())
      .then(d => { if (!cancelled) setCheck(d) })
      .catch(() => { if (!cancelled) setCheck(null) })
    return () => { cancelled = true }
  }, [snapshotId])

  const hasCookies = (snap?.cmp_vendors?.length ?? 0) > 0

  return (
    <div className="p-6 max-w-6xl space-y-4">
      <Link href="/sdk/agent/snapshots" className="text-xs text-blue-700 hover:underline">
        ‹ Zurück zur Historie
      </Link>
      {loading ? (
        <div className="text-sm text-gray-500">Lade Snapshot…</div>
      ) : error || !snap ? (
        <div className="text-sm text-red-600">Snapshot nicht gefunden.</div>
      ) : hasCookies ? (
        <>
          <CookieLibraryPanel snapshotId={snapshotId} data={check ?? undefined} />
          <CookieResultView snapshot={snap} cookieCategories={check?.cookie_categories} />
        </>
      ) : (
        <div className="text-sm text-gray-500">
          Dieser Snapshot enthält keine Cookie-/Vendor-Daten.
        </div>
      )}
    </div>
  )
}
