import { useState } from 'react'

// Renders a freshly generated batch of recovery codes ONCE, with copy + download.
// The backend never returns these again, so the copy stresses saving them now.
export default function RecoveryCodesDisplay({ codes, onDone }) {
  const [copied, setCopied] = useState(false)
  const text = (codes || []).join('\n')

  async function copy() {
    try {
      await navigator.clipboard.writeText(text)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    } catch {
      /* clipboard blocked — the codes are visible to copy manually */
    }
  }

  function download() {
    const blob = new Blob([`${text}\n`], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = 'recovery-codes.txt'
    a.click()
    URL.revokeObjectURL(url)
  }

  return (
    <div style={{ border: '1px solid var(--line)', borderRadius: 10, padding: 18, marginTop: 8 }}>
      <p className="sans" style={{ margin: '0 0 12px', color: 'var(--muted)', fontSize: '0.88rem', lineHeight: 1.6 }}>
        Save these recovery codes somewhere safe. Each can be used <strong>once</strong> to sign in if you
        lose your authenticator. <strong>They will not be shown again.</strong>
      </p>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))',
          gap: 8,
          fontFamily: 'monospace',
          fontSize: '0.95rem',
          marginBottom: 14,
        }}
      >
        {(codes || []).map((c) => (
          <div key={c} style={{ padding: '8px 10px', border: '1px solid var(--line-soft)', borderRadius: 6, letterSpacing: '0.06em', textAlign: 'center', color: 'var(--head)' }}>
            {c}
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
        <button onClick={copy} className="pill">{copied ? 'Copied!' : 'Copy'}</button>
        <button onClick={download} className="pill">Download</button>
        {onDone && (
          <button onClick={onDone} className="btn btn-primary btn-sq" style={{ marginLeft: 'auto' }}>
            I’ve saved them
          </button>
        )}
      </div>
    </div>
  )
}
