// frontend/src/modals/melodies/CodeSnippetModal.jsx
// Shows the C++ PROGMEM firmware code snippet for a single archetype.

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

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 CodeSnippetModal({ archetype, onClose }) {
  const [copied, setCopied] = useState(false)

  const handleCopy = () => {
    copyText(archetype?.progmem_code || '', () => {
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    })
  }

  return (
    <Modal
      open={Boolean(archetype)}
      onClose={onClose}
      title="Firmware Code Snippet"
      subtitle={archetype ? `${archetype.name} · PID: ${archetype.pid || '—'}` : ''}
      size="lg"
      footer={
        <>
          <Button variant="secondary" onClick={onClose}>Close</Button>
          <Button variant={copied ? 'success' : 'secondary'} onClick={handleCopy}>
            {copied ? 'Copied!' : 'Copy Code'}
          </Button>
        </>
      }
    >
      <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: '60vh',
        lineHeight: 1.6,
      }}>
        {archetype?.progmem_code || ''}
      </pre>
    </Modal>
  )
}
