import { useState } from 'react'

interface CodeBlockProps {
  code: string
  /** Small label shown in the bar, e.g. "curl" or "python". */
  label?: string
}

/**
 * A monospace code block on the second neutral surface with a copy-to-clipboard
 * affordance. Wide lines scroll horizontally inside the block so the page never does.
 */
export default function CodeBlock({ code, label }: CodeBlockProps) {
  const [copied, setCopied] = useState(false)

  async function copy() {
    try {
      await navigator.clipboard.writeText(code)
      setCopied(true)
      window.setTimeout(() => setCopied(false), 1600)
    } catch {
      setCopied(false)
    }
  }

  return (
    <figure className="codeblock">
      <div className="codeblock-bar">
        {label && <span className="codeblock-label">{label}</span>}
        <button
          type="button"
          className="codeblock-copy"
          onClick={copy}
          aria-label={copied ? 'Copied to clipboard' : 'Copy to clipboard'}
        >
          {copied ? 'Copied' : 'Copy'}
        </button>
      </div>
      <pre className="codeblock-pre">
        <code>{code}</code>
      </pre>
    </figure>
  )
}
