import { useState } from 'react'
import styles from './CodeBlock.module.css'

interface CodeBlockProps {
  content: string
  language?: string
  copyable?: boolean
  lineNumbers?: boolean
  className?: string
}

export function CodeBlock({
  content,
  language = 'text',
  copyable = false,
  lineNumbers = false,
  className,
}: CodeBlockProps) {
  const [copied, setCopied] = useState(false)

  let formatted = content
  if (language === 'json') {
    try {
      formatted = JSON.stringify(JSON.parse(content), null, 2)
    } catch {
      // invalid JSON — show as-is
    }
  }

  const lines = formatted.split('\n')

  function handleCopy() {
    navigator.clipboard.writeText(formatted).then(() => {
      setCopied(true)
      setTimeout(() => setCopied(false), 1500)
    })
  }

  return (
    <div className={`${styles.wrapper} ${className ?? ''}`}>
      {copyable && (
        <button
          className={styles.copyBtn}
          onClick={handleCopy}
          aria-label="Copy code"
        >
          {copied ? 'Copied!' : 'Copy'}
        </button>
      )}
      <pre className={styles.pre}>
        {lineNumbers
          ? lines.map((line, i) => (
              <span key={i} className={styles.line}>
                <span className={styles.lineNum}>{i + 1}</span>
                {line + (i < lines.length - 1 ? '\n' : '')}
              </span>
            ))
          : formatted}
      </pre>
    </div>
  )
}
