'use client'

// DownloadMdButton — download grill_md of plan_md als .md-bestand.
// Demo MAG downloaden (read-only). Server-action returnt md-string; client
// bouwt een Blob + anchor + click().

import { useTransition } from 'react'
import { Download } from 'lucide-react'
import { toast } from 'sonner'

import { Button } from '@/components/ui/button'
import { debugProps } from '@/lib/debug'
import { downloadIdeaMdAction } from '@/actions/ideas'

interface Props {
  ideaId: string
  kind: 'grill' | 'plan'
  hasContent: boolean
}

export function DownloadMdButton({ ideaId, kind, hasContent }: Props) {
  const [pending, startTransition] = useTransition()

  function handleClick() {
    startTransition(async () => {
      const r = await downloadIdeaMdAction(ideaId, kind)
      if ('error' in r) {
        toast.error(r.error)
        return
      }
      if (!r.data) return
      const blob = new Blob([r.data.markdown], { type: 'text/markdown;charset=utf-8' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = r.data.filename
      document.body.appendChild(a)
      a.click()
      a.remove()
      URL.revokeObjectURL(url)
    })
  }

  return (
    <Button
      size="sm"
      variant="ghost"
      onClick={handleClick}
      disabled={pending || !hasContent}
      title={hasContent ? `Download ${kind}_md` : 'Geen content'}
      {...debugProps('download-md-button', 'DownloadMdButton', 'components/ideas/download-md-button.tsx')}
    >
      <Download className="size-3.5 mr-1" />
      .md
    </Button>
  )
}
