import { useState } from 'react'

export default function TagEditor({ tags, onChange }) {
  const [input, setInput] = useState('')

  const add = () => {
    const tag = input.trim().toLowerCase()
    setInput('')
    if (tag && !tags.includes(tag)) onChange([...tags, tag])
  }

  return (
    <div className="tag-editor">
      {tags.map((tag) => (
        <span key={tag} className="chip">
          {tag}
          <button
            type="button"
            onClick={() => onChange(tags.filter((t) => t !== tag))}
            title="Remove tag"
          >
            ×
          </button>
        </span>
      ))}
      <input
        value={input}
        placeholder="add tag…"
        maxLength={40}
        onChange={(e) => setInput(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' || e.key === ',') {
            e.preventDefault()
            add()
          }
        }}
        onBlur={add}
      />
    </div>
  )
}
