'use client'

// Export controls for the comparison detail page (KAR-840 export layer).
// tdd-guard:skip — thin composition of the unit-tested export-utils with
// window/DOM APIs (print, querySelector, blob download); no own logic.

import { useState } from 'react'
import { AlertTriangle, Download, FileJson, Printer } from 'lucide-react'
import {
  buildViewModelExport,
  withContentHash,
  downloadJson,
  exportFilename,
  exportSectionPng,
  type ViewModelExportInput,
} from './export-utils'

const BTN =
  'inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-xs text-muted-foreground hover:text-foreground print:hidden'

/** Small per-section PNG download (targets the surrounding data-export-id).
 *  data-export-exclude keeps the button itself out of the snapshot. */
export function SectionPngButton({ exportId, partNumber }: { exportId: string; partNumber: string | null }) {
  const [state, setState] = useState<'idle' | 'busy' | 'error'>('idle')
  return (
    <button
      type="button"
      data-export-exclude
      className={`${BTN} float-right ${state === 'error' ? 'border-destructive text-destructive' : ''}`}
      disabled={state === 'busy'}
      title={state === 'error' ? 'Export fehlgeschlagen — erneut versuchen' : 'Sektion als PNG herunterladen'}
      onClick={async () => {
        const el = document.querySelector<HTMLElement>(`[data-export-id="${exportId}"]`)
        if (!el) return
        setState('busy')
        try {
          await exportSectionPng(el, exportFilename('png', partNumber, new Date(), exportId))
          setState('idle')
        } catch {
          setState('error')
          setTimeout(() => setState('idle'), 4000)
        }
      }}
    >
      {state === 'error' ? <AlertTriangle size={12} aria-hidden /> : <Download size={12} aria-hidden />}{' '}
      {state === 'error' ? 'Fehler' : 'PNG'}
    </button>
  )
}

/** Full view-model JSON download (V11 JSON-Export) + print-to-PDF. */
export function GlobalExportButtons({
  vm,
}: {
  vm: Omit<ViewModelExportInput, 'generatedAtIso'>
}) {
  return (
    <div className="flex items-center gap-2 print:hidden">
      <button
        type="button"
        className={BTN}
        title="Komplettes Ergebnis als JSON (identisch zur Ansicht)"
        onClick={async () => {
          // Der Inhalts-Hash läuft über das fertige Dokument und braucht die
          // asynchrone Web-Crypto-API — erst danach ist der Determinismus
          // belegt statt behauptet (R-19).
          const doc = await withContentHash(buildViewModelExport({ ...vm, generatedAtIso: new Date().toISOString() }))
          downloadJson(doc, exportFilename('json', vm.partNumber, new Date()))
        }}
      >
        <FileJson size={12} aria-hidden /> JSON
      </button>
      <button type="button" className={BTN} title="Druckansicht (PDF über den Browser-Dialog)" onClick={() => window.print()}>
        <Printer size={12} aria-hidden /> PDF
      </button>
    </div>
  )
}
