// karm.dev — FormField (text input, textarea, select)
// Elegant input w/ focus + error + success states.

function FormField({
  label,
  type = 'text',
  placeholder,
  value,
  onChange,
  error,
  success,
  children, // for select options
  as = 'input', // 'input' | 'textarea' | 'select'
  ...props
}) {
  const [focused, setFocused] = React.useState(false);
  const state = error ? 'is-error' : success ? 'is-success' : focused ? 'is-focused' : '';

  const common = {
    className: `form-input ${state}`,
    value, onChange,
    onFocus: () => setFocused(true),
    onBlur: () => setFocused(false),
    placeholder,
    ...props,
  };

  return (
    <div className="form-group">
      {label && <label className="form-label">{label}</label>}
      {as === 'textarea' ? (
        <textarea rows={4} {...common} />
      ) : as === 'select' ? (
        <select {...common}>{children}</select>
      ) : (
        <input type={type} {...common} />
      )}
      {error && <p className="form-feedback is-error">✕ {error}</p>}
      {success && <p className="form-feedback is-success">✓ {success}</p>}
    </div>
  );
}

window.FormField = FormField;
