'use client' import { useCallback, useState } from 'react' import type { AdvisorTurn } from './useAdvisorStream' function esc(s: string): string { return s .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') } function sourcesHtml(turn: AdvisorTurn): string { if (turn.meta.sources.length === 0) return '' const items = turn.meta.sources .map((s) => { const hier = [s.section, s.subsection, s.paragraph, s.footnoteRef].filter(Boolean).join(' › ') return `
  • ${esc(s.regulation.short || '')}${hier ? ` — ${esc(hier)}` : ''}
  • ` }) .join('') return `

    Quellen:

    ` } /** Sends the consultation transcript (question + answer + structured sources) as an email to the DSB. */ export function useAdvisorEmail(turns: AdvisorTurn[], country: string, currentStep: string) { const [sending, setSending] = useState(false) const [sent, setSent] = useState(false) const send = useCallback(async () => { if (turns.length === 0 || sending) return setSending(true) try { const qaHtml = turns .map( (t) => `

    Frage: ${esc( t.question, )}

    ${esc(t.answer)}

    ${sourcesHtml(t)}
    `, ) .join('') const bodyHtml = `

    Compliance Advisor — Beratungsprotokoll

    Datum: ${esc(new Date().toLocaleString('de-DE'))} | Land: ${esc(country)} | Kontext: ${esc(currentStep)}


    ${qaHtml}

    Automatisch erstellt vom BreakPilot Compliance Advisor

    ` await fetch('/api/sdk/v1/agent/notify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ recipient: 'dsb@breakpilot.local', subject: `Compliance Advisor — ${turns.length} Fragen (${currentStep})`, body_html: bodyHtml, role: 'Datenschutzbeauftragter', }), }) setSent(true) setTimeout(() => setSent(false), 3000) } catch (e) { console.error('Email send failed:', e) } finally { setSending(false) } }, [turns, sending, country, currentStep]) return { send, sending, sent } }