'use client'
import { useState } from 'react'

interface Props { onComplete: (pin: string) => void; label?: string; error?: string }

const KEYS = ['1','2','3','4','5','6','7','8','9','','0','⌫']

export default function PinInput({ onComplete, label = 'Enter your 4-digit PIN', error }: Props) {
  const [pin, setPin] = useState('')

  function press(key: string) {
    if (key === '⌫') { setPin(p => p.slice(0, -1)); return }
    if (!key) return
    const next = pin + key
    setPin(next)
    if (next.length === 4) { onComplete(next); setPin('') }
  }

  return (
    <div className="flex flex-col items-center w-full">
      <p className="text-[9px] font-black uppercase tracking-widest mb-5 text-center" style={{ color: '#555' }}>{label}</p>
      <div className="flex gap-4 mb-7">
        {[0,1,2,3].map(i => (
          <div key={i} className="w-4 h-4 rounded-full transition-all duration-150"
            style={{ background: i < pin.length ? '#c9a84c' : 'transparent', border: `1.5px solid ${i < pin.length ? '#c9a84c' : '#2a2a2a'}`, transform: i < pin.length ? 'scale(1.1)' : 'scale(1)' }} />
        ))}
      </div>
      {error && <p className="text-xs mb-4 px-4 py-2 rounded-xl text-center" style={{ color: '#c97070', background: '#1e0000' }}>{error}</p>}
      <div className="grid grid-cols-3 gap-3 w-full max-w-[260px]">
        {KEYS.map((key, i) => (
          <button key={i} onClick={() => press(key)} disabled={!key && key !== '0'}
            className="h-14 rounded-2xl text-lg font-bold transition-all active:scale-90"
            style={key === '⌫' ? { background: '#0d0d0d', color: '#444', border: '0.5px solid #1e1e1e' }
              : key === '' ? { visibility: 'hidden' }
              : { background: '#111', border: '0.5px solid #1e1e1e', color: '#e8e8e8' }}>
            {key}
          </button>
        ))}
      </div>
    </div>
  )
}
