'use client'

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

// Customer "Dokumente" view: lists ONLY published legal documents (the
// ready-to-use output), never templates or drafts. Backed by
// GET /api/sdk/v1/legal-documents/public (published-only, tenant-scoped).

export interface PublishedDoc {
  id: string
  type: string
  name: string
  version: number
  title: string
  content: string
  language: string
  published_at: string | null
}

// Human-readable German labels for the known document types. Internal type keys
// are never shown to the customer — only this Klartext.
const TYPE_LABEL: Record<string, string> = {
  impressum: 'Impressum',
  privacy_policy: 'Datenschutzerklärung',
  datenschutz: 'Datenschutzerklärung',
  dse: 'Datenschutzerklärung',
  agb: 'AGB',
  terms_of_service: 'Nutzungsbedingungen',
  widerruf: 'Widerrufsbelehrung',
  cookie_policy: 'Cookie-Richtlinie',
  cookie_banner: 'Cookie-Banner-Text',
  dpa: 'Auftragsverarbeitungsvertrag (AVV)',
  nda: 'Geheimhaltungsvereinbarung (NDA)',
  sla: 'Service-Level-Agreement (SLA)',
  legal_notice: 'Rechtlicher Hinweis',
}

export function docLabel(type: string): string {
  return TYPE_LABEL[type] || type.replace(/_/g, ' ')
}

export function useDokumente() {
  const [docs, setDocs] = useState<PublishedDoc[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const load = useCallback(() => {
    setLoading(true)
    setError(null)
    fetch('/api/sdk/v1/legal-documents/public')
      .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
      .then((data: PublishedDoc[]) => setDocs(Array.isArray(data) ? data : []))
      .catch((e) => setError(String(e?.message || e)))
      .finally(() => setLoading(false))
  }, [])

  useEffect(() => { load() }, [load])

  return { docs, loading, error, reload: load }
}

// Trigger a client-side download of a document's content as a .md file.
export function downloadDoc(doc: PublishedDoc): void {
  const safe = (doc.title || docLabel(doc.type) || 'dokument')
    .replace(/[^\w\-äöüÄÖÜß ]/g, '').trim().replace(/\s+/g, '_')
  const blob = new Blob([doc.content || ''], { type: 'text/markdown;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${safe || 'dokument'}_v${doc.version}.md`
  document.body.appendChild(a)
  a.click()
  a.remove()
  URL.revokeObjectURL(url)
}
