// frontend/src/modals/melodies/GenerateBuiltinModal.jsx
// Fetches and displays the generated C++ PROGMEM header for all is_builtin archetypes.

import { useState, useEffect } from 'react'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import Spinner from '@/components/ui/Spinner'

function fallbackCopy(text, onSuccess) {
  const ta = document.createElement('textarea')
  ta.value = text
  ta.style.cssText = 'position:fixed;top:0;left:0;opacity:0'
  document.body.appendChild(ta)
  ta.focus(); ta.select()
  try { document.execCommand('copy'); onSuccess?.() } catch (_) {}
  document.body.removeChild(ta)
}

function copyText(text, onSuccess) {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text).then(onSuccess).catch(() => fallbackCopy(text, onSuccess))
  } else {
    fallbackCopy(text, onSuccess)
  }
}

export default function GenerateBuiltinModal({ open, onClose }) {
  const [loading, setLoading] = useState(false)
  const [code, setCode]       = useState('')
  const [copied, setCopied]   = useState(false)
  const [error, setError]     = useState('')

  useEffect(() => {
    if (!open) { setCode(''); setCopied(false); setError(''); return }
    setLoading(true)
    const token = localStorage.getItem('access_token')
    fetch('/api/builder/melodies/generate-builtin-list', {
      headers: token ? { Authorization: `Bearer ${token}` } : {},
    })
      .then((r) => r.ok ? r.text() : r.text().then((t) => Promise.reject(t)))
      .then(setCode)
      .catch((e) => setError(String(e)))
      .finally(() => setLoading(false))
  }, [open])

  const handleCopy = () => {
    copyText(code, () => { setCopied(true); setTimeout(() => setCopied(false), 2000) })
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Generate Built-in List"
      subtitle="C++ PROGMEM header for all is_builtin archetypes"
      size="xl"
      footer={
        <>
          <Button variant="secondary" onClick={onClose}>Close</Button>
          {code && (
            <Button variant={copied ? 'success' : 'secondary'} onClick={handleCopy}>
              {copied ? 'Copied!' : 'Copy Code'}
            </Button>
          )}
        </>
      }
    >
      {loading && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'var(--space-16)' }}>
          <Spinner size="md" />
        </div>
      )}
      {error && (
        <div style={{
          padding: 'var(--space-4)',
          borderRadius: 'var(--radius-md)',
          backgroundColor: 'var(--color-danger-bg)',
          border: '1px solid var(--color-danger)',
          color: 'var(--color-danger)',
          fontSize: 'var(--font-size-sm)',
        }}>
          {error}
        </div>
      )}
      {!loading && !error && code && (
        <pre style={{
          margin: 0,
          padding: 'var(--space-4)',
          borderRadius: 'var(--radius-md)',
          backgroundColor: 'var(--color-bg-abyss)',
          border: '1px solid var(--color-border)',
          fontFamily: 'var(--font-family-mono)',
          fontSize: 'var(--font-size-sm)',
          color: 'var(--color-text-primary)',
          whiteSpace: 'pre',
          overflowX: 'auto',
          overflowY: 'auto',
          maxHeight: '65vh',
          lineHeight: 1.6,
        }}>
          {code}
        </pre>
      )}
    </Modal>
  )
}
